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
//! Fully GPU-resident batched Arrow-Schur dense Cholesky solver.
//!
//! Implements the square-root Schur form: each local block `D_i = L_i L_i^T`
//! is factored on device, `u_i = L_i^{-1} g_i` and `Y_i = L_i^{-1} B_i` are
//! formed by triangular solves, the reduced shared system
//! `S_β = C + ρ_β I − Σ_i Y_i^T Y_i, r_β = -g_β + Σ_i Y_i^T u_i`
//! is assembled on device, factored once, and the back-substitution
//! `w_i = u_i + Y_i · δβ, L_i^T x_i = w_i, δt_i = -x_i`
//! is run on device. Only the final `(δt, δβ, log|H|)` triple is downloaded.
//!
//! The current caller (Arrow-Schur Newton step inside PIRLS) feeds uniform
//! local block size `d` and uniform shared width `k`, so the entire pipeline
//! is dispatched as a single p-group; per-p grouping for heterogenous blocks
//! is Layer D's NVRTC fused-kernel concern and lives in this module's
//! follow-up implementation rather than in policy plumbing.
//!
//! On non-Linux builds the entire module degrades to a CPU-fallback shim.
use ndarray::{Array1, Array2};
use crate::linalg::triangular::{CholeskyGuard, cholesky_factor_in_place, cholesky_solve_vector};
use crate::solver::arrow_schur::{ArrowSchurSystem, DeviceSaePcgData, PcgDiagnostics};
/// Outcome of a single Arrow-Schur Newton solve.
pub struct ArrowSchurGpuSolution {
pub delta_t: Array1<f64>,
pub delta_beta: Array1<f64>,
/// Natural log of the determinant of the full bordered Hessian, computed
/// from the local Cholesky factors and the Schur factor on device.
pub log_det_hessian: f64,
}
/// Reason a device path declined to run; lets the host caller decide between
/// CPU fallback and per-row escalation. `RidgeBumpRequired` carries the
/// estimated diagonal bump needed to clear the failed pivot.
#[derive(Debug, Clone)]
pub enum ArrowSchurGpuFailure {
/// CUDA runtime unavailable, allocation failed, or workload below policy.
Unavailable,
/// A row block was not positive definite even after the requested ridge.
/// Caller may retry with `ridge_t + bump`.
RidgeBumpRequired { row: usize, bump: f64 },
/// Shared Schur factor failed; bordered system is rank-deficient at the
/// requested ridges and the CPU path should handle escalation.
SchurFactorFailed { reason: String },
/// The system carries matrix-free `H_ββ` or per-row `H_tβ` operators that
/// the dense GPU Schur path cannot consume. The caller should route to CPU
/// `InexactPCG` (or supply dense buffers) rather than treating this as a
/// numerical failure. See `gpu/arrow_schur.rs` Part B for the planned GPU
/// PCG path that will lift this restriction at K ≥ 5000.
GpuRequiresDenseSystem {
had_hbb_matvec: bool,
had_htbeta_matvec: bool,
},
}
/// Safety-margin multiplier on `√(machine ε)` for the diagonal ridge bump
/// suggested when a local block fails Cholesky.
///
/// The estimated bump is `diag_scale · |pivot| · √ε · RIDGE_BUMP_EPS_MARGIN`.
/// A bare `diag_scale · √ε` ridge is the smallest perturbation that makes a
/// marginally-indefinite block PD in exact arithmetic, but a single retry at
/// that magnitude is routinely re-rejected by the next POTRF because the
/// rounding error of forming `D + ridge·I` and re-factoring is itself O(√ε).
/// The 1024× headroom (≈ 2¹⁰, i.e. ten extra bits below the f64 mantissa's
/// 52) clears the pivot on the first retry without materially perturbing the
/// curvature the Newton step sees. Shared by the per-row scalar path and the
/// batched-tile path so both suggest an identical bump.
const RIDGE_BUMP_EPS_MARGIN: f64 = 1024.0;
/// Entry point: attempt the fully device-resident Arrow-Schur Newton solve.
/// Returns `Err(ArrowSchurGpuFailure::Unavailable)` to indicate "device path
/// declined, fall back to CPU" — never panics.
pub fn solve_arrow_newton_step(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
// Detect matrix-free operators before any dim() checks so callers get a
// clear, actionable error instead of a generic SchurFactorFailed. The GPU
// dense-Schur path requires materialised H_ββ and per-row H_tβ slabs;
// CPU InexactPCG is the correct fallback when either operator is abstract.
let had_hbb_matvec = sys.hbb_matvec.is_some();
let had_htbeta_matvec = sys.htbeta_matvec.is_some();
if had_hbb_matvec || had_htbeta_matvec {
return Err(ArrowSchurGpuFailure::GpuRequiresDenseSystem {
had_hbb_matvec,
had_htbeta_matvec,
});
}
if sys.hbb.dim() != (k, k) {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "CUDA arrow-Schur requires a dense shared beta block".to_string(),
});
}
if n == 0 || d == 0 {
return Err(ArrowSchurGpuFailure::Unavailable);
}
if sys
.rows
.iter()
.any(|row| row.htt.dim() != (d, d) || row.htbeta.dim() != (d, k) || row.gt.len() != d)
{
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "row block dimension mismatch".to_string(),
});
}
#[cfg(not(target_os = "linux"))]
{
if ridge_t.is_nan() || ridge_beta.is_nan() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "ridge is NaN".to_string(),
});
}
Err(ArrowSchurGpuFailure::Unavailable)
}
#[cfg(target_os = "linux")]
{
// Multi-GPU: the arrow-Schur solve is row-block separable in its forward
// (per-row factor / whiten / partial-Schur) and backward (per-row
// back-sub) phases — only the small shared K×K reduce+factor+δβ is
// central. When more than one device is usable, split the WHOLE solve at
// row-block granularity across all GPUs. The POTRF stays fused with its
// dependent TRSM+GEMM on each tile's own stream, so no on-stream solve is
// orphaned. On `Unavailable` (one device, shape below policy, transient)
// fall through to the single-device fused / Layer-A paths below.
if crate::gpu::device_runtime::GpuRuntime::global()
.map(crate::gpu::device_runtime::GpuRuntime::device_count)
.unwrap_or(0)
> 1
{
match cuda::solve_multi_gpu(sys, ridge_t, ridge_beta) {
Ok(sol) => return Ok(sol),
Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump }) => {
return Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump });
}
Err(ArrowSchurGpuFailure::SchurFactorFailed { reason }) => {
return Err(ArrowSchurGpuFailure::SchurFactorFailed { reason });
}
// Unavailable / GpuRequiresDenseSystem: fall through to the
// single-device paths (already shape-validated above).
Err(_) => {}
}
}
// Layer D admission: when the system shape passes the
// (Σ p³ ≥ 1e5 OR R ≥ 16) heuristic and `p ≤ MAX_FUSED_P`, the fused
// NVRTC kernel replaces the cuSOLVER/cuBLAS Layer A+B+C path with a
// single per-row block. Layer C↔D parity (math block 3 §16 test 6)
// requires both paths to agree to 1e-10 on identical inputs.
if crate::gpu::kernels::arrow_schur_nvrtc::system_admits_fused_path(sys) {
match cuda::solve_fused(sys, ridge_t, ridge_beta) {
Ok(sol) => return Ok(sol),
// RidgeBumpRequired must surface to the outer escalation loop —
// the fused path's pivot diagnostic is identical in semantics
// to the cuSOLVER batched POTRF info code.
Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump }) => {
return Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump });
}
// Any other failure (Unavailable, SchurFactorFailed) falls
// through to the unfused path so a flaky NVRTC compile or
// shared-mem allocation does not abort the outer Newton step.
Err(_) => {}
}
}
cuda::solve(sys, ridge_t, ridge_beta)
}
}
/// Build the stacked column-major D buffer (n local d×d blocks), the stacked
/// stacked B buffer (n local d×k blocks), and the stacked g buffer
/// (n local d-vectors) consumed by the device pipeline. Each block is laid
/// out column-major so a single allocation + `cuMemcpyHtoD` reaches the
/// device without per-row dispatch overhead.
#[cfg(target_os = "linux")]
fn pack_host(sys: &ArrowSchurSystem, ridge_t: f64) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let mut d_buf = Vec::with_capacity(n * d * d);
let mut b_buf = Vec::with_capacity(n * d * k);
let mut g_buf = Vec::with_capacity(n * d);
for row in &sys.rows {
pack_block(row, ridge_t, d, k, &mut d_buf, &mut b_buf, &mut g_buf);
}
(d_buf, b_buf, g_buf)
}
#[cfg(target_os = "linux")]
#[inline]
fn pack_block(
row: &crate::solver::arrow_schur::ArrowRowBlock,
ridge_t: f64,
d: usize,
k: usize,
d_buf: &mut Vec<f64>,
b_buf: &mut Vec<f64>,
g_buf: &mut Vec<f64>,
) {
for col in 0..d {
for r in 0..d {
let mut value = row.htt[[r, col]];
if r == col {
value += ridge_t;
}
d_buf.push(value);
}
}
for col in 0..k {
for r in 0..d {
b_buf.push(row.htbeta[[r, col]]);
}
}
for r in 0..d {
g_buf.push(row.gt[r]);
}
}
/// Test-only entry that forces the Layer D + E fused NVRTC path regardless
/// of the admission heuristic. Used by the V100 Layer C↔D parity test to
/// drive the fused kernel at small shapes the heuristic would otherwise
/// route through the cuSOLVER/cuBLAS Layer A+B+C path.
#[doc(hidden)]
pub fn solve_arrow_newton_step_fused_force(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
if ridge_t.is_nan() || ridge_beta.is_nan() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "ridge is NaN".to_string(),
});
}
if crate::gpu::kernels::arrow_schur_nvrtc::plan_fused_launch(sys.rows.len(), sys.d, sys.k)
.is_none()
{
return Err(ArrowSchurGpuFailure::Unavailable);
}
#[cfg(not(target_os = "linux"))]
{
Err(ArrowSchurGpuFailure::Unavailable)
}
#[cfg(target_os = "linux")]
{
cuda::solve_fused(sys, ridge_t, ridge_beta)
}
}
/// #1017 Phase 3: a device-resident Arrow-Schur frame whose constant Hessian
/// blocks (`D = H_tt`, `B = H_tβ`, border `H_ββ`) and their factors stay on the
/// device across the inner Newton loop. Construct once per frozen gate/basis
/// frame, then call [`ResidentArrowFrameHandle::solve_gradient`] once per
/// iterate with the fresh residual gradient — only the `O(n·d + p)` gradient
/// crosses to the device and only `δ` crosses back, in contrast to
/// [`solve_arrow_newton_step`] which re-uploads and re-factors the full system
/// every call. On a non-CUDA host construction returns
/// `ArrowSchurGpuFailure::Unavailable`.
pub struct ResidentArrowFrameHandle {
#[cfg(target_os = "linux")]
inner: cuda::ResidentArrowFrame,
#[cfg(not(target_os = "linux"))]
_never: std::convert::Infallible,
}
impl ResidentArrowFrameHandle {
/// Upload the constant Hessian blocks and perform the one-time factor work.
pub fn new(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<Self, ArrowSchurGpuFailure> {
// The dense device path requires materialised blocks, same admission as
// `solve_arrow_newton_step`.
if sys.hbb_matvec.is_some() || sys.htbeta_matvec.is_some() {
return Err(ArrowSchurGpuFailure::GpuRequiresDenseSystem {
had_hbb_matvec: sys.hbb_matvec.is_some(),
had_htbeta_matvec: sys.htbeta_matvec.is_some(),
});
}
#[cfg(not(target_os = "linux"))]
{
if ridge_t.is_nan() || ridge_beta.is_nan() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "ridge is NaN".to_string(),
});
}
Err(ArrowSchurGpuFailure::Unavailable)
}
#[cfg(target_os = "linux")]
{
Ok(Self {
inner: cuda::ResidentArrowFrame::new(sys, ridge_t, ridge_beta)?,
})
}
}
/// Solve `H δ = −gradient` for a fresh gradient reusing the resident factors.
pub fn solve_gradient(
&self,
g_t: &[f64],
g_beta: &[f64],
) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
#[cfg(not(target_os = "linux"))]
{
if g_t.iter().chain(g_beta).any(|v| !v.is_finite()) {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "non-finite gradient entry".to_string(),
});
}
Err(ArrowSchurGpuFailure::Unavailable)
}
#[cfg(target_os = "linux")]
{
self.inner.solve_gradient(g_t, g_beta)
}
}
/// `log|H|` for the frame (constant; depends only on the factored Hessian).
#[must_use]
pub fn log_det_hessian(&self) -> f64 {
#[cfg(not(target_os = "linux"))]
{
// SAFETY: off-CUDA, `ResidentArrowFrameHandle::new` always returns
// `Err(Unavailable)`, so no handle of this type is ever constructed and
// this method is statically unreachable on non-Linux targets. A NaN
// sentinel would silently corrupt any consumer of the log-determinant,
// so fail loudly on the impossible path instead.
panic!("ResidentArrowFrameHandle cannot be constructed off CUDA")
}
#[cfg(target_os = "linux")]
{
self.inner.log_det_hessian()
}
}
}
/// Build a GPU-backed Schur matvec closure for CPU-driven PCG at K ≥ 5000.
///
/// Runs the fused NVRTC forward kernel once on the dense per-row `H_tβ` slabs
/// to compute `Y_i = L_i^{-1} H_tβ^(i)` for all rows, persists the `Y_i`
/// factors in a host-side buffer, and returns an `Arc<dyn Fn(...)>` closure
/// that computes the full Schur matvec
///
/// ```text
/// S·x = (H_ββ + ridge_beta·I)·x − Σ_i Y_i^T (Y_i·x)
/// ```
///
/// each time it is called. At K ≥ 5000 the `Σ_i Y_i^T (Y_i·x)` term
/// dominates over the host↔device transfer of the K-vector `x`, so the GPU
/// path is a clear win even with per-iteration transfer.
///
/// `H_ββ·x` is evaluated on the CPU using `sys.hbb_matvec` when present (the
/// matrix-free hook for SAE-manifold scale callers) or the dense `sys.hbb`
/// block otherwise. The `Y_i` term uses cuBLAS batched GEMV device-side; only
/// `x` (K doubles) and `out` (K doubles) cross the host↔device boundary per
/// PCG iteration.
///
/// Returns `Err(ArrowSchurGpuFailure::Unavailable)` if CUDA is unavailable or
/// the system shape is outside the fused kernel's admission range (e.g.
/// `d > MAX_FUSED_P = 32` or no CUDA context). Callers should fall back to CPU
/// `InexactPCG` on `Unavailable`.
///
/// Returns `Err(ArrowSchurGpuFailure::RidgeBumpRequired)` if a per-row Cholesky
/// factor failed at the requested `ridge_t`; the outer LM escalation should
/// bump `ridge_t` and retry.
///
/// # Composition with the matrix-free SAE Kronecker operator
///
/// When `sys.htbeta_matvec` is set (matrix-free `H_tβ` Kronecker operator),
/// the dense `H_tβ` slabs are absent — the dense forward kernel above cannot
/// run, and at `K = 100K` the dense `Y_i = L_i^{-1} H_tβ^(i)` (`d × K` per row)
/// could not be materialised anyway. Instead, `build_row_procedural_matvec`
/// returns a row-procedural Schur matvec: per row it gathers
/// `v_i = H_tβ^(i)·x` through the forward operator (sparse `O(m_i · p)`),
/// solves `(H_tt^(i) + ρ_t·I)^{-1} v_i` through a pre-computed per-row Cholesky
/// factor, and scatters `H_βt^(i)·w_i` through the sparse transpose operator
/// (`O(m_i · p)`, replacing the old `O(K)` column-probe). This is the
/// row-procedural `a_ik · Φ_k[i,m]` Kronecker apply over the active atoms only.
pub fn gpu_schur_matvec_backend(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<crate::solver::arrow_schur::GpuSchurMatvec, ArrowSchurGpuFailure> {
// Matrix-free H_tβ operator present: drive the row-procedural sparse
// Kronecker apply (active atoms only) instead of the dense forward kernel.
if sys.htbeta_matvec.is_some() {
return build_row_procedural_matvec(sys, ridge_t, ridge_beta);
}
#[cfg(not(target_os = "linux"))]
{
// No CUDA runtime on non-Linux. NaN ridges are validated to ensure the
// same contract as the Linux path.
if ridge_t.is_nan() || ridge_beta.is_nan() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
Err(ArrowSchurGpuFailure::Unavailable)
}
#[cfg(target_os = "linux")]
{
cuda::build_schur_matvec_backend(sys, ridge_t, ridge_beta)
}
}
/// Build a row-procedural reduced-Schur matvec for matrix-free SAE Kronecker
/// systems, eliminating the per-row latent block via cached per-row Cholesky
/// factors and applying the cross-block through the sparse forward/transpose
/// Kronecker operators (active atoms only).
///
/// The returned closure evaluates
/// `S·x = (H_ββ + ρ_β·I)·x − Σ_i H_βt^(i) (H_tt^(i) + ρ_t·I)^{-1} H_tβ^(i)·x`,
/// the same reduced Schur complement the dense path forms, but never
/// materialises the `d × K` cross-block `H_tβ^(i)`: the forward operator
/// (`out = H_tβ^(i)·x`) and transpose operator (`out += H_βt^(i)·v`) are the
/// sparse Kronecker gather/scatter from `SaeKroneckerRows`. The per-row factor
/// of `H_tt^(i) + ρ_t·I` is computed once when the closure is built and reused
/// across every CG iteration.
///
/// Returns `RidgeBumpRequired` if a per-row block is not positive definite at
/// the requested `ridge_t`; the outer LM escalation bumps `ridge_t` and retries.
fn build_row_procedural_matvec(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<crate::solver::arrow_schur::GpuSchurMatvec, ArrowSchurGpuFailure> {
use std::sync::Arc;
let n = sys.rows.len();
let k = sys.k;
let forward = sys
.htbeta_matvec
.clone()
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let transpose = sys.htbeta_transpose_matvec.clone().ok_or_else(|| {
// A forward operator without its sparse adjoint cannot be applied
// row-procedurally; this is a wiring error, surfaced as a Schur failure
// so the caller routes to the dense CPU path rather than misreporting a
// numerical bump.
ArrowSchurGpuFailure::SchurFactorFailed {
reason: "row-procedural Schur matvec requires htbeta_transpose_matvec; \
forward operator installed without its sparse adjoint"
.to_string(),
}
})?;
// Pre-factor each per-row block H_tt^(i) + ρ_t·I = L_i L_iᵀ on the host.
// The blocks are tiny (d_i ≲ 32) and the dense cross-block slabs are
// absent, so there is no device forward-kernel work to amortise here; the
// GPU win is the reduced K-system solve in `solve_reduced_beta_pcg`.
let mut factors: Vec<Array2<f64>> = Vec::with_capacity(n);
for (i, row) in sys.rows.iter().enumerate() {
let di = row.htt.nrows();
if row.htt.ncols() != di || row.gt.len() != di {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("row {i}: malformed H_tt block {:?}", row.htt.dim()),
});
}
let mut block = row.htt.clone();
for r in 0..di {
block[[r, r]] += ridge_t;
}
let factor = cholesky_factor_in_place(block.view(), CholeskyGuard::NonnegativePivot)
.ok_or_else(|| {
let scale = row
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
ArrowSchurGpuFailure::RidgeBumpRequired {
row: i,
bump: scale * f64::EPSILON.sqrt() * RIDGE_BUMP_EPS_MARGIN,
}
})?;
factors.push(factor);
}
// The SAE-manifold β-Hessian lives in the structured penalty operator
// (data-fit Gauss-Newton `G ⊗ I_p` + smoothness Kronecker blocks + any
// dense analytic-β residual), NOT in the dense `hbb` accumulator — for
// matrix-free systems `hbb` is zero/absent. Capture the effective penalty
// operator so `H_ββ·x` matches the CPU `schur_matvec` path exactly. The
// operator's `matvec` adds (`y += P x`), so seed `out` from the ridge term.
let penalty_op = sys.effective_penalty_op();
let row_dims: Vec<usize> = sys.rows.iter().map(|row| row.htt.nrows()).collect();
let closure: crate::solver::arrow_schur::GpuSchurMatvec =
Arc::new(move |x: &Array1<f64>, out: &mut Array1<f64>| {
assert_eq!(x.len(), k, "row-procedural matvec: x.len() != k");
assert_eq!(out.len(), k, "row-procedural matvec: out.len() != k");
// (H_ββ + ρ_β·I)·x into out. Seed with the ridge term, then add the
// structured penalty-side product (penalty_op.matvec is additive).
{
let x_slice = x.as_slice().expect("x must be contiguous");
let out_slice = out.as_slice_mut().expect("out must be contiguous");
for a in 0..k {
out_slice[a] = ridge_beta * x_slice[a];
}
penalty_op.matvec(x_slice, out_slice);
}
// out -= Σ_i H_βt^(i) (H_tt^(i) + ρ_t·I)^{-1} H_tβ^(i)·x.
//
// #1017: this row-procedural reduced-Schur term is the matrix-free
// SAE path's matvec hot loop (`build_row_procedural_matvec` is the
// host backend `gpu_schur_matvec_backend` returns when the dense
// `H_tβ` slabs are absent — the production Qwen shape). At
// (n≈2000 rows) it ran SERIALLY on one core and allocated a fresh
// length-`K` `neg` plus per-row `v_i`/`w_i` on EVERY CG iteration —
// tens of thousands of tiny heap allocations across a solve. Each
// row contributes an independent length-`K` scatter, so the sum is
// embarrassingly parallel; fan it across rayon over fixed row chunks
// and fold the per-chunk length-`K` partials in chunk order so the
// f64 reduction is deterministic (bit-identical run-to-run)
// regardless of thread scheduling — it agrees with the serial sum up
// to ULP-scale chunk reassociation (the #1017 verification gate).
// Because that reassociation is a real (if tiny) departure from
// serial, the criterion ranking across topology candidates is stable
// except for candidates separated by less than the reassociation
// margin, where the near-tie winner can flip — not an exact no-move
// guarantee (#1211). Stay
// sequential below
// `SCHUR_MATVEC_PARALLEL_ROW_MIN` rows and when already inside a
// rayon worker (the topology race fans candidates with
// `run_topology_race_parallel`) — the same nested-rayon guard the
// CPU `schur_matvec` uses. Buffers (`v_i`, `neg`) are reused across
// rows within a chunk, so the per-row allocation churn is gone.
let parallel = n >= crate::solver::arrow_schur::SCHUR_MATVEC_PARALLEL_ROW_MIN
&& rayon::current_thread_index().is_none();
if parallel {
use rayon::prelude::*;
const CHUNK: usize = 64;
let partials: Vec<Array1<f64>> = (0..n)
.into_par_iter()
.chunks(CHUNK)
.map(|idxs| {
// One length-`K` scatter accumulator per chunk; the
// per-row latent vector `v_i` (length `d_i ≲ 32`) is the
// only per-row buffer, sized to the row's own `d_i`.
let mut neg = Array1::<f64>::zeros(k);
for i in idxs {
let di = row_dims[i];
// v_i = H_tβ^(i)·x (sparse Kronecker gather).
let mut v_i = Array1::<f64>::zeros(di);
forward(i, x.view(), &mut v_i);
// w_i = (H_tt^(i) + ρ_t·I)^{-1} v_i via L_i L_iᵀ.
let w_i = cholesky_solve_vector(factors[i].view(), v_i.view());
// neg += H_βt^(i)·w_i (sparse scatter).
transpose(i, w_i.view(), &mut neg);
}
neg
})
.collect();
// #1017/#1175 floating-point parity contract: each chunk's row
// sum is formed locally, then chunk partials are folded
// left-to-right. That makes the parallel row-procedural Schur
// term deterministic for a fixed input and chunking, but it is
// not required to be bit-identical to the serial path because
// the additions are reassociated at chunk boundaries. CPU/GPU
// validation should therefore allow ULP-scale drift while
// expecting stable run-to-run results.
let mut neg = Array1::<f64>::zeros(k);
for part in &partials {
for a in 0..k {
neg[a] += part[a];
}
}
for a in 0..k {
out[a] -= neg[a];
}
} else {
// Serial path: reuse one `neg` and one `v_i` across rows.
let mut neg = Array1::<f64>::zeros(k);
for i in 0..n {
let di = row_dims[i];
// v_i = H_tβ^(i)·x (sparse Kronecker gather, length d_i).
let mut v_i = Array1::<f64>::zeros(di);
forward(i, x.view(), &mut v_i);
// w_i = (H_tt^(i) + ρ_t·I)^{-1} v_i via L_i L_iᵀ.
let w_i = cholesky_solve_vector(factors[i].view(), v_i.view());
// neg += H_βt^(i)·w_i (sparse scatter); subtract once at end.
transpose(i, w_i.view(), &mut neg);
}
for a in 0..k {
out[a] -= neg[a];
}
}
});
Ok(closure)
}
/// Solve the reduced shared β-system `S·δβ = r` fully on device with a
/// Jacobi-preconditioned conjugate-gradient (Steihaug truncated-CG) loop.
///
/// `S` is the already-reduced symmetric positive-definite `K × K` Schur
/// complement the streaming SAE joint fit accumulates across minibatches
/// (`StreamingArrowSchur::take_accumulators` summed over chunks, with the
/// global β ridge folded in). The per-row latent blocks have already been
/// eliminated into `S` on the host streaming path; the device's job is the
/// dense `K`-dimensional solve, which is the dominant cost at `K = 100K`.
///
/// The dense `S·p` matvec runs on device via cuBLAS `Dgemv`, and the PCG state
/// vectors (`x`, `r`, `z`, `p`, `S·p`) remain device-resident for the solve.
/// Jacobi preconditioning is an elementwise CUDA kernel; only convergence
/// scalars (`pᵀSp`, `rᵀz`, `‖r‖`) cross the host boundary per iteration, plus the
/// final solution vector.
///
/// Returns `Err(ArrowSchurGpuFailure::Unavailable)` when CUDA is unavailable
/// or the workload is below the dispatch policy; the caller then runs the CPU
/// reduced-β solve. Returns `Err(ArrowSchurGpuFailure::SchurFactorFailed)`
/// when `S` carries a non-positive Jacobi diagonal (caller escalates the
/// proximal ridge).
pub fn solve_reduced_beta_pcg(
s_acc: &Array2<f64>,
rhs_beta: &Array1<f64>,
max_iterations: usize,
relative_tolerance: f64,
) -> Result<Array1<f64>, ArrowSchurGpuFailure> {
solve_reduced_beta_pcg_with_diagnostics(s_acc, rhs_beta, max_iterations, relative_tolerance)
.map(|(x, _)| x)
}
#[doc(hidden)]
pub fn solve_reduced_beta_pcg_with_diagnostics(
s_acc: &Array2<f64>,
rhs_beta: &Array1<f64>,
max_iterations: usize,
relative_tolerance: f64,
) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
let k = rhs_beta.len();
if s_acc.dim() != (k, k) {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"reduced-β GPU PCG requires a square (k×k) Schur block; got {:?} for k={k}",
s_acc.dim()
),
});
}
if k == 0 {
return Err(ArrowSchurGpuFailure::Unavailable);
}
#[cfg(not(target_os = "linux"))]
{
if relative_tolerance.is_nan() || max_iterations == 0 {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "reduced-β GPU PCG: invalid CG controls".to_string(),
});
}
Err(ArrowSchurGpuFailure::Unavailable)
}
#[cfg(target_os = "linux")]
{
cuda::solve_reduced_beta_pcg_with_diagnostics(
s_acc,
rhs_beta,
max_iterations,
relative_tolerance,
)
}
}
pub fn solve_sae_matrix_free_pcg(
sys: &ArrowSchurSystem,
data: &DeviceSaePcgData,
ridge_t: f64,
ridge_beta: f64,
rhs_beta: &Array1<f64>,
max_iterations: usize,
relative_tolerance: f64,
) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
if sys.k != data.beta_dim || rhs_beta.len() != data.beta_dim || data.p == 0 {
return Err(ArrowSchurGpuFailure::Unavailable);
}
#[cfg(not(target_os = "linux"))]
{
if ridge_t.is_nan()
|| ridge_beta.is_nan()
|| relative_tolerance.is_nan()
|| max_iterations == 0
{
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "SAE matrix-free GPU PCG: invalid controls".to_string(),
});
}
Err(ArrowSchurGpuFailure::Unavailable)
}
#[cfg(target_os = "linux")]
{
// #1017/#1026 dispatch GUARD: framed data (frame metadata present) carries
// a factored β border `G ⊗ W_{ij}` data Hessian and dense per-row cross
// blocks the legacy `⊗ I_p` kernel CANNOT represent — feeding it framed
// data would silently return a WRONG Newton step (it returns Ok with no
// fallback). Route framed systems to the dedicated framed kernel and
// legacy full-`B` systems to the legacy kernel; the two never cross.
if data.frame.is_some() {
cuda::solve_sae_matrix_free_pcg_framed(
sys,
data,
ridge_t,
ridge_beta,
rhs_beta,
max_iterations,
relative_tolerance,
)
} else {
cuda::solve_sae_matrix_free_pcg(
sys,
data,
ridge_t,
ridge_beta,
rhs_beta,
max_iterations,
relative_tolerance,
)
}
}
}
/// Reference dense back-end used by tests and as the fallback when the
/// GPU declines. Kept here (not in `arrow_schur_gpu.rs`) so the validation
/// suite has one canonical baseline.
#[doc(hidden)]
pub fn solve_arrow_newton_step_dense_reference(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<ArrowSchurGpuSolution, String> {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let total = n.checked_mul(d).ok_or("dimension overflow")? + k;
let mut h = Array2::<f64>::zeros((total, total));
let mut rhs = Array1::<f64>::zeros(total);
for (i, row) in sys.rows.iter().enumerate() {
let base = i * d;
for c in 0..d {
for r in 0..d {
h[[base + r, base + c]] = row.htt[[r, c]];
}
h[[base + c, base + c]] += ridge_t;
}
for c in 0..k {
for r in 0..d {
let value = row.htbeta[[r, c]];
h[[base + r, n * d + c]] = value;
h[[n * d + c, base + r]] = value;
}
}
for r in 0..d {
rhs[base + r] = -row.gt[r];
}
}
for c in 0..k {
for r in 0..k {
h[[n * d + r, n * d + c]] += sys.hbb[[r, c]];
}
h[[n * d + c, n * d + c]] += ridge_beta;
rhs[n * d + c] = -sys.gb[c];
}
let factor = cholesky_factor_in_place(h.view(), CholeskyGuard::NonnegativePivot)
.ok_or_else(|| "dense reference Cholesky failed".to_string())?;
let mut log_det = 0.0_f64;
for i in 0..total {
log_det += factor[[i, i]].ln();
}
log_det *= 2.0;
let solved = cholesky_solve_vector(factor.view(), rhs.view());
let delta_t = solved.slice(ndarray::s![..n * d]).to_owned();
let delta_beta = solved.slice(ndarray::s![n * d..]).to_owned();
Ok(ArrowSchurGpuSolution {
delta_t,
delta_beta,
log_det_hessian: log_det,
})
}
/// Frames-engaged reduced-Schur penalty-side matvec `out = (P_ββ + ρ_β I)·x`,
/// computed purely from the factored device data (issue #1017/#1026). This is
/// the CPU bit-parity ORACLE for the GPU `arrow_sae_*` penalty kernels on the
/// frames path: smooth `λ S_k ⊗ I_{r_k}` (each `smooth_blocks[i]` at its
/// `global_offset` with right-width `frame.smooth_ranks[i]`) plus data-fit
/// `G_{ij} ⊗ W_{ij}` (each `frame.frame_blocks` entry, with the `μ`-major /
/// frame-minor index `border_offset[atom] + basis·r + frame_coord`). The
/// accumulation order matches the device kernels exactly.
///
/// `out` is OVERWRITTEN: first set to `ρ_β·x`, then the penalty blocks add in.
#[doc(hidden)]
pub fn sae_framed_penalty_matvec_cpu(
data: &DeviceSaePcgData,
ridge_beta: f64,
x: &[f64],
out: &mut [f64],
) {
let frame = data
.frame
.as_ref()
.expect("sae_framed_penalty_matvec_cpu requires frame metadata");
let k = data.beta_dim;
for a in 0..k {
out[a] = ridge_beta * x[a];
}
// Smooth penalty `λ S_k ⊗ I_{r_k}`: y[off + ia·r + ib] += Σ_ja S[ia,ja]·x[off + ja·r + ib].
for (blk, &r) in data.smooth_blocks.iter().zip(frame.smooth_ranks.iter()) {
let off = blk.global_offset;
let m = blk.factor_a.nrows();
for i_a in 0..m {
for i_b in 0..r {
let mut acc = 0.0_f64;
for j_a in 0..m {
let s = blk.factor_a[[i_a, j_a]];
if s == 0.0 {
continue;
}
acc += s * x[off + j_a * r + i_b];
}
out[off + i_a * r + i_b] += acc;
}
}
}
// Data-fit penalty `G_{ij} ⊗ W_{ij}`.
for blk in &frame.frame_blocks {
let r_i = frame.ranks[blk.atom_i];
let r_j = frame.ranks[blk.atom_j];
let off_i = frame.border_offsets[blk.atom_i];
let off_j = frame.border_offsets[blk.atom_j];
let (m_i, m_j) = blk.g.dim();
for li in 0..m_i {
let yi_base = off_i + li * r_i;
for lj in 0..m_j {
let g = blk.g[[li, lj]];
if g == 0.0 {
continue;
}
let xj_base = off_j + lj * r_j;
for a in 0..r_i {
let mut acc = 0.0_f64;
for b in 0..r_j {
acc += blk.w[[a, b]] * x[xj_base + b];
}
out[yi_base + a] += g * acc;
}
}
}
}
}
/// Frames-engaged FULL reduced-Schur matvec `out = S·x` purely from the device
/// data, where `S = (P_ββ + ρ_β I) − Σ_i H_βt^(i)(H_tt^(i)+ρ_t I)⁻¹ H_tβ^(i)`
/// (issue #1017/#1026). The penalty side is [`sae_framed_penalty_matvec_cpu`];
/// the per-row reduced term reads the dense `frame.row_htbeta[i]`
/// (`q_i × border_dim`, row-major), solves against the row's
/// `H_tt^(i)+ρ_t I` Cholesky factor, and scatters the transpose back. This is
/// the size-independent bit-parity oracle the device kernel mirrors; it is also
/// the matvec the GPU PCG iterates.
#[doc(hidden)]
pub fn sae_framed_schur_matvec_cpu(
sys: &ArrowSchurSystem,
data: &DeviceSaePcgData,
ridge_t: f64,
ridge_beta: f64,
x: &[f64],
out: &mut [f64],
) -> Result<(), String> {
let frame = data
.frame
.as_ref()
.ok_or("sae_framed_schur_matvec_cpu requires frame metadata")?;
let k = data.beta_dim;
sae_framed_penalty_matvec_cpu(data, ridge_beta, x, out);
if frame.row_htbeta.len() != sys.rows.len() {
return Err(format!(
"sae_framed_schur_matvec_cpu: {} row_htbeta slabs but {} rows",
frame.row_htbeta.len(),
sys.rows.len()
));
}
for (i, row) in sys.rows.iter().enumerate() {
let slab = &frame.row_htbeta[i];
if slab.is_empty() {
continue;
}
let qi = sys.row_dims[i];
if qi == 0 || slab.len() != qi * k {
continue;
}
// h = H_tβ^(i) · x (length q_i).
let mut h = vec![0.0_f64; qi];
for c in 0..qi {
let base = c * k;
let mut acc = 0.0_f64;
for a in 0..k {
acc += slab[base + a] * x[a];
}
h[c] = acc;
}
// solve (H_tt^(i)+ρ_t I) s = h.
let mut block = row.htt.clone();
for d in 0..qi {
block[[d, d]] += ridge_t;
}
let factor = cholesky_factor_in_place(block.view(), CholeskyGuard::NonnegativePivot)
.ok_or_else(|| format!("sae_framed_schur_matvec_cpu: row {i} H_tt not PD"))?;
let s = cholesky_solve_vector(factor.view(), Array1::from_vec(h).view());
// out -= H_βt^(i) · s = (H_tβ^(i))ᵀ · s.
for c in 0..qi {
let sc = s[c];
if sc == 0.0 {
continue;
}
let base = c * k;
for a in 0..k {
out[a] -= slab[base + a] * sc;
}
}
}
Ok(())
}
#[cfg(target_os = "linux")]
mod cuda {
use super::{ArrowSchurGpuFailure, ArrowSchurGpuSolution, pack_block, pack_host};
use crate::gpu::driver::to_i32;
use crate::gpu::linalg_dispatch::{DispatchOp, route_through_gpu};
use crate::solver::arrow_schur::{
ArrowSchurSystem, DeviceSaeFrameData, DeviceSaePcgData, PcgDiagnostics, PcgStopReason,
};
use cudarc::cublas::sys::{
cublasDiagType_t, cublasFillMode_t, cublasOperation_t, cublasSideMode_t, cublasStatus_t,
};
use cudarc::cublas::{CudaBlas, Gemm, GemmConfig, Gemv, GemvConfig};
use cudarc::cusolver::{DnHandle, sys as cusolver_sys};
use cudarc::driver::{
CudaContext, CudaModule, CudaSlice, CudaStream, DevicePtr, DevicePtrMut, LaunchConfig,
PushKernelArg,
};
use ndarray::Array1;
use std::sync::{Arc, OnceLock};
/// Per-row work slot for the row-block-granular multi-GPU solve. Inputs are
/// the packed single-row buffers (`d×d` D block + ρ_t ridge, `d×k` B block,
/// `d` g vector); the forward pass fills the whitened factors `l/u/y` and the
/// per-tile reduction lands in the tile's leading slot.
struct RowSlot {
// Inputs (packed once on the host, column-major).
d_block: Vec<f64>, // d*d
b_block: Vec<f64>, // d*k
g_vec: Vec<f64>, // d
diag_scale: f64, // |diag(H_tt)| scale for the ridge-bump diagnostic
// Forward outputs, kept on the host for the back-sub pass.
l_block: Vec<f64>, // d*d lower factor, column-major
u_vec: Vec<f64>, // d (= L^{-1} g)
y_block: Vec<f64>, // d*k (= L^{-1} B), column-major
log_det_local: f64,
// Set on a non-PD pivot so the orchestrator can raise RidgeBumpRequired
// for the offending global row instead of silently falling back.
bump: Option<f64>,
// Tile-level reduction, written into the tile's first slot only.
tile_partial_schur: Option<Vec<f64>>, // k*k col-major, = Σ Y_iᵀY_i
tile_partial_rhs: Option<Vec<f64>>, // k, = Σ Y_iᵀu_i
// Back-sub output for this row.
delta_t_block: Vec<f64>, // d
}
/// Row-block-granular multi-GPU Arrow-Schur Newton solve.
///
/// The solve is separable across row blocks in both phases:
/// * forward — each row's local Cholesky `L_i`, whitening
/// `u_i = L_i⁻¹g_i`, `Y_i = L_i⁻¹B_i`, and partial Schur
/// `(Σ Y_iᵀY_i, Σ Y_iᵀu_i)` are independent;
/// * backward — `δt_i = -L_iᵀ⁻¹(u_i + Y_iδβ)` is independent.
/// Only the small shared `K×K` reduce + factor + `δβ` solve is central.
///
/// `crate::gpu::pool::scatter_batched` hands each device a contiguous row
/// tile on its own bound context/stream; the per-tile forward keeps the
/// POTRF fused with its dependent TRSM + Schur GEMM on that one stream, so no
/// on-stream solve is orphaned. Tile partials and per-tile `log|L|` are
/// reduced on the host (in tile/row order), `S_β` is factored on the primary
/// device, and the back-sub is scattered back across the same tiles.
///
/// Returns `Unavailable` (caller uses a single-device path) when the system
/// carries matrix-free operators, the shared block is not dense `K×K`, the
/// pool is single-device, or any tile's device work declines. A non-PD tip
/// block surfaces as `RidgeBumpRequired` for the precise global row.
pub(super) fn solve_multi_gpu(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
if n == 0 || d == 0 || k == 0 {
return Err(ArrowSchurGpuFailure::Unavailable);
}
// Dense shared block + materialised per-row slabs are required; the
// public entry already rejected matrix-free operators, but re-check so
// this routine is safe in isolation.
if sys.hbb_matvec.is_some() || sys.htbeta_matvec.is_some() || sys.hbb.dim() != (k, k) {
return Err(ArrowSchurGpuFailure::Unavailable);
}
let runtime = crate::gpu::device_runtime::GpuRuntime::global()
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
if runtime.device_count() < 2 {
return Err(ArrowSchurGpuFailure::Unavailable);
}
// Pack one slot per row (column-major), folding ρ_t into each D block.
let mut slots: Vec<RowSlot> = Vec::with_capacity(n);
for row in &sys.rows {
if row.htt.dim() != (d, d) || row.htbeta.dim() != (d, k) || row.gt.len() != d {
return Err(ArrowSchurGpuFailure::Unavailable);
}
let mut d_block = Vec::with_capacity(d * d);
let mut b_block = Vec::with_capacity(d * k);
let mut g_vec = Vec::with_capacity(d);
pack_block(row, ridge_t, d, k, &mut d_block, &mut b_block, &mut g_vec);
let diag_scale = row
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
slots.push(RowSlot {
d_block,
b_block,
g_vec,
diag_scale,
l_block: Vec::new(),
u_vec: Vec::new(),
y_block: Vec::new(),
log_det_local: 0.0,
bump: None,
tile_partial_schur: None,
tile_partial_rhs: None,
delta_t_block: vec![0.0; d],
});
}
// ---- Forward pass: per-device row tile, fused on its own stream ----
let forward_ok = crate::gpu::pool::scatter_batched(runtime, &mut slots, |ordinal, tile| {
forward_tile(ordinal, d, k, tile)
});
if forward_ok.is_none() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
// Surface a non-PD tip block as a precise per-row ridge bump.
let row_base_of_tile = crate::gpu::pool::balanced_partition(runtime, n);
if let Some((row, bump)) = slots
.iter()
.enumerate()
.find_map(|(i, slot)| slot.bump.map(|b| (i, b)))
{
return Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump });
}
// ---- Central: reduce tile partials → S_β, r_β; factor; solve δβ ----
// Seed S_β with H_ββ + ρ_β I (column-major) and r_β with -g_β, then fold
// in the per-tile partials in tile order so the reduction order tracks
// the single-device accumulation (up to inter-tile reassociation).
let mut schur_host = vec![0.0_f64; k * k];
for col in 0..k {
for row in 0..k {
let mut v = sys.hbb[[row, col]];
if row == col {
v += ridge_beta;
}
schur_host[col * k + row] = v;
}
}
let mut rhs_host: Vec<f64> = sys.gb.iter().map(|v| -v).collect();
let mut log_det = 0.0_f64;
for start in tile_starts(&row_base_of_tile) {
let slot = &slots[start];
let partial_schur = slot
.tile_partial_schur
.as_ref()
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let partial_rhs = slot
.tile_partial_rhs
.as_ref()
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
// `accumulate_schur` writes `partial_schur = -Σ_tile Y_iᵀY_i` (GEMM
// α=-1, β=1 into a zero seed) and `partial_rhs = +Σ_tile Y_iᵀu_i`.
// The reduced Schur is `S = (H_ββ+ρI) − Σ_all Y_iᵀY_i`, so adding the
// (already-negated) partials reproduces the single-device sign.
for idx in 0..k * k {
schur_host[idx] += partial_schur[idx];
}
for a in 0..k {
rhs_host[a] += partial_rhs[a];
}
}
for slot in &slots {
log_det += slot.log_det_local;
}
// Factor S_β and solve δβ on the primary device (small K×K leaf). The
// stream carries the primary context (same pattern as `solve()`); no
// thread bind is needed for the cuSOLVER/cuBLAS handles created from it.
let primary = runtime.selected_device().ordinal;
let stream = crate::gpu::device_runtime::cuda_context_for(primary)
.and_then(|ctx| ctx.new_stream().ok())
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let solver =
DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut schur_dev = stream
.clone_htod(&schur_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut rhs_dev = stream
.clone_htod(&rhs_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
if info != 0 {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("multi-GPU Schur Cholesky failed at pivot {info}"),
});
}
trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, false)?;
trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, true)?;
let delta_beta_host = stream
.clone_dtoh(&rhs_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let delta_beta = Array1::from_vec(delta_beta_host.clone());
let l_schur_host = stream
.clone_dtoh(&schur_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
for j in 0..k {
log_det += l_schur_host[j * k + j].ln();
}
log_det *= 2.0;
// ---- Backward pass: δt_i = -L_iᵀ⁻¹(u_i + Y_iδβ), per-device tile ----
let delta_beta_ref = &delta_beta_host;
let back_ok = crate::gpu::pool::scatter_batched(runtime, &mut slots, |ordinal, tile| {
back_sub_tile(ordinal, d, k, delta_beta_ref, tile)
});
if back_ok.is_none() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
// Stitch per-row δt into the stacked (n*d) result.
let mut delta_t = Array1::<f64>::zeros(n * d);
for (i, slot) in slots.iter().enumerate() {
let base = i * d;
for r in 0..d {
delta_t[base + r] = slot.delta_t_block[r];
}
}
Ok(ArrowSchurGpuSolution {
delta_t,
delta_beta,
log_det_hessian: log_det,
})
}
/// Tile starts: the leading global row index of each device tile (where the
/// tile-level partial reduction was written by the forward pass).
fn tile_starts(tiles: &[(usize, std::ops::Range<usize>)]) -> impl Iterator<Item = usize> + '_ {
tiles.iter().map(|(_, range)| range.start)
}
/// Forward pass for one device row tile, running on `ordinal`'s bound stream.
/// Factors each row block, whitens `u`/`Y`, accumulates the tile's partial
/// Schur `(Σ Y_iᵀY_i, Σ Y_iᵀu_i)` into the tile's leading slot, keeps the
/// per-row `L`/`u`/`Y` on the host for back-sub, and records the per-row
/// `Σ_j log L_jj`. A non-PD pivot is recorded in `slot.bump` (the tile still
/// returns `Some(())` so the orchestrator raises a precise `RidgeBumpRequired`
/// rather than collapsing the whole batch to CPU).
fn forward_tile(ordinal: usize, d: usize, k: usize, tile: &mut [RowSlot]) -> Option<()> {
if tile.is_empty() {
return Some(());
}
// `scatter_batched` has already bound this ordinal's context on this
// worker thread; the stream below targets that same device.
let stream = crate::gpu::device_runtime::cuda_context_for(ordinal)
.and_then(|ctx| ctx.new_stream().ok())?;
let solver = DnHandle::new(stream.clone()).ok()?;
let blas = CudaBlas::new(stream.clone()).ok()?;
let m = tile.len();
// Stack the tile's D, B, g into contiguous device buffers (same layout
// the single-device path packs for `m` rows).
let mut d_host = Vec::with_capacity(m * d * d);
let mut b_host = Vec::with_capacity(m * d * k);
let mut g_host = Vec::with_capacity(m * d);
for slot in tile.iter() {
d_host.extend_from_slice(&slot.d_block);
b_host.extend_from_slice(&slot.b_block);
g_host.extend_from_slice(&slot.g_vec);
}
let mut d_dev = stream.clone_htod(&d_host).ok()?;
let mut b_dev = stream.clone_htod(&b_host).ok()?;
let mut g_dev = stream.clone_htod(&g_host).ok()?;
// Batched POTRF; a non-PD block records its bump and stops the tile.
let info_host = potrf_batched(&solver, &stream, d, m, &mut d_dev).ok()?;
if let Some(local) = info_host.iter().position(|info| *info != 0) {
let pivot = info_host[local];
tile[local].bump = Some(
tile[local].diag_scale
* (f64::from(pivot).abs()).max(1.0)
* f64::EPSILON.sqrt()
* super::RIDGE_BUMP_EPS_MARGIN,
);
return Some(());
}
// Whiten: u = L⁻¹ g, Y = L⁻¹ B.
trsm_batched_lower_inplace(&blas, &stream, d, m, 1, &d_dev, &mut g_dev).ok()?;
trsm_batched_lower_inplace(&blas, &stream, d, m, k, &d_dev, &mut b_dev).ok()?;
// Tile partial Schur: zero-seeded so the host adds the H_ββ seed once.
let mut schur_dev = stream.alloc_zeros::<f64>(k * k).ok()?;
let mut rhs_dev = stream.alloc_zeros::<f64>(k).ok()?;
accumulate_schur(&blas, d, k, m, &b_dev, &g_dev, &mut schur_dev, &mut rhs_dev).ok()?;
// Download L, u, Y, and the tile partials.
let l_host = stream.clone_dtoh(&d_dev).ok()?;
let u_host = stream.clone_dtoh(&g_dev).ok()?;
let y_host = stream.clone_dtoh(&b_dev).ok()?;
let partial_schur = stream.clone_dtoh(&schur_dev).ok()?;
let partial_rhs = stream.clone_dtoh(&rhs_dev).ok()?;
for (local, slot) in tile.iter_mut().enumerate() {
let l_base = local * d * d;
let u_base = local * d;
let y_base = local * d * k;
slot.l_block = l_host[l_base..l_base + d * d].to_vec();
slot.u_vec = u_host[u_base..u_base + d].to_vec();
slot.y_block = y_host[y_base..y_base + d * k].to_vec();
let mut log_det_local = 0.0_f64;
for j in 0..d {
log_det_local += l_host[l_base + j * d + j].ln();
}
slot.log_det_local = log_det_local;
}
tile[0].tile_partial_schur = Some(partial_schur);
tile[0].tile_partial_rhs = Some(partial_rhs);
Some(())
}
/// Back-substitution for one device row tile: `δt_i = -L_iᵀ⁻¹(u_i + Y_iδβ)`.
/// Re-uploads the tile's kept `L`/`u`/`Y` to `ordinal`, applies the GEMV
/// accumulate + transposed TRSM, and writes each row's `δt` into its slot.
fn back_sub_tile(
ordinal: usize,
d: usize,
k: usize,
delta_beta: &[f64],
tile: &mut [RowSlot],
) -> Option<()> {
if tile.is_empty() {
return Some(());
}
// `scatter_batched` has already bound this ordinal's context on this
// worker thread; the stream below targets that same device.
let stream = crate::gpu::device_runtime::cuda_context_for(ordinal)
.and_then(|ctx| ctx.new_stream().ok())?;
let blas = CudaBlas::new(stream.clone()).ok()?;
let m = tile.len();
let mut l_host = Vec::with_capacity(m * d * d);
let mut u_host = Vec::with_capacity(m * d);
let mut y_host = Vec::with_capacity(m * d * k);
for slot in tile.iter() {
l_host.extend_from_slice(&slot.l_block);
u_host.extend_from_slice(&slot.u_vec);
y_host.extend_from_slice(&slot.y_block);
}
let d_dev = stream.clone_htod(&l_host).ok()?;
let mut g_dev = stream.clone_htod(&u_host).ok()?;
let b_dev = stream.clone_htod(&y_host).ok()?;
let rhs_dev = stream.clone_htod(&delta_beta.to_vec()).ok()?;
// g ← u + Y·δβ, then x = L⁻ᵀ g; δt = -x.
accumulate_back_sub_rhs(&blas, d, k, m, &b_dev, &rhs_dev, &mut g_dev).ok()?;
trsm_batched_lower_inplace_transposed(&blas, &stream, d, m, 1, &d_dev, &mut g_dev).ok()?;
let x_host = stream.clone_dtoh(&g_dev).ok()?;
for (local, slot) in tile.iter_mut().enumerate() {
let base = local * d;
for r in 0..d {
slot.delta_t_block[r] = -x_host[base + r];
}
}
Some(())
}
pub(super) fn solve(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let runtime = route_through_gpu(DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n })
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let stream = crate::gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
.and_then(|ctx| ctx.new_stream().ok())
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let solver =
DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// ----- Pack + upload D, B, g -----
let (d_host, b_host, g_host) = pack_host(sys, ridge_t);
let mut d_dev = stream
.clone_htod(&d_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut b_dev = stream
.clone_htod(&b_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut g_dev = stream
.clone_htod(&g_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// ----- Layer A: batched lower Cholesky of D in place -----
// This POTRF is fused with the downstream TRSM + Schur GEMM + back-sub
// on this one stream, so splitting only the POTRF across devices would
// orphan the dependent on-stream solves. Multi-GPU here is the
// whole-solve row-block split in `solve_arrow_newton_step` (see
// `solve_multi_gpu`), not a per-layer split — this device-resident path
// is the single-device leaf the split dispatches per tile.
let info_host = potrf_batched(&solver, &stream, d, n, &mut d_dev)?;
if let Some(idx) = info_host.iter().position(|info| *info != 0) {
let pivot = info_host[idx];
let scale = sys.rows[idx]
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
return Err(ArrowSchurGpuFailure::RidgeBumpRequired {
row: idx,
bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
});
}
// ----- Layer B (1/2): in-place triangular solves -----
// u_i = L_i^{-1} g_i, packed as a stacked (n*d) column-vector.
trsm_batched_lower_inplace(&blas, &stream, d, n, 1, &d_dev, &mut g_dev)?;
// Y_i = L_i^{-1} B_i, in place over the (n*d) × k buffer (laid out as
// n stacked column-major d×k tiles).
trsm_batched_lower_inplace(&blas, &stream, d, n, k, &d_dev, &mut b_dev)?;
// ----- Layer B (2/2): Schur reduction via single big GEMM / GEMV -----
// Y_all is (n*d) × k column-major: viewing all n stacked d×k tiles as
// one big matrix is bit-exact because each tile is column-major with
// leading dim d and the tiles are contiguous in memory, so the
// combined leading dim is n*d only for the *outer* matrix view. To
// make the single-GEMM equivalence hold we must treat the stacked
// buffer as (n*d) × k column-major with leading dim = n*d, which
// means columns of Y_all are interleaved by row across blocks.
// That is NOT what we packed. So we use the cuBLAS stride pattern
// instead: stride-by-block, transpose-A, and *accumulate* into one
// S_β buffer via beta=1 across batches. Equivalent flop count, no
// extra reduction kernel, and correct layout.
//
// Concretely: schur ← C + ρ_β I; rhs ← -g_β; then for each block
// schur -= Y_i^T Y_i (k×k)
// rhs += Y_i^T u_i (k)
// We launch this as `n` sequential GEMMs/GEMVs with beta=1 on the
// accumulator. Layer D fuses these into one NVRTC launch.
let schur_init: Vec<f64> = {
let mut tmp = Vec::with_capacity(k * k);
for col in 0..k {
for row in 0..k {
let mut v = sys.hbb[[row, col]];
if row == col {
v += ridge_beta;
}
tmp.push(v);
}
}
tmp
};
let mut schur_dev = stream
.clone_htod(&schur_init)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let rhs_init: Vec<f64> = sys.gb.iter().map(|v| -v).collect();
let mut rhs_dev = stream
.clone_htod(&rhs_init)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
accumulate_schur(&blas, d, k, n, &b_dev, &g_dev, &mut schur_dev, &mut rhs_dev)?;
// ----- Layer C (1/2): factor S_β and solve for δβ -----
let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
if info != 0 {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("Schur Cholesky failed at pivot {info}"),
});
}
// δβ ← L_S^{-T} L_S^{-1} rhs
trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, false)?;
trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, true)?;
let delta_beta_host = stream
.clone_dtoh(&rhs_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let delta_beta = Array1::from_vec(delta_beta_host.clone());
// ----- Layer C (2/2): back-sub δt_i = -L_i^{-T} (u_i + Y_i δβ) -----
// Already on device:
// g_dev holds u_i stacked (n*d).
// b_dev holds Y_i stacked column-major n×(d×k) tiles.
// Compute g_dev ← g_dev + Y_block · δβ per block (cuBLAS gemv with beta=1),
// then in-place trsm with L_i^T (CUBLAS_OP_T) to obtain x_i, and finally
// δt_i = -x_i on host after download.
accumulate_back_sub_rhs(&blas, d, k, n, &b_dev, &rhs_dev, &mut g_dev)?;
trsm_batched_lower_inplace_transposed(&blas, &stream, d, n, 1, &d_dev, &mut g_dev)?;
let x_host = stream
.clone_dtoh(&g_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut delta_t = Array1::<f64>::zeros(n * d);
for (i, v) in x_host.iter().enumerate() {
delta_t[i] = -*v;
}
// ----- log|H| = 2 Σ log L_{i,jj} + 2 Σ log R_{β,aa} -----
let l_local_host = stream
.clone_dtoh(&d_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let l_schur_host = stream
.clone_dtoh(&schur_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut log_det = 0.0_f64;
for i in 0..n {
let base = i * d * d;
for j in 0..d {
log_det += l_local_host[base + j * d + j].ln();
}
}
for j in 0..k {
log_det += l_schur_host[j * k + j].ln();
}
log_det *= 2.0;
Ok(ArrowSchurGpuSolution {
delta_t,
delta_beta,
log_det_hessian: log_det,
})
}
fn potrf_batched(
solver: &DnHandle,
stream: &Arc<CudaStream>,
p: usize,
batch: usize,
matrices: &mut CudaSlice<f64>,
) -> Result<Vec<i32>, ArrowSchurGpuFailure> {
let p_i = to_i32(p).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let batch_i = to_i32(batch).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let matrix_len = p * p;
let bytes_per = (matrix_len * std::mem::size_of::<f64>()) as u64;
let (base_ptr, _record) = matrices.device_ptr_mut(stream);
let mut ptrs = Vec::with_capacity(batch);
for idx in 0..batch {
ptrs.push(base_ptr + (idx as u64) * bytes_per);
}
let mut ptrs_dev = stream
.clone_htod(&ptrs)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut info_dev = stream
.alloc_zeros::<i32>(batch)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let status = {
let (ptrs_ptr, _ptrs_record) = ptrs_dev.device_ptr_mut(stream);
let (info_ptr, _info_record) = info_dev.device_ptr_mut(stream);
// SAFETY: pointer array and info buffer live on the device,
// matrices_dev holds `batch` contiguous p×p column-major blocks.
unsafe {
cusolver_sys::cusolverDnDpotrfBatched(
solver.cu(),
cusolver_sys::cublasFillMode_t::CUBLAS_FILL_MODE_LOWER,
p_i,
ptrs_ptr as *mut *mut f64,
p_i,
info_ptr as *mut i32,
batch_i,
)
}
};
if status != cusolver_sys::cusolverStatus_t::CUSOLVER_STATUS_SUCCESS {
return Err(ArrowSchurGpuFailure::Unavailable);
}
stream
.clone_dtoh(&info_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
}
fn potrf_single(
solver: &DnHandle,
stream: &Arc<CudaStream>,
p: usize,
matrix: &mut CudaSlice<f64>,
) -> Result<i32, ArrowSchurGpuFailure> {
let p_i = to_i32(p).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let uplo = cusolver_sys::cublasFillMode_t::CUBLAS_FILL_MODE_LOWER;
let mut lwork = 0_i32;
{
let (mat_ptr, _rec) = matrix.device_ptr_mut(stream);
// SAFETY: buffer query against a live p-by-p column-major device matrix.
let status = unsafe {
cusolver_sys::cusolverDnDpotrf_bufferSize(
solver.cu(),
uplo,
p_i,
mat_ptr as *mut f64,
p_i,
&mut lwork,
)
};
if status != cusolver_sys::cusolverStatus_t::CUSOLVER_STATUS_SUCCESS {
return Err(ArrowSchurGpuFailure::Unavailable);
}
}
let lwork_usize = usize::try_from(lwork).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut workspace = stream
.alloc_zeros::<f64>(lwork_usize.max(1))
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut info_dev = stream
.alloc_zeros::<i32>(1)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
{
let (mat_ptr, _rec) = matrix.device_ptr_mut(stream);
let (work_ptr, _wrec) = workspace.device_ptr_mut(stream);
let (info_ptr, _irec) = info_dev.device_ptr_mut(stream);
// SAFETY: all three pointers refer to live, correctly sized device buffers.
let status = unsafe {
cusolver_sys::cusolverDnDpotrf(
solver.cu(),
uplo,
p_i,
mat_ptr as *mut f64,
p_i,
work_ptr as *mut f64,
lwork,
info_ptr as *mut i32,
)
};
if status != cusolver_sys::cusolverStatus_t::CUSOLVER_STATUS_SUCCESS {
return Err(ArrowSchurGpuFailure::Unavailable);
}
}
let info_host = stream
.clone_dtoh(&info_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
Ok(info_host[0])
}
/// In-place lower-triangular solves `X_i ← L_i^{-1} X_i` over the n stacked
/// d×nrhs RHS tiles in `rhs`. Uses `cublasDtrsmBatched` so all n solves
/// hit the device in one launch.
fn trsm_batched_lower_inplace(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
d: usize,
n: usize,
nrhs: usize,
l_stack: &CudaSlice<f64>,
rhs_stack: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
trsm_batched_inplace_inner(blas, stream, d, n, nrhs, l_stack, rhs_stack, false)
}
/// As above but with `L_i^T` instead of `L_i`.
fn trsm_batched_lower_inplace_transposed(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
d: usize,
n: usize,
nrhs: usize,
l_stack: &CudaSlice<f64>,
rhs_stack: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
trsm_batched_inplace_inner(blas, stream, d, n, nrhs, l_stack, rhs_stack, true)
}
fn trsm_batched_inplace_inner(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
d: usize,
n: usize,
nrhs: usize,
l_stack: &CudaSlice<f64>,
rhs_stack: &mut CudaSlice<f64>,
transposed: bool,
) -> Result<(), ArrowSchurGpuFailure> {
let alpha = 1.0_f64;
let d_i = to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let nrhs_i = to_i32(nrhs).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let batch_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let l_bytes_per = (d * d * std::mem::size_of::<f64>()) as u64;
let rhs_bytes_per = (d * nrhs * std::mem::size_of::<f64>()) as u64;
let (l_base, _l_record) = l_stack.device_ptr(stream);
let (rhs_base, _rhs_record) = rhs_stack.device_ptr_mut(stream);
let mut l_ptrs = Vec::with_capacity(n);
let mut rhs_ptrs = Vec::with_capacity(n);
for i in 0..n {
l_ptrs.push(l_base + (i as u64) * l_bytes_per);
rhs_ptrs.push(rhs_base + (i as u64) * rhs_bytes_per);
}
let mut l_ptrs_dev = stream
.clone_htod(&l_ptrs)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut rhs_ptrs_dev = stream
.clone_htod(&rhs_ptrs)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let (l_ptrs_ptr, _l_ptrs_rec) = l_ptrs_dev.device_ptr_mut(stream);
let (rhs_ptrs_ptr, _rhs_ptrs_rec) = rhs_ptrs_dev.device_ptr_mut(stream);
let op = if transposed {
cublasOperation_t::CUBLAS_OP_T
} else {
cublasOperation_t::CUBLAS_OP_N
};
let handle = *blas.handle();
// SAFETY: pointer arrays and base buffers were just constructed from
// live device allocations covering the entire batch.
let status = unsafe {
cudarc::cublas::sys::cublasDtrsmBatched(
handle,
cublasSideMode_t::CUBLAS_SIDE_LEFT,
cublasFillMode_t::CUBLAS_FILL_MODE_LOWER,
op,
cublasDiagType_t::CUBLAS_DIAG_NON_UNIT,
d_i,
nrhs_i,
&alpha,
l_ptrs_ptr as *const *const f64,
d_i,
rhs_ptrs_ptr as *const *mut f64,
d_i,
batch_i,
)
};
if status != cublasStatus_t::CUBLAS_STATUS_SUCCESS {
return Err(ArrowSchurGpuFailure::Unavailable);
}
Ok(())
}
/// Single-matrix lower-triangular solve: `rhs ← L^{-1} rhs` (or
/// `L^{-T} rhs` if `transposed`). For the Schur Cholesky back-sub.
fn trsm_single(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
n: usize,
l: &CudaSlice<f64>,
rhs: &mut CudaSlice<f64>,
upper: bool,
transposed: bool,
) -> Result<(), ArrowSchurGpuFailure> {
let alpha = 1.0_f64;
let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let handle = *blas.handle();
let (l_ptr, _l_rec) = l.device_ptr(stream);
let (rhs_ptr, _rhs_rec) = rhs.device_ptr_mut(stream);
// SAFETY: single n×n lower factor and n-vector RHS on device.
let status = unsafe {
cudarc::cublas::sys::cublasDtrsm_v2(
handle,
cublasSideMode_t::CUBLAS_SIDE_LEFT,
if upper {
cublasFillMode_t::CUBLAS_FILL_MODE_UPPER
} else {
cublasFillMode_t::CUBLAS_FILL_MODE_LOWER
},
if transposed {
cublasOperation_t::CUBLAS_OP_T
} else {
cublasOperation_t::CUBLAS_OP_N
},
cublasDiagType_t::CUBLAS_DIAG_NON_UNIT,
n_i,
1,
&alpha,
l_ptr as *const f64,
n_i,
rhs_ptr as *mut f64,
n_i,
)
};
if status != cublasStatus_t::CUBLAS_STATUS_SUCCESS {
return Err(ArrowSchurGpuFailure::Unavailable);
}
Ok(())
}
/// Accumulate `schur ← schur − Σ_i Y_i^T Y_i` and `rhs ← rhs + Σ_i Y_i^T u_i`
/// using one GEMM and one GEMV per block. Each call uses beta=1 to chain
/// the accumulation device-side.
fn accumulate_schur(
blas: &CudaBlas,
d: usize,
k: usize,
n: usize,
y_stack: &CudaSlice<f64>,
u_stack: &CudaSlice<f64>,
schur: &mut CudaSlice<f64>,
rhs: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let y_block_elems = d * k;
let u_block_elems = d;
for i in 0..n {
let y_slice = y_stack.slice(i * y_block_elems..(i + 1) * y_block_elems);
let u_slice = u_stack.slice(i * u_block_elems..(i + 1) * u_block_elems);
// GEMM: schur += (-1) · Y_i^T · Y_i (Y_i is d×k col-major; out is k×k)
let gemm_cfg = GemmConfig::<f64> {
transa: cublasOperation_t::CUBLAS_OP_T,
transb: cublasOperation_t::CUBLAS_OP_N,
m: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
k: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
alpha: -1.0,
lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
ldb: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
beta: 1.0,
ldc: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
};
// SAFETY: y_slice is d×k col-major, schur is k×k col-major; alpha/beta scalars set above.
unsafe { blas.gemm(gemm_cfg, &y_slice, &y_slice, schur) }
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// GEMV: rhs += 1 · Y_i^T · u_i
let gemv_cfg = GemvConfig::<f64> {
trans: cublasOperation_t::CUBLAS_OP_T,
m: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
alpha: 1.0,
lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
incx: 1,
beta: 1.0,
incy: 1,
};
// SAFETY: y_slice (d×k col-major) and u_slice (length d) are live
// device buffers; `rhs` is the length-k accumulator.
unsafe { blas.gemv(gemv_cfg, &y_slice, &u_slice, rhs) }
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
Ok(())
}
/// `#1017` resident gradient path: accumulate ONLY the Schur RHS term
/// `rhs += Σ_i Y_iᵀ u_i`, skipping the `−Σ_i Y_iᵀ Y_i` matrix GEMM that the
/// resident frame already folded into its persistent `L_S` factor. This is
/// the per-iterate-cheap counterpart of [`accumulate_schur`]: the GEMV here
/// is bit-identical to the GEMV inside `accumulate_schur` (same config, same
/// `beta=1` accumulation order over rows), so the resident frame's `δβ`
/// matches a full `solve()` at the same gradient.
fn accumulate_schur_rhs_only(
blas: &CudaBlas,
d: usize,
k: usize,
n: usize,
y_stack: &CudaSlice<f64>,
u_stack: &CudaSlice<f64>,
rhs: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let y_block_elems = d * k;
let u_block_elems = d;
for i in 0..n {
let y_slice = y_stack.slice(i * y_block_elems..(i + 1) * y_block_elems);
let u_slice = u_stack.slice(i * u_block_elems..(i + 1) * u_block_elems);
let gemv_cfg = GemvConfig::<f64> {
trans: cublasOperation_t::CUBLAS_OP_T,
m: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
alpha: 1.0,
lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
incx: 1,
beta: 1.0,
incy: 1,
};
// SAFETY: y_slice (d×k col-major) and u_slice (length d) are live
// device buffers; `rhs` is the length-k accumulator.
unsafe { blas.gemv(gemv_cfg, &y_slice, &u_slice, rhs) }
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
Ok(())
}
/// Accumulate `g_dev[i] ← u_i + Y_i · δβ` per block. This is the
/// pre-trsm RHS for the back-substitution `L_i^T x_i = w_i`.
fn accumulate_back_sub_rhs(
blas: &CudaBlas,
d: usize,
k: usize,
n: usize,
y_stack: &CudaSlice<f64>,
delta_beta: &CudaSlice<f64>,
u_stack: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let y_block_elems = d * k;
let u_block_elems = d;
for i in 0..n {
let y_slice = y_stack.slice(i * y_block_elems..(i + 1) * y_block_elems);
let mut u_slice = u_stack.slice_mut(i * u_block_elems..(i + 1) * u_block_elems);
let gemv_cfg = GemvConfig::<f64> {
trans: cublasOperation_t::CUBLAS_OP_N,
m: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
alpha: 1.0,
lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
incx: 1,
beta: 1.0,
incy: 1,
};
// SAFETY: y_slice / delta_beta / u_slice are live device buffers
// of the expected sizes (d×k, k, d).
unsafe { blas.gemv(gemv_cfg, &y_slice, delta_beta, &mut u_slice) }
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
Ok(())
}
// ────────────────────────────────────────────────────────────────────
// Layer D + E — fused NVRTC dispatch.
//
// The forward kernel (`arrow_schur_forward_pgroup`) is a single launch
// that, per row block, factors `D_i + ρI = L_i L_iᵀ` in shared memory,
// forward-solves `u_i = L_i⁻¹ g_i` and `Y_i = L_i⁻¹ B_i`, and emits the
// per-block Schur partials `partial_S[i] = Yᵀ Y` (R×R) and
// `partial_r[i] = Yᵀ u` (R). The host reduces partials on the CPU after
// dtoh (one fused sum across `n` blocks of R²+R doubles; cheap because
// n·R² ≲ 5M doubles at large scale), assembles `S_β`, factors it via
// cuSOLVER, and launches the back-substitution kernel
// `arrow_schur_back_sub_pgroup` to recover `δt_i = -L_i⁻ᵀ(u_i + Y_i δβ)`
// without re-uploading the local factors.
// ────────────────────────────────────────────────────────────────────
use std::collections::HashMap;
use std::sync::Mutex;
/// One compiled NVRTC module per `(cc_major, cc_minor, p_max, r_template)`.
/// `cc_*` lets one process drive multiple device generations; the
/// `(p_max, r_template)` pair selects the shared-memory layout baked into
/// the kernel source.
struct FusedModuleCache {
modules: Mutex<
HashMap<crate::gpu::kernels::arrow_schur_nvrtc::FusedModuleCacheKey, Arc<CudaModule>>,
>,
}
fn fused_module_cache() -> &'static FusedModuleCache {
static CACHE: OnceLock<FusedModuleCache> = OnceLock::new();
CACHE.get_or_init(|| FusedModuleCache {
modules: Mutex::new(HashMap::new()),
})
}
fn fused_module_for(
ctx: &Arc<CudaContext>,
key: crate::gpu::kernels::arrow_schur_nvrtc::FusedModuleCacheKey,
) -> Result<Arc<CudaModule>, ArrowSchurGpuFailure> {
let cache = fused_module_cache();
if let Ok(guard) = cache.modules.lock() {
if let Some(existing) = guard.get(&key) {
return Ok(existing.clone());
}
}
let src = crate::gpu::kernels::arrow_schur_nvrtc::forward_kernel_source(
key.p_max as usize,
key.r_template as usize,
);
let ptx = cudarc::nvrtc::compile_ptx(&src).map_err(|err| {
ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"arrow-schur fused NVRTC compile (p_max={}, r={}): {err}",
key.p_max, key.r_template
),
}
})?;
let module = ctx
.load_module(ptx)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
if let Ok(mut guard) = cache.modules.lock() {
guard.entry(key).or_insert_with(|| module.clone());
}
Ok(module)
}
const PCG_VECTOR_KERNEL_SOURCE: &str = r#"
extern "C" __global__ void arrow_pcg_jacobi_mul(
const double* __restrict__ inv_diag,
const double* __restrict__ r,
double* __restrict__ z,
int n
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
z[idx] = inv_diag[idx] * r[idx];
}
}
extern "C" __global__ void arrow_pcg_update_p(
const double* __restrict__ z,
double beta,
double* __restrict__ p,
int n
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
p[idx] = z[idx] + beta * p[idx];
}
}
extern "C" __global__ void arrow_sae_init(
double* __restrict__ out,
const double* __restrict__ x,
double ridge,
int n
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
out[idx] = ridge * x[idx];
}
}
extern "C" __global__ void arrow_sae_smooth_matvec(
const double* __restrict__ x,
double* __restrict__ out,
const int* __restrict__ block_offsets,
const int* __restrict__ block_m,
const int* __restrict__ factor_ptr,
const double* __restrict__ factors,
int p,
int n_blocks
) {
int block_id = blockIdx.y;
int linear = blockIdx.x * blockDim.x + threadIdx.x;
if (block_id >= n_blocks) {
return;
}
int m = block_m[block_id];
int total = m * p;
if (linear >= total) {
return;
}
int li = linear / p;
int oc = linear - li * p;
int off = block_offsets[block_id];
int fbase = factor_ptr[block_id];
double acc = 0.0;
for (int lj = 0; lj < m; ++lj) {
double a = factors[fbase + li * m + lj];
acc += a * x[off + lj * p + oc];
}
out[off + li * p + oc] += acc;
}
extern "C" __global__ void arrow_sae_sparse_g_matvec(
const double* __restrict__ x,
double* __restrict__ out,
const int* __restrict__ row_off,
const int* __restrict__ col_off,
const int* __restrict__ rows,
const int* __restrict__ cols,
const int* __restrict__ data_ptr,
const double* __restrict__ data,
int p,
int n_blocks
) {
int block_id = blockIdx.y;
int linear = blockIdx.x * blockDim.x + threadIdx.x;
if (block_id >= n_blocks) {
return;
}
int m_i = rows[block_id];
int m_j = cols[block_id];
int total = m_i * p;
if (linear >= total) {
return;
}
int li = linear / p;
int oc = linear - li * p;
int rbase = row_off[block_id];
int cbase = col_off[block_id];
int dbase = data_ptr[block_id];
double acc = 0.0;
for (int lj = 0; lj < m_j; ++lj) {
acc += data[dbase + li * m_j + lj] * x[(cbase + lj) * p + oc];
}
out[(rbase + li) * p + oc] += acc;
}
extern "C" __global__ void arrow_sae_gather_u(
const double* __restrict__ x,
const int* __restrict__ row_ptr,
const int* __restrict__ beta_base,
const double* __restrict__ phi,
double* __restrict__ u,
int p,
int n_rows
) {
int row = blockIdx.y;
int oc = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows || oc >= p) {
return;
}
double acc = 0.0;
int start = row_ptr[row];
int end = row_ptr[row + 1];
for (int e = start; e < end; ++e) {
acc += phi[e] * x[beta_base[e] + oc];
}
u[row * p + oc] = acc;
}
extern "C" __global__ void arrow_sae_apply_l(
const double* __restrict__ u,
const int* __restrict__ jac_ptr,
const double* __restrict__ jac,
double* __restrict__ w,
int p,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows) {
return;
}
int jstart = jac_ptr[row];
int q = (jac_ptr[row + 1] - jstart) / p;
if (c >= q) {
return;
}
double acc = 0.0;
for (int oc = 0; oc < p; ++oc) {
acc += jac[jstart + c * p + oc] * u[row * p + oc];
}
w[row * max_q + c] = acc;
}
extern "C" __global__ void arrow_sae_apply_ainv(
const double* __restrict__ ainv,
const double* __restrict__ w,
double* __restrict__ v,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows || c >= max_q) {
return;
}
double acc = 0.0;
int base = row * max_q * max_q;
for (int j = 0; j < max_q; ++j) {
acc += ainv[base + c * max_q + j] * w[row * max_q + j];
}
v[row * max_q + c] = acc;
}
extern "C" __global__ void arrow_sae_scatter_sub(
const double* __restrict__ v,
const int* __restrict__ jac_ptr,
const double* __restrict__ jac,
const int* __restrict__ row_ptr,
const int* __restrict__ beta_base,
const double* __restrict__ phi,
double* __restrict__ out,
int p,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int oc = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows || oc >= p) {
return;
}
int jstart = jac_ptr[row];
int q = (jac_ptr[row + 1] - jstart) / p;
double lt_v = 0.0;
for (int c = 0; c < q; ++c) {
lt_v += jac[jstart + c * p + oc] * v[row * max_q + c];
}
int start = row_ptr[row];
int end = row_ptr[row + 1];
for (int e = start; e < end; ++e) {
atomicAdd(&out[beta_base[e] + oc], -phi[e] * lt_v);
}
}
extern "C" __global__ void arrow_sae_diag_sub(
double* __restrict__ diag,
const double* __restrict__ ainv,
const int* __restrict__ jac_ptr,
const double* __restrict__ jac,
const int* __restrict__ row_ptr,
const int* __restrict__ beta_base,
const double* __restrict__ phi,
int p,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int oc = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows || oc >= p) {
return;
}
int jstart = jac_ptr[row];
int q = (jac_ptr[row + 1] - jstart) / p;
int abase = row * max_q * max_q;
double quad = 0.0;
for (int c = 0; c < q; ++c) {
double lc = jac[jstart + c * p + oc];
for (int d = 0; d < q; ++d) {
quad += lc * ainv[abase + c * max_q + d] * jac[jstart + d * p + oc];
}
}
int start = row_ptr[row];
int end = row_ptr[row + 1];
for (int e = start; e < end; ++e) {
double pe = phi[e];
atomicAdd(&diag[beta_base[e] + oc], -(pe * pe) * quad);
}
}
/* ── #1017/#1026 frames-engaged device kernels ─────────────────────────────
* The factored β border is C-space (width Σ M_k·r_k). The penalty side is the
* smooth `λ S_k ⊗ I_{r_k}` (per-block right-width r_k) plus the data-fit
* `G_{ij} ⊗ W_{ij}` (W = U_iᵀU_j, dense r_i×r_j). The reduced-Schur term uses
* the per-row DENSE cross-block H_tβ^(i) (q_i × border_dim, row-major). */
extern "C" __global__ void arrow_sae_frame_smooth_matvec(
const double* __restrict__ x,
double* __restrict__ out,
const int* __restrict__ block_offsets,
const int* __restrict__ block_m,
const int* __restrict__ block_r,
const int* __restrict__ factor_ptr,
const double* __restrict__ factors,
int n_blocks
) {
int block_id = blockIdx.y;
int linear = blockIdx.x * blockDim.x + threadIdx.x;
if (block_id >= n_blocks) {
return;
}
int m = block_m[block_id];
int r = block_r[block_id];
int total = m * r;
if (linear >= total) {
return;
}
int li = linear / r;
int ib = linear - li * r;
int off = block_offsets[block_id];
int fbase = factor_ptr[block_id];
double acc = 0.0;
for (int lj = 0; lj < m; ++lj) {
double a = factors[fbase + li * m + lj];
acc += a * x[off + lj * r + ib];
}
out[off + li * r + ib] += acc;
}
extern "C" __global__ void arrow_sae_frame_g_matvec(
const double* __restrict__ x,
double* __restrict__ out,
const int* __restrict__ off_i,
const int* __restrict__ off_j,
const int* __restrict__ r_i,
const int* __restrict__ r_j,
const int* __restrict__ m_i,
const int* __restrict__ m_j,
const int* __restrict__ g_ptr,
const double* __restrict__ g_data,
const int* __restrict__ w_ptr,
const double* __restrict__ w_data,
int n_blocks
) {
int block_id = blockIdx.y;
int linear = blockIdx.x * blockDim.x + threadIdx.x;
if (block_id >= n_blocks) {
return;
}
int ri = r_i[block_id];
int rj = r_j[block_id];
int mi = m_i[block_id];
int mj = m_j[block_id];
int total = mi * ri;
if (linear >= total) {
return;
}
int li = linear / ri; // basis row in atom i
int a = linear - li * ri; // frame coord in atom i
int oi = off_i[block_id];
int oj = off_j[block_id];
int gbase = g_ptr[block_id];
int wbase = w_ptr[block_id];
double acc = 0.0;
for (int lj = 0; lj < mj; ++lj) {
double g = g_data[gbase + li * mj + lj];
if (g == 0.0) { continue; }
int xj_base = oj + lj * rj;
double inner = 0.0;
for (int b = 0; b < rj; ++b) {
inner += w_data[wbase + a * rj + b] * x[xj_base + b];
}
acc += g * inner;
}
out[oi + li * ri + a] += acc;
}
/* Per-row reduced-Schur subtraction with a DENSE cross-block H_tβ^(i).
* h_i = H_tβ^(i) · x (length q_i)
* s_i = (H_tt^(i)+ρ_t I)⁻¹ h_i (apply cached ainv, length q_i)
* out -= (H_tβ^(i))ᵀ · s_i (scatter into border_dim)
* `htb` is row-major (q_i × k) flattened, `htb_ptr` gives each row's base and
* (htb_ptr[row+1]-htb_ptr[row])/k == q_i. `q_of` carries q_i directly. */
extern "C" __global__ void arrow_sae_frame_apply_h(
const double* __restrict__ x,
const int* __restrict__ htb_ptr,
const double* __restrict__ htb,
const int* __restrict__ q_of,
double* __restrict__ hvec,
int k,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows) { return; }
int q = q_of[row];
if (c >= q) { return; }
int base = htb_ptr[row] + c * k;
double acc = 0.0;
for (int a = 0; a < k; ++a) {
acc += htb[base + a] * x[a];
}
hvec[row * max_q + c] = acc;
}
extern "C" __global__ void arrow_sae_frame_apply_ainv(
const double* __restrict__ ainv,
const double* __restrict__ hvec,
const int* __restrict__ q_of,
double* __restrict__ svec,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows || c >= max_q) { return; }
int q = q_of[row];
double acc = 0.0;
int abase = row * max_q * max_q;
for (int j = 0; j < q; ++j) {
acc += ainv[abase + c * max_q + j] * hvec[row * max_q + j];
}
svec[row * max_q + c] = acc;
}
extern "C" __global__ void arrow_sae_frame_scatter_h(
const double* __restrict__ svec,
const int* __restrict__ htb_ptr,
const double* __restrict__ htb,
const int* __restrict__ q_of,
double* __restrict__ out,
int k,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int a = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows || a >= k) { return; }
int q = q_of[row];
int hbase = htb_ptr[row];
double acc = 0.0;
for (int c = 0; c < q; ++c) {
acc += htb[hbase + c * k + a] * svec[row * max_q + c];
}
atomicAdd(&out[a], -acc);
}
/* Frame Jacobi diagonal subtraction: diag[a] -= Σ_c Σ_d H_tβ[c,a]·ainv[c,d]·H_tβ[d,a]. */
extern "C" __global__ void arrow_sae_frame_diag_sub(
double* __restrict__ diag,
const double* __restrict__ ainv,
const int* __restrict__ htb_ptr,
const double* __restrict__ htb,
const int* __restrict__ q_of,
int k,
int max_q,
int n_rows
) {
int row = blockIdx.y;
int a = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= n_rows || a >= k) { return; }
int q = q_of[row];
int hbase = htb_ptr[row];
int abase = row * max_q * max_q;
double quad = 0.0;
for (int c = 0; c < q; ++c) {
double hc = htb[hbase + c * k + a];
for (int d = 0; d < q; ++d) {
quad += hc * ainv[abase + c * max_q + d] * htb[hbase + d * k + a];
}
}
atomicAdd(&diag[a], -quad);
}
"#;
fn pcg_vector_module(
ctx: &Arc<CudaContext>,
) -> Result<&'static Arc<CudaModule>, ArrowSchurGpuFailure> {
static CACHE: crate::gpu::device_cache::PtxModuleCache =
crate::gpu::device_cache::PtxModuleCache::new();
CACHE
.get_or_compile(ctx, "arrow_pcg_vector", PCG_VECTOR_KERNEL_SOURCE)
.map_err(|err| {
// #1551: an NVRTC compile / module-load failure of
// PCG_VECTOR_KERNEL_SOURCE means the device SAE PCG cannot run;
// log it (the historical silent collapse to `Unavailable` is what
// masked the missing `--gpu-architecture` for so long) and fall
// back to the CPU.
log::warn!("[#1551] pcg_vector_module get_or_compile failed: {err}");
ArrowSchurGpuFailure::Unavailable
})
}
fn pcg_launch_config(n: usize) -> Result<LaunchConfig, ArrowSchurGpuFailure> {
let threads = 256u32;
let blocks = ((n as u32).saturating_add(threads - 1) / threads).max(1);
Ok(LaunchConfig {
grid_dim: (blocks, 1, 1),
block_dim: (threads, 1, 1),
shared_mem_bytes: 0,
})
}
fn launch_jacobi_mul(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
inv_diag: &CudaSlice<f64>,
r: &CudaSlice<f64>,
z: &mut CudaSlice<f64>,
n: usize,
) -> Result<(), ArrowSchurGpuFailure> {
let kernel = module
.load_function("arrow_pcg_jacobi_mul")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let n_i32 = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let mut builder = stream.launch_builder(&kernel);
builder.arg(inv_diag).arg(r).arg(z).arg(&n_i32);
// SAFETY: all buffers have length n and belong to `stream`; the kernel only
// reads/writes indices `< n`.
unsafe { builder.launch(pcg_launch_config(n)?) }
.map(drop)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
}
fn launch_update_p(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
z: &CudaSlice<f64>,
beta: f64,
p: &mut CudaSlice<f64>,
n: usize,
) -> Result<(), ArrowSchurGpuFailure> {
let kernel = module
.load_function("arrow_pcg_update_p")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let n_i32 = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let mut builder = stream.launch_builder(&kernel);
builder.arg(z).arg(&beta).arg(p).arg(&n_i32);
// SAFETY: z/p both have length n and belong to `stream`; the kernel only
// reads/writes indices `< n`.
unsafe { builder.launch(pcg_launch_config(n)?) }
.map(drop)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
}
struct DeviceSaePcgBuffers {
row_ptr: CudaSlice<i32>,
beta_base: CudaSlice<i32>,
phi: CudaSlice<f64>,
jac_ptr: CudaSlice<i32>,
jac: CudaSlice<f64>,
smooth_offsets: CudaSlice<i32>,
smooth_m: CudaSlice<i32>,
smooth_ptr: CudaSlice<i32>,
smooth_data: CudaSlice<f64>,
g_row_off: CudaSlice<i32>,
g_col_off: CudaSlice<i32>,
g_rows: CudaSlice<i32>,
g_cols: CudaSlice<i32>,
g_ptr: CudaSlice<i32>,
g_data: CudaSlice<f64>,
ainv: CudaSlice<f64>,
u: CudaSlice<f64>,
w: CudaSlice<f64>,
v: CudaSlice<f64>,
n_rows: usize,
p: usize,
k: usize,
max_q: usize,
smooth_blocks: usize,
g_blocks: usize,
}
fn checked_i32(value: usize) -> Result<i32, ArrowSchurGpuFailure> {
to_i32(value).ok_or(ArrowSchurGpuFailure::Unavailable)
}
fn sae_penalty_diag_host(
data: &DeviceSaePcgData,
ridge_beta: f64,
) -> Result<Vec<f64>, ArrowSchurGpuFailure> {
let mut diag = vec![ridge_beta; data.beta_dim];
for block in &data.smooth_blocks {
let (rows, cols) = block.factor_a.dim();
if rows != cols {
return Err(ArrowSchurGpuFailure::Unavailable);
}
for row in 0..rows {
let coeff = block.factor_a[[row, row]];
let base = block
.global_offset
.checked_add(
row.checked_mul(data.p)
.ok_or(ArrowSchurGpuFailure::Unavailable)?,
)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let end = base
.checked_add(data.p)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
if end > diag.len() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
for channel in 0..data.p {
diag[base + channel] += coeff;
}
}
}
for block in &data.sparse_g_blocks {
if block.row_off != block.col_off {
continue;
}
let (rows, cols) = block.data.dim();
for row in 0..rows.min(cols) {
let coeff = block.data[[row, row]];
let beta_row = block
.row_off
.checked_add(row)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let base = beta_row
.checked_mul(data.p)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let end = base
.checked_add(data.p)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
if end > diag.len() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
for channel in 0..data.p {
diag[base + channel] += coeff;
}
}
}
Ok(diag)
}
fn flatten_device_sae_data(
sys: &ArrowSchurSystem,
data: &DeviceSaePcgData,
ridge_t: f64,
stream: &Arc<CudaStream>,
) -> Result<DeviceSaePcgBuffers, ArrowSchurGpuFailure> {
let n_rows = sys.rows.len();
let p = data.p;
let k = data.beta_dim;
if data.a_phi.len() != n_rows || data.local_jac.len() != n_rows {
return Err(ArrowSchurGpuFailure::Unavailable);
}
let mut row_ptr_host = Vec::with_capacity(n_rows + 1);
let mut beta_base_host = Vec::<i32>::new();
let mut phi_host = Vec::<f64>::new();
row_ptr_host.push(0_i32);
for row in data.a_phi.iter() {
for &(base, phi) in row {
beta_base_host.push(checked_i32(base)?);
phi_host.push(phi);
}
row_ptr_host.push(checked_i32(beta_base_host.len())?);
}
let mut jac_ptr_host = Vec::with_capacity(n_rows + 1);
let mut jac_host = Vec::<f64>::new();
let mut max_q = 0usize;
jac_ptr_host.push(0_i32);
for row_jac in data.local_jac.iter() {
if row_jac.len() % p != 0 {
return Err(ArrowSchurGpuFailure::Unavailable);
}
max_q = max_q.max(row_jac.len() / p);
jac_host.extend_from_slice(row_jac);
jac_ptr_host.push(checked_i32(jac_host.len())?);
}
if max_q == 0 {
return Err(ArrowSchurGpuFailure::Unavailable);
}
let mut smooth_offsets_host = Vec::with_capacity(data.smooth_blocks.len());
let mut smooth_m_host = Vec::with_capacity(data.smooth_blocks.len());
let mut smooth_ptr_host = Vec::with_capacity(data.smooth_blocks.len() + 1);
let mut smooth_data_host = Vec::<f64>::new();
smooth_ptr_host.push(0_i32);
for block in &data.smooth_blocks {
let (rows, cols) = block.factor_a.dim();
if rows != cols {
return Err(ArrowSchurGpuFailure::Unavailable);
}
smooth_offsets_host.push(checked_i32(block.global_offset)?);
smooth_m_host.push(checked_i32(rows)?);
for r in 0..rows {
for c in 0..cols {
smooth_data_host.push(block.factor_a[[r, c]]);
}
}
smooth_ptr_host.push(checked_i32(smooth_data_host.len())?);
}
let mut g_row_off_host = Vec::with_capacity(data.sparse_g_blocks.len());
let mut g_col_off_host = Vec::with_capacity(data.sparse_g_blocks.len());
let mut g_rows_host = Vec::with_capacity(data.sparse_g_blocks.len());
let mut g_cols_host = Vec::with_capacity(data.sparse_g_blocks.len());
let mut g_ptr_host = Vec::with_capacity(data.sparse_g_blocks.len() + 1);
let mut g_data_host = Vec::<f64>::new();
g_ptr_host.push(0_i32);
for block in &data.sparse_g_blocks {
let (rows, cols) = block.data.dim();
g_row_off_host.push(checked_i32(block.row_off)?);
g_col_off_host.push(checked_i32(block.col_off)?);
g_rows_host.push(checked_i32(rows)?);
g_cols_host.push(checked_i32(cols)?);
for r in 0..rows {
for c in 0..cols {
g_data_host.push(block.data[[r, c]]);
}
}
g_ptr_host.push(checked_i32(g_data_host.len())?);
}
let mut ainv_host = vec![0.0_f64; n_rows * max_q * max_q];
for (row_idx, row) in sys.rows.iter().enumerate() {
let q = data.local_jac[row_idx].len() / p;
if row.htt.dim() != (q, q) {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"SAE device PCG row {row_idx}: H_tt shape {:?} != ({q}, {q})",
row.htt.dim()
),
});
}
let mut block = row.htt.clone();
for d in 0..q {
block[[d, d]] += ridge_t;
}
let factor = crate::linalg::triangular::cholesky_factor_in_place(
block.view(),
crate::linalg::triangular::CholeskyGuard::NonnegativePivot,
)
.ok_or_else(|| {
let scale = row
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
ArrowSchurGpuFailure::RidgeBumpRequired {
row: row_idx,
bump: scale * f64::EPSILON.sqrt() * super::RIDGE_BUMP_EPS_MARGIN,
}
})?;
for col in 0..q {
let mut e = Array1::<f64>::zeros(q);
e[col] = 1.0;
let solved =
crate::linalg::triangular::cholesky_solve_vector(factor.view(), e.view());
for r in 0..q {
ainv_host[row_idx * max_q * max_q + r * max_q + col] = solved[r];
}
}
}
Ok(DeviceSaePcgBuffers {
row_ptr: stream
.clone_htod(&row_ptr_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
beta_base: stream
.clone_htod(&beta_base_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
phi: stream
.clone_htod(&phi_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
jac_ptr: stream
.clone_htod(&jac_ptr_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
jac: stream
.clone_htod(&jac_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
smooth_offsets: stream
.clone_htod(&smooth_offsets_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
smooth_m: stream
.clone_htod(&smooth_m_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
smooth_ptr: stream
.clone_htod(&smooth_ptr_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
smooth_data: stream
.clone_htod(&smooth_data_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
g_row_off: stream
.clone_htod(&g_row_off_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
g_col_off: stream
.clone_htod(&g_col_off_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
g_rows: stream
.clone_htod(&g_rows_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
g_cols: stream
.clone_htod(&g_cols_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
g_ptr: stream
.clone_htod(&g_ptr_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
g_data: stream
.clone_htod(&g_data_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
ainv: stream
.clone_htod(&ainv_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
u: stream
.alloc_zeros::<f64>(n_rows * p)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
w: stream
.alloc_zeros::<f64>(n_rows * max_q)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
v: stream
.alloc_zeros::<f64>(n_rows * max_q)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
n_rows,
p,
k,
max_q,
smooth_blocks: data.smooth_blocks.len(),
g_blocks: data.sparse_g_blocks.len(),
})
}
fn launch_sae_init(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
out: &mut CudaSlice<f64>,
x: &CudaSlice<f64>,
ridge: f64,
n: usize,
) -> Result<(), ArrowSchurGpuFailure> {
let kernel = module
.load_function("arrow_sae_init")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let n_i32 = checked_i32(n)?;
let mut builder = stream.launch_builder(&kernel);
builder.arg(out).arg(x).arg(&ridge).arg(&n_i32);
// SAFETY: `out` and `x` are live device buffers with at least `n`
// entries on `stream`; the kernel writes one in-bounds element per
// launched index below `n`.
unsafe { builder.launch(pcg_launch_config(n)?) }
.map(drop)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
}
fn launch_sae_penalty_matvec(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
buffers: &mut DeviceSaePcgBuffers,
x: &CudaSlice<f64>,
out: &mut CudaSlice<f64>,
ridge_beta: f64,
) -> Result<(), ArrowSchurGpuFailure> {
launch_sae_init(stream, module, out, x, ridge_beta, buffers.k)?;
if buffers.smooth_blocks > 0 {
let kernel = module
.load_function("arrow_sae_smooth_matvec")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let max_m = buffers.k;
let p_i32 = checked_i32(buffers.p)?;
let blocks_i32 = checked_i32(buffers.smooth_blocks)?;
let cfg = LaunchConfig {
grid_dim: (
((max_m as u32).saturating_add(255) / 256).max(1),
checked_i32(buffers.smooth_blocks)? as u32,
1,
),
block_dim: (256, 1, 1),
shared_mem_bytes: 0,
};
let mut builder = stream.launch_builder(&kernel);
builder
.arg(x)
.arg(&mut *out)
.arg(&buffers.smooth_offsets)
.arg(&buffers.smooth_m)
.arg(&buffers.smooth_ptr)
.arg(&buffers.smooth_data)
.arg(&p_i32)
.arg(&blocks_i32);
// SAFETY: smooth block metadata and dense smooth data were flattened
// into live device buffers; the 2D grid covers only declared block
// and coefficient-channel work items, and the kernel bounds-checks
// against each block's stored size.
unsafe { builder.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
if buffers.g_blocks > 0 {
let kernel = module
.load_function("arrow_sae_sparse_g_matvec")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let max_work = buffers
.k
.checked_div(buffers.p)
.unwrap_or(0)
.saturating_mul(buffers.p);
let p_i32 = checked_i32(buffers.p)?;
let blocks_i32 = checked_i32(buffers.g_blocks)?;
let cfg = LaunchConfig {
grid_dim: (
((max_work as u32).saturating_add(255) / 256).max(1),
checked_i32(buffers.g_blocks)? as u32,
1,
),
block_dim: (256, 1, 1),
shared_mem_bytes: 0,
};
let mut builder = stream.launch_builder(&kernel);
builder
.arg(x)
.arg(&mut *out)
.arg(&buffers.g_row_off)
.arg(&buffers.g_col_off)
.arg(&buffers.g_rows)
.arg(&buffers.g_cols)
.arg(&buffers.g_ptr)
.arg(&buffers.g_data)
.arg(&p_i32)
.arg(&blocks_i32);
// SAFETY: sparse G block metadata/data are live device buffers built
// from host CSR-like block descriptors; the launch dimensions cover
// declared block work only and the kernel checks row/column bounds
// before reading or accumulating.
unsafe { builder.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
Ok(())
}
fn launch_sae_row_schur_sub(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
buffers: &mut DeviceSaePcgBuffers,
x: &CudaSlice<f64>,
out: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let p_i32 = checked_i32(buffers.p)?;
let max_q_i32 = checked_i32(buffers.max_q)?;
let n_rows_i32 = checked_i32(buffers.n_rows)?;
let cfg_p_rows = LaunchConfig {
grid_dim: (
((buffers.p as u32).saturating_add(255) / 256).max(1),
checked_i32(buffers.n_rows)? as u32,
1,
),
block_dim: (256, 1, 1),
shared_mem_bytes: 0,
};
let gather = module
.load_function("arrow_sae_gather_u")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
{
let mut builder = stream.launch_builder(&gather);
builder
.arg(x)
.arg(&buffers.row_ptr)
.arg(&buffers.beta_base)
.arg(&buffers.phi)
.arg(&mut buffers.u)
.arg(&p_i32)
.arg(&n_rows_i32);
// SAFETY: `x`, row pointers, beta offsets, basis rows, and `u` are
// live device buffers sized for `n_rows` by `p`; the kernel guards
// row/channel indices before gathering.
unsafe { builder.launch(cfg_p_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
let cfg_q_rows = LaunchConfig {
grid_dim: (
((buffers.max_q as u32).saturating_add(255) / 256).max(1),
checked_i32(buffers.n_rows)? as u32,
1,
),
block_dim: (256, 1, 1),
shared_mem_bytes: 0,
};
let apply_l = module
.load_function("arrow_sae_apply_l")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
{
let mut builder = stream.launch_builder(&apply_l);
builder
.arg(&buffers.u)
.arg(&buffers.jac_ptr)
.arg(&buffers.jac)
.arg(&mut buffers.w)
.arg(&p_i32)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: `u`, Jacobian row pointers/data, and `w` are live buffers
// sized for the `(n_rows, p)` to `(n_rows, max_q)` multiply; the
// kernel checks row and local-coordinate bounds.
unsafe { builder.launch(cfg_q_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
let apply_ainv = module
.load_function("arrow_sae_apply_ainv")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
{
let mut builder = stream.launch_builder(&apply_ainv);
builder
.arg(&buffers.ainv)
.arg(&buffers.w)
.arg(&mut buffers.v)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: `ainv`, `w`, and `v` are live device buffers sized for
// `n_rows * max_q`; the kernel guards all row/local-coordinate
// indices before reading or writing.
unsafe { builder.launch(cfg_q_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
let scatter = module
.load_function("arrow_sae_scatter_sub")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
{
let mut builder = stream.launch_builder(&scatter);
builder
.arg(&buffers.v)
.arg(&buffers.jac_ptr)
.arg(&buffers.jac)
.arg(&buffers.row_ptr)
.arg(&buffers.beta_base)
.arg(&buffers.phi)
.arg(out)
.arg(&p_i32)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: `v`, Jacobian metadata, row pointers, beta offsets, basis
// rows, and `out` are live buffers for `n_rows` by `p`; scatter
// indices are checked against row and channel bounds in the kernel.
unsafe { builder.launch(cfg_p_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
Ok(())
}
fn launch_sae_diag_sub(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
buffers: &DeviceSaePcgBuffers,
diag: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let kernel = module
.load_function("arrow_sae_diag_sub")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let p_i32 = checked_i32(buffers.p)?;
let max_q_i32 = checked_i32(buffers.max_q)?;
let n_rows_i32 = checked_i32(buffers.n_rows)?;
let cfg = LaunchConfig {
grid_dim: (
((buffers.p as u32).saturating_add(255) / 256).max(1),
checked_i32(buffers.n_rows)? as u32,
1,
),
block_dim: (256, 1, 1),
shared_mem_bytes: 0,
};
let mut builder = stream.launch_builder(&kernel);
builder
.arg(diag)
.arg(&buffers.ainv)
.arg(&buffers.jac_ptr)
.arg(&buffers.jac)
.arg(&buffers.row_ptr)
.arg(&buffers.beta_base)
.arg(&buffers.phi)
.arg(&p_i32)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: diagonal output and all read-only SAE row metadata buffers are
// live on `stream` with sizes matching `n_rows`, `p`, and `max_q`; the
// kernel bounds-checks its flattened work index.
unsafe { builder.launch(cfg) }
.map(drop)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
}
fn launch_sae_matvec(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
buffers: &mut DeviceSaePcgBuffers,
x: &CudaSlice<f64>,
out: &mut CudaSlice<f64>,
ridge_beta: f64,
) -> Result<(), ArrowSchurGpuFailure> {
launch_sae_penalty_matvec(stream, module, buffers, x, out, ridge_beta)?;
launch_sae_row_schur_sub(stream, module, buffers, x, out)
}
/// Pack `D + ρ_t I`, `B`, and `g` into the strided `(n × P_MAX × P_MAX)`
/// / `(n × P_MAX × R_TEMPLATE)` / `(n × P_MAX)` layout the fused kernel
/// expects. Entries outside the runtime `(p, r)` window stay at zero so
/// the kernel's per-element loops are safe to no-op there.
fn pack_fused_host(
sys: &ArrowSchurSystem,
ridge_t: f64,
p_max: usize,
r_template: usize,
) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let mut d_buf = vec![0.0_f64; n * p_max * p_max];
let mut b_buf = vec![0.0_f64; n * p_max * r_template];
let mut g_buf = vec![0.0_f64; n * p_max];
for (i, row) in sys.rows.iter().enumerate() {
// D_i + ρI, column-major in P_MAX×P_MAX strided block.
for col in 0..d {
let base = (i * p_max + col) * p_max;
for r in 0..d {
let mut value = row.htt[[r, col]];
if r == col {
value += ridge_t;
}
d_buf[base + r] = value;
}
}
// B_i in P_MAX×R_TEMPLATE strided block.
for col in 0..k {
let base = (i * p_max + col) * p_max;
for r in 0..d {
b_buf[base + r] = row.htbeta[[r, col]];
}
}
// g_i in P_MAX strided vector.
let g_base = i * p_max;
for r in 0..d {
g_buf[g_base + r] = row.gt[r];
}
}
(d_buf, b_buf, g_buf)
}
// -----------------------------------------------------------------------
// #1017 Phase 3: across-iteration device residency.
//
// `solve()` re-packs and re-uploads `D` (`H_tt`), `B` (`H_tβ`) and `g`,
// then re-runs the per-row POTRF and the border Schur factorization on
// EVERY call. For the SAE joint inner Newton at a frozen gate/basis frame
// the Hessian blocks `D`, `B`, `H_ββ` are CONSTANT across the inner loop —
// only the gradient `g = r(z) = H z − g₀` changes per iterate. So the
// factor work (`O(n·d³ + p³)`) and the dominant `O(n·d·p)` cross-block
// upload are pure waste when repeated per iterate.
//
// `ResidentArrowFrame` performs that constant work ONCE at construction:
// upload+ridge+POTRF of `D` (keeping `L_i` resident in `l_dev`), the
// forward solve `Y_i = L_i^{-1} B_i` (kept resident in `y_dev`), and the
// Schur assembly + border POTRF (keeping `L_S` resident in `schur_dev`).
// Each subsequent `solve_gradient(g)` uploads only the `n·d` row gradient,
// runs the cheap residual path — `u_i = L_i^{-1} g_i` (one batched TRSM),
// Schur RHS `−g_β + Σ Y_iᵀ u_i`, `δβ = L_S^{-T} L_S^{-1} rhs` (two TRSM,
// NO POTRF), back-sub `δt_i = −L_i^{-T}(u_i + Y_i δβ)` — and reads back only
// `δ` and the cached log|H|. The heavy buffers never leave the device
// across iterations; the per-iterate host transfer is `O(n·d + p)`, not
// `O(n·d·p)`. Numerics are bit-identical to a `solve()` at the same
// `(D, B, H_ββ, g, ridge_t, ridge_beta)` because the factor buffers and the
// helper kernels are the same; the resident path merely SKIPS re-deriving
// the parts that do not depend on `g`. The CPU dense reference
// (`solve_arrow_newton_step_dense_reference`) is the parity oracle.
pub(super) struct ResidentArrowFrame {
n: usize,
d: usize,
k: usize,
stream: Arc<CudaStream>,
blas: CudaBlas,
/// Per-row lower Cholesky factors `L_i` of `H_tt + ρ_t I`, stacked
/// column-major (`n` tiles of `d×d`). Resident across iterations.
l_dev: CudaSlice<f64>,
/// Whitened cross blocks `Y_i = L_i^{-1} H_tβ^(i)`, stacked column-major
/// (`n` tiles of `d×k`). Resident across iterations.
y_dev: CudaSlice<f64>,
/// Lower Cholesky factor `L_S` of the reduced Schur complement
/// `S_β = H_ββ + ρ_β I − Σ_i Y_iᵀ Y_i`. Resident across iterations.
schur_dev: CudaSlice<f64>,
/// `log|H| = 2 Σ log L_{i,jj} + 2 Σ log L_{S,aa}`, constant for the
/// frame (depends only on the factored Hessian, not on `g`).
log_det_hessian: f64,
}
impl ResidentArrowFrame {
/// Upload the constant Hessian blocks and perform the one-time factor
/// work (`POTRF(D)`, `Y_i = L_i^{-1} B_i`, Schur assembly + border
/// `POTRF`). The frame then serves cheap per-gradient solves.
pub(super) fn new(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<Self, ArrowSchurGpuFailure> {
if ridge_t.is_nan() || ridge_beta.is_nan() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: "ridge is NaN".to_string(),
});
}
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let runtime = route_through_gpu(DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n })
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let stream = crate::gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
.and_then(|ctx| ctx.new_stream().ok())
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let solver =
DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blas =
CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// Upload the constant blocks. `g` is uploaded per-gradient, not here.
let (d_host, b_host, _g_host) = pack_host(sys, ridge_t);
let mut l_dev = stream
.clone_htod(&d_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut y_dev = stream
.clone_htod(&b_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// POTRF(D) → L_i, kept resident in l_dev.
let info_host = potrf_batched(&solver, &stream, d, n, &mut l_dev)?;
if let Some(idx) = info_host.iter().position(|info| *info != 0) {
let pivot = info_host[idx];
let scale = sys.rows[idx]
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
return Err(ArrowSchurGpuFailure::RidgeBumpRequired {
row: idx,
bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
});
}
// Y_i = L_i^{-1} B_i, in place over y_dev. Kept resident.
trsm_batched_lower_inplace(&blas, &stream, d, n, k, &l_dev, &mut y_dev)?;
// Schur assembly S_β = (H_ββ + ρ_β I) − Σ Y_iᵀ Y_i, then POTRF → L_S.
// The RHS accumulation is folded into the gradient path; here we
// only need the (gradient-independent) Schur factor, so accumulate
// into a throwaway rhs buffer.
let schur_init: Vec<f64> = {
let mut tmp = Vec::with_capacity(k * k);
for col in 0..k {
for row in 0..k {
let mut v = sys.hbb[[row, col]];
if row == col {
v += ridge_beta;
}
tmp.push(v);
}
}
tmp
};
let mut schur_dev = stream
.clone_htod(&schur_init)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// A zero u-stack makes `Σ Y_iᵀ u_i = 0`, so only the `−Σ Y_iᵀ Y_i`
// Schur term is accumulated (the rhs is rebuilt per gradient).
let zero_u = stream
.clone_htod(&vec![0.0_f64; n * d])
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut throwaway_rhs = stream
.clone_htod(&vec![0.0_f64; k])
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
accumulate_schur(
&blas,
d,
k,
n,
&y_dev,
&zero_u,
&mut schur_dev,
&mut throwaway_rhs,
)?;
let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
if info != 0 {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("Schur Cholesky failed at pivot {info}"),
});
}
// log|H| from the resident factors (constant for the frame).
let l_local_host = stream
.clone_dtoh(&l_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let l_schur_host = stream
.clone_dtoh(&schur_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut log_det = 0.0_f64;
for i in 0..n {
let base = i * d * d;
for j in 0..d {
log_det += l_local_host[base + j * d + j].ln();
}
}
for j in 0..k {
log_det += l_schur_host[j * k + j].ln();
}
log_det *= 2.0;
Ok(Self {
n,
d,
k,
stream,
blas,
l_dev,
y_dev,
schur_dev,
log_det_hessian: log_det,
})
}
#[inline]
pub(super) fn log_det_hessian(&self) -> f64 {
self.log_det_hessian
}
/// Solve `H δ = −gradient` for a fresh gradient `(g_t, g_β)` reusing the
/// resident factors. Uploads only `g_t` (`n·d` scalars); reads back only
/// `δ`. No POTRF runs here — all factorization is amortized into `new`.
pub(super) fn solve_gradient(
&self,
g_t: &[f64],
g_beta: &[f64],
) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
let n = self.n;
let d = self.d;
let k = self.k;
if g_t.len() != n * d || g_beta.len() != k {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"resident gradient shape mismatch: g_t={} (want {}), g_beta={} (want {})",
g_t.len(),
n * d,
g_beta.len(),
k
),
});
}
// Upload the per-iterate row gradient → u_i = L_i^{-1} g_i in place.
let mut u_dev = self
.stream
.clone_htod(&g_t.to_vec())
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
trsm_batched_lower_inplace(&self.blas, &self.stream, d, n, 1, &self.l_dev, &mut u_dev)?;
// Schur RHS = −g_β + Σ_i Y_iᵀ u_i. Reuse the resident Schur factor
// (no POTRF, and skip the −Σ Y_iᵀ Y_i GEMM already baked into L_S).
let rhs_init: Vec<f64> = g_beta.iter().map(|v| -v).collect();
let mut rhs_dev = self
.stream
.clone_htod(&rhs_init)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
accumulate_schur_rhs_only(&self.blas, d, k, n, &self.y_dev, &u_dev, &mut rhs_dev)?;
// δβ ← L_S^{-T} L_S^{-1} rhs using the resident border factor.
trsm_single(
&self.blas,
&self.stream,
k,
&self.schur_dev,
&mut rhs_dev,
false,
false,
)?;
trsm_single(
&self.blas,
&self.stream,
k,
&self.schur_dev,
&mut rhs_dev,
false,
true,
)?;
let delta_beta_host = self
.stream
.clone_dtoh(&rhs_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let delta_beta = Array1::from_vec(delta_beta_host);
// Back-sub δt_i = −L_i^{-T}(u_i + Y_i δβ).
accumulate_back_sub_rhs(&self.blas, d, k, n, &self.y_dev, &rhs_dev, &mut u_dev)?;
trsm_batched_lower_inplace_transposed(
&self.blas,
&self.stream,
d,
n,
1,
&self.l_dev,
&mut u_dev,
)?;
let x_host = self
.stream
.clone_dtoh(&u_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut delta_t = Array1::<f64>::zeros(n * d);
for (i, v) in x_host.iter().enumerate() {
delta_t[i] = -*v;
}
Ok(ArrowSchurGpuSolution {
delta_t,
delta_beta,
log_det_hessian: self.log_det_hessian,
})
}
}
pub(super) fn solve_fused(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let plan = crate::gpu::kernels::arrow_schur_nvrtc::plan_fused_launch(n, d, k)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let p_max = plan.p_max;
let r_template = plan.r_template;
let runtime = crate::gpu::linalg_dispatch::route_through_gpu(
crate::gpu::linalg_dispatch::DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n },
)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let ctx = crate::gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let stream = ctx
.new_stream()
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let cap = &runtime.device.capability;
let key = crate::gpu::kernels::arrow_schur_nvrtc::FusedModuleCacheKey {
cc_major: cap.compute_major,
cc_minor: cap.compute_minor,
p_max: p_max as u32,
r_template: r_template as u32,
};
let module = fused_module_for(&ctx, key)?;
let forward = module
.load_function("arrow_schur_forward_pgroup")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let back_sub = module
.load_function("arrow_schur_back_sub_pgroup")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// ----- Upload packed D, B, g -----
let (d_host, b_host, g_host) = pack_fused_host(sys, ridge_t, p_max, r_template);
let d_dev = stream
.clone_htod(&d_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let b_dev = stream
.clone_htod(&b_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let g_dev = stream
.clone_htod(&g_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut l_out = stream
.alloc_zeros::<f64>(n * p_max * p_max)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut u_out = stream
.alloc_zeros::<f64>(n * p_max)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut y_out = stream
.alloc_zeros::<f64>(n * p_max * r_template)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut partial_s = stream
.alloc_zeros::<f64>(plan.partial_s_doubles)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut partial_r = stream
.alloc_zeros::<f64>(plan.partial_r_doubles)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut status_dev = stream
.alloc_zeros::<i32>(n)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// ----- Launch forward kernel: 1 block per row, P_MAX threads -----
let cfg = LaunchConfig {
grid_dim: (plan.blocks, 1, 1),
block_dim: (plan.threads_per_block, 1, 1),
shared_mem_bytes: 0,
};
let n_i32 = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let p_i32 = to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let r_i32 = to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let ridge_arg = ridge_t;
{
let mut builder = stream.launch_builder(&forward);
builder
.arg(&d_dev)
.arg(&b_dev)
.arg(&g_dev)
.arg(&n_i32)
.arg(&p_i32)
.arg(&r_i32)
.arg(&ridge_arg)
.arg(&mut l_out)
.arg(&mut u_out)
.arg(&mut y_out)
.arg(&mut partial_s)
.arg(&mut partial_r)
.arg(&mut status_dev);
// SAFETY: all buffers were just allocated on `stream` with sizes
// derived from `plan`; kernel parameter list matches the
// FORWARD_KERNEL_SOURCE signature.
unsafe { builder.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
stream
.synchronize()
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// ----- Check per-block pivot status -----
let status_host = stream
.clone_dtoh(&status_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
if let Some(row) = status_host.iter().position(|s| *s != 0) {
let pivot = status_host[row];
let scale = sys.rows[row]
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
return Err(ArrowSchurGpuFailure::RidgeBumpRequired {
row,
bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
});
}
// ----- Reduce partials on host into S_β and r_β -----
let partial_s_host = stream
.clone_dtoh(&partial_s)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let partial_r_host = stream
.clone_dtoh(&partial_r)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut schur_host = vec![0.0_f64; k * k];
for col in 0..k {
for row in 0..k {
let mut v = sys.hbb[[row, col]];
if row == col {
v += ridge_beta;
}
schur_host[col * k + row] = v;
}
}
let mut rhs_host: Vec<f64> = sys.gb.iter().map(|v| -v).collect();
for i in 0..n {
// partial_S[i] stride is R_TEMPLATE × R_TEMPLATE column-major; we
// only read the leading (k × k) sub-block.
let s_base = i * r_template * r_template;
for col in 0..k {
let col_base = s_base + col * r_template;
let dst_col_base = col * k;
for row in 0..k {
schur_host[dst_col_base + row] -= partial_s_host[col_base + row];
}
}
let r_base = i * r_template;
for a in 0..k {
rhs_host[a] += partial_r_host[r_base + a];
}
}
// ----- Factor S_β on device (cuSOLVER), solve for δβ -----
let mut schur_dev = stream
.clone_htod(&schur_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut rhs_dev = stream
.clone_htod(&rhs_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let solver =
DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
if info != 0 {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("fused Schur Cholesky failed at pivot {info}"),
});
}
trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, false)?;
trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, true)?;
let delta_beta_host = stream
.clone_dtoh(&rhs_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let delta_beta = Array1::from_vec(delta_beta_host.clone());
// ----- Layer E: launch back-sub kernel using persisted L, u, Y -----
let mut delta_t_dev = stream
.alloc_zeros::<f64>(n * p_max)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let back_cfg = LaunchConfig {
grid_dim: (plan.blocks, 1, 1),
block_dim: (plan.threads_per_block, 1, 1),
shared_mem_bytes: 0,
};
{
let mut builder = stream.launch_builder(&back_sub);
builder
.arg(&l_out)
.arg(&u_out)
.arg(&y_out)
.arg(&rhs_dev)
.arg(&n_i32)
.arg(&p_i32)
.arg(&r_i32)
.arg(&mut delta_t_dev);
// SAFETY: kernel parameter list matches FORWARD_KERNEL_SOURCE
// back-sub signature; `rhs_dev` holds δβ in the leading k entries
// (R_TEMPLATE-strided indexing is column 0..k of the R-vector).
unsafe { builder.launch(back_cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
stream
.synchronize()
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let delta_t_host = stream
.clone_dtoh(&delta_t_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut delta_t = Array1::<f64>::zeros(n * d);
for i in 0..n {
let src_base = i * p_max;
let dst_base = i * d;
for r in 0..d {
delta_t[dst_base + r] = delta_t_host[src_base + r];
}
}
// ----- log|H| = 2·Σ log L_{i,jj} + 2·Σ log R_{β,aa} -----
let l_local_host = stream
.clone_dtoh(&l_out)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let l_schur_host = stream
.clone_dtoh(&schur_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut log_det = 0.0_f64;
for i in 0..n {
let base = i * p_max * p_max;
for j in 0..d {
log_det += l_local_host[base + j * p_max + j].ln();
}
}
for j in 0..k {
log_det += l_schur_host[j * k + j].ln();
}
log_det *= 2.0;
Ok(ArrowSchurGpuSolution {
delta_t,
delta_beta,
log_det_hessian: log_det,
})
}
/// Pre-compute `Y_i = L_i^{-1} H_tβ^(i)` via the fused forward kernel and
/// return a closure that evaluates the full Schur matvec
/// `S·x = (H_ββ + ρ·I)·x − Σ_i Y_i^T (Y_i·x)` for each PCG iteration.
///
/// The `Y_i` factors are kept in a host-side buffer after one GPU forward
/// pass. Each matvec call runs O(N·d·K) host loops over the pre-computed
/// buffer plus an optional `H_ββ·x` call (matrix-free or dense). This is
/// the first landing of the GPU matvec; a future iteration can move the
/// `Y_i·x` / `Y_i^T z_i` steps to cuBLAS batched GEMV.
pub(super) fn build_schur_matvec_backend(
sys: &ArrowSchurSystem,
ridge_t: f64,
ridge_beta: f64,
) -> Result<crate::solver::arrow_schur::GpuSchurMatvec, super::ArrowSchurGpuFailure> {
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let plan = crate::gpu::kernels::arrow_schur_nvrtc::plan_fused_launch(n, d, k)
.ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
let p_max = plan.p_max;
let r_template = plan.r_template;
let runtime = crate::gpu::linalg_dispatch::route_through_gpu(
crate::gpu::linalg_dispatch::DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n },
)
.ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
let ctx = crate::gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
.ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
let stream = ctx
.new_stream()
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let cap = &runtime.device.capability;
let key = crate::gpu::kernels::arrow_schur_nvrtc::FusedModuleCacheKey {
cc_major: cap.compute_major,
cc_minor: cap.compute_minor,
p_max: p_max as u32,
r_template: r_template as u32,
};
let module = fused_module_for(&ctx, key)?;
let forward = module
.load_function("arrow_schur_forward_pgroup")
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let (d_host, b_host, g_host) = pack_fused_host(sys, ridge_t, p_max, r_template);
let d_dev = stream
.clone_htod(&d_host)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let b_dev = stream
.clone_htod(&b_host)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let g_dev = stream
.clone_htod(&g_host)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let mut l_out = stream
.alloc_zeros::<f64>(n * p_max * p_max)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let mut u_out = stream
.alloc_zeros::<f64>(n * p_max)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let mut y_out = stream
.alloc_zeros::<f64>(n * p_max * r_template)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let mut partial_s = stream
.alloc_zeros::<f64>(plan.partial_s_doubles)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let mut partial_r = stream
.alloc_zeros::<f64>(plan.partial_r_doubles)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let mut status_dev = stream
.alloc_zeros::<i32>(n)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let cfg = LaunchConfig {
grid_dim: (plan.blocks, 1, 1),
block_dim: (plan.threads_per_block, 1, 1),
shared_mem_bytes: 0,
};
let n_i32 = to_i32(n).ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
let p_i32 = to_i32(d).ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
let r_i32 = to_i32(k).ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
let ridge_arg = ridge_t;
{
let mut builder = stream.launch_builder(&forward);
builder
.arg(&d_dev)
.arg(&b_dev)
.arg(&g_dev)
.arg(&n_i32)
.arg(&p_i32)
.arg(&r_i32)
.arg(&ridge_arg)
.arg(&mut l_out)
.arg(&mut u_out)
.arg(&mut y_out)
.arg(&mut partial_s)
.arg(&mut partial_r)
.arg(&mut status_dev);
// SAFETY: all buffers were allocated on `stream` with sizes
// derived from `plan`; parameter list matches FORWARD_KERNEL_SOURCE.
unsafe { builder.launch(cfg) }.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
}
stream
.synchronize()
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
let status_host = stream
.clone_dtoh(&status_dev)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
if let Some(row) = status_host.iter().position(|s| *s != 0) {
let pivot = status_host[row];
let scale = sys.rows[row]
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
return Err(super::ArrowSchurGpuFailure::RidgeBumpRequired {
row,
bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
});
}
// Download Y_i factors: n × p_max × r_template column-major per block.
let y_host = stream
.clone_dtoh(&y_out)
.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
// Capture H_ββ data for the closure. Use the matrix-free hook if present
// (SAE-manifold callers), otherwise fall back to the dense matrix rows.
let hbb_host: Vec<f64> = sys.hbb.iter().copied().collect();
let hbb_is_kk = sys.hbb.dim() == (k, k);
let hbb_matvec_opt = sys.hbb_matvec.clone();
let closure: crate::solver::arrow_schur::GpuSchurMatvec =
Arc::new(move |x: &Array1<f64>, out: &mut Array1<f64>| {
assert_eq!(x.len(), k, "gpu_schur_matvec: x.len() != k");
assert_eq!(out.len(), k, "gpu_schur_matvec: out.len() != k");
// (H_ββ + ρ·I)·x into out.
if let Some(ref mv) = hbb_matvec_opt {
mv(x.view(), out);
for a in 0..k {
out[a] += ridge_beta * x[a];
}
} else if hbb_is_kk {
// hbb_host row-major: hbb[a, b] = hbb_host[a * k + b].
for a in 0..k {
let mut acc = ridge_beta * x[a];
for b in 0..k {
acc += hbb_host[a * k + b] * x[b];
}
out[a] = acc;
}
} else {
for a in 0..k {
out[a] = ridge_beta * x[a];
}
}
// out[c] -= Σ_i (Y_i^T (Y_i·x))[c].
// Y_i column-major at y_host[i·p_max·r_template + col·p_max + row].
let mut z = vec![0.0_f64; d];
for i in 0..n {
let y_base = i * p_max * r_template;
for r in 0..d {
let mut acc = 0.0;
for c in 0..k {
acc += y_host[y_base + c * p_max + r] * x[c];
}
z[r] = acc;
}
for c in 0..k {
let mut acc = 0.0;
for r in 0..d {
acc += y_host[y_base + c * p_max + r] * z[r];
}
out[c] -= acc;
}
}
});
Ok(closure)
}
// ── #1017/#1026 frames-engaged device PCG ──────────────────────────────
struct DeviceSaeFrameBuffers {
// Smooth `λ S_k ⊗ I_{r_k}`.
s_off: CudaSlice<i32>,
s_m: CudaSlice<i32>,
s_r: CudaSlice<i32>,
s_ptr: CudaSlice<i32>,
s_data: CudaSlice<f64>,
s_blocks: usize,
// Data `G_{ij} ⊗ W_{ij}`.
g_off_i: CudaSlice<i32>,
g_off_j: CudaSlice<i32>,
g_ri: CudaSlice<i32>,
g_rj: CudaSlice<i32>,
g_mi: CudaSlice<i32>,
g_mj: CudaSlice<i32>,
g_ptr: CudaSlice<i32>,
g_data: CudaSlice<f64>,
w_ptr: CudaSlice<i32>,
w_data: CudaSlice<f64>,
g_blocks: usize,
g_max_work: usize,
// Per-row dense cross-block H_tβ^(i) + row q + factored ainv.
htb_ptr: CudaSlice<i32>,
htb: CudaSlice<f64>,
q_of: CudaSlice<i32>,
ainv: CudaSlice<f64>,
hvec: CudaSlice<f64>,
svec: CudaSlice<f64>,
n_rows: usize,
k: usize,
max_q: usize,
}
fn flatten_device_sae_frame_data(
sys: &ArrowSchurSystem,
data: &DeviceSaePcgData,
frame: &DeviceSaeFrameData,
ridge_t: f64,
stream: &Arc<CudaStream>,
) -> Result<DeviceSaeFrameBuffers, ArrowSchurGpuFailure> {
let n_rows = sys.rows.len();
let k = data.beta_dim;
if frame.row_htbeta.len() != n_rows
|| frame.ranks.len() != frame.basis_sizes.len()
|| frame.border_offsets.len() != frame.ranks.len()
|| data.smooth_blocks.len() != frame.smooth_ranks.len()
{
return Err(ArrowSchurGpuFailure::Unavailable);
}
// Smooth blocks.
let mut s_off = Vec::new();
let mut s_m = Vec::new();
let mut s_r = Vec::new();
let mut s_ptr = vec![0_i32];
let mut s_data = Vec::<f64>::new();
for (blk, &r) in data.smooth_blocks.iter().zip(frame.smooth_ranks.iter()) {
let (m, mc) = blk.factor_a.dim();
if m != mc {
return Err(ArrowSchurGpuFailure::Unavailable);
}
s_off.push(checked_i32(blk.global_offset)?);
s_m.push(checked_i32(m)?);
s_r.push(checked_i32(r)?);
for ri in 0..m {
for ci in 0..m {
s_data.push(blk.factor_a[[ri, ci]]);
}
}
s_ptr.push(checked_i32(s_data.len())?);
}
// Data blocks (g + w).
let mut g_off_i = Vec::new();
let mut g_off_j = Vec::new();
let mut g_ri = Vec::new();
let mut g_rj = Vec::new();
let mut g_mi = Vec::new();
let mut g_mj = Vec::new();
let mut g_ptr = vec![0_i32];
let mut g_data = Vec::<f64>::new();
let mut w_ptr = vec![0_i32];
let mut w_data = Vec::<f64>::new();
let mut g_max_work = 0usize;
for blk in &frame.frame_blocks {
let ri = frame.ranks[blk.atom_i];
let rj = frame.ranks[blk.atom_j];
let (mi, mj) = blk.g.dim();
if blk.w.dim() != (ri, rj) {
return Err(ArrowSchurGpuFailure::Unavailable);
}
g_off_i.push(checked_i32(frame.border_offsets[blk.atom_i])?);
g_off_j.push(checked_i32(frame.border_offsets[blk.atom_j])?);
g_ri.push(checked_i32(ri)?);
g_rj.push(checked_i32(rj)?);
g_mi.push(checked_i32(mi)?);
g_mj.push(checked_i32(mj)?);
for r in 0..mi {
for c in 0..mj {
g_data.push(blk.g[[r, c]]);
}
}
g_ptr.push(checked_i32(g_data.len())?);
for a in 0..ri {
for b in 0..rj {
w_data.push(blk.w[[a, b]]);
}
}
w_ptr.push(checked_i32(w_data.len())?);
g_max_work = g_max_work.max(mi * ri);
}
// Per-row dense cross-block + q + ainv (factored H_tt⁻¹).
let mut htb_ptr = vec![0_i32];
let mut htb = Vec::<f64>::new();
let mut q_of = Vec::<i32>::with_capacity(n_rows);
let mut max_q = 0usize;
for (i, slab) in frame.row_htbeta.iter().enumerate() {
let qi = sys.row_dims[i];
// A populated slab must be q_i × k row-major; an empty slab ⇒ q=0
// (the row contributes no reduced-Schur term).
let q_eff = if !slab.is_empty() && slab.len() == qi * k {
qi
} else {
0
};
q_of.push(checked_i32(q_eff)?);
max_q = max_q.max(q_eff);
if q_eff > 0 {
htb.extend_from_slice(slab);
}
htb_ptr.push(checked_i32(htb.len())?);
}
if max_q == 0 {
// No row contributes a reduced term — the system is pure-penalty.
// Still valid; give max_q=1 so the ainv buffer is non-empty.
max_q = 1;
}
let mut ainv = vec![0.0_f64; n_rows * max_q * max_q];
for (i, row) in sys.rows.iter().enumerate() {
let q = q_of[i] as usize;
if q == 0 {
continue;
}
if row.htt.dim() != (q, q) {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"framed SAE device PCG row {i}: H_tt shape {:?} != ({q}, {q})",
row.htt.dim()
),
});
}
let mut block = row.htt.clone();
for d in 0..q {
block[[d, d]] += ridge_t;
}
let factor = crate::linalg::triangular::cholesky_factor_in_place(
block.view(),
crate::linalg::triangular::CholeskyGuard::NonnegativePivot,
)
.ok_or_else(|| {
let scale = row
.htt
.diag()
.iter()
.map(|v| v.abs())
.fold(0.0_f64, f64::max)
.max(1.0);
ArrowSchurGpuFailure::RidgeBumpRequired {
row: i,
bump: scale * f64::EPSILON.sqrt() * super::RIDGE_BUMP_EPS_MARGIN,
}
})?;
for col in 0..q {
let mut e = Array1::<f64>::zeros(q);
e[col] = 1.0;
let solved =
crate::linalg::triangular::cholesky_solve_vector(factor.view(), e.view());
for r in 0..q {
ainv[i * max_q * max_q + r * max_q + col] = solved[r];
}
}
}
let htod_i = |v: &[i32]| {
stream
.clone_htod(v)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
};
let htod_f = |v: &[f64]| {
stream
.clone_htod(v)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
};
Ok(DeviceSaeFrameBuffers {
s_off: htod_i(&s_off)?,
s_m: htod_i(&s_m)?,
s_r: htod_i(&s_r)?,
s_ptr: htod_i(&s_ptr)?,
s_data: htod_f(&s_data)?,
s_blocks: data.smooth_blocks.len(),
g_off_i: htod_i(&g_off_i)?,
g_off_j: htod_i(&g_off_j)?,
g_ri: htod_i(&g_ri)?,
g_rj: htod_i(&g_rj)?,
g_mi: htod_i(&g_mi)?,
g_mj: htod_i(&g_mj)?,
g_ptr: htod_i(&g_ptr)?,
g_data: htod_f(&g_data)?,
w_ptr: htod_i(&w_ptr)?,
w_data: htod_f(&w_data)?,
g_blocks: frame.frame_blocks.len(),
g_max_work,
htb_ptr: htod_i(&htb_ptr)?,
htb: htod_f(&htb)?,
q_of: htod_i(&q_of)?,
ainv: htod_f(&ainv)?,
hvec: stream
.alloc_zeros::<f64>(n_rows * max_q)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
svec: stream
.alloc_zeros::<f64>(n_rows * max_q)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
n_rows,
k,
max_q,
})
}
fn sae_frame_penalty_diag_host(
data: &DeviceSaePcgData,
frame: &DeviceSaeFrameData,
ridge_beta: f64,
) -> Result<Vec<f64>, ArrowSchurGpuFailure> {
let mut diag = vec![ridge_beta; data.beta_dim];
// Smooth: diag[off + ia·r + ib] += S[ia,ia].
for (blk, &r) in data.smooth_blocks.iter().zip(frame.smooth_ranks.iter()) {
let m = blk.factor_a.nrows();
for ia in 0..m {
let coeff = blk.factor_a[[ia, ia]];
let base = blk.global_offset + ia * r;
for ib in 0..r {
if base + ib >= diag.len() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
diag[base + ib] += coeff;
}
}
}
// Data: on-diagonal atom blocks contribute g[li,li]·w[a,a].
for blk in &frame.frame_blocks {
if blk.atom_i != blk.atom_j {
continue;
}
let r = frame.ranks[blk.atom_i];
let off = frame.border_offsets[blk.atom_i];
let (mi, mj) = blk.g.dim();
for li in 0..mi.min(mj) {
let gii = blk.g[[li, li]];
let base = off + li * r;
for a in 0..r {
if base + a >= diag.len() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
diag[base + a] += gii * blk.w[[a, a]];
}
}
}
Ok(diag)
}
fn frame_grid(work: usize, n_rows: usize) -> Result<LaunchConfig, ArrowSchurGpuFailure> {
Ok(LaunchConfig {
grid_dim: (
((work as u32).saturating_add(255) / 256).max(1),
checked_i32(n_rows)? as u32,
1,
),
block_dim: (256, 1, 1),
shared_mem_bytes: 0,
})
}
fn launch_sae_frame_matvec(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
buffers: &mut DeviceSaeFrameBuffers,
x: &CudaSlice<f64>,
out: &mut CudaSlice<f64>,
ridge_beta: f64,
) -> Result<(), ArrowSchurGpuFailure> {
launch_sae_init(stream, module, out, x, ridge_beta, buffers.k)?;
// Smooth penalty.
if buffers.s_blocks > 0 {
let kernel = module
.load_function("arrow_sae_frame_smooth_matvec")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blocks_i32 = checked_i32(buffers.s_blocks)?;
let cfg = frame_grid(buffers.k, buffers.s_blocks)?;
let mut b = stream.launch_builder(&kernel);
b.arg(x)
.arg(&mut *out)
.arg(&buffers.s_off)
.arg(&buffers.s_m)
.arg(&buffers.s_r)
.arg(&buffers.s_ptr)
.arg(&buffers.s_data)
.arg(&blocks_i32);
// SAFETY: smooth block metadata/data are live device buffers; the grid
// covers (k channels × n_blocks) and the kernel bounds-checks m·r.
unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
// Data penalty.
if buffers.g_blocks > 0 {
let kernel = module
.load_function("arrow_sae_frame_g_matvec")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blocks_i32 = checked_i32(buffers.g_blocks)?;
let cfg = frame_grid(buffers.g_max_work.max(1), buffers.g_blocks)?;
let mut b = stream.launch_builder(&kernel);
b.arg(x)
.arg(&mut *out)
.arg(&buffers.g_off_i)
.arg(&buffers.g_off_j)
.arg(&buffers.g_ri)
.arg(&buffers.g_rj)
.arg(&buffers.g_mi)
.arg(&buffers.g_mj)
.arg(&buffers.g_ptr)
.arg(&buffers.g_data)
.arg(&buffers.w_ptr)
.arg(&buffers.w_data)
.arg(&blocks_i32);
// SAFETY: g/w block metadata/data are live device buffers; the grid
// covers (max m_i·r_i × n_blocks) and the kernel bounds-checks.
unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
// Reduced-Schur subtraction via dense per-row cross-blocks.
let k_i32 = checked_i32(buffers.k)?;
let max_q_i32 = checked_i32(buffers.max_q)?;
let n_rows_i32 = checked_i32(buffers.n_rows)?;
{
let kernel = module
.load_function("arrow_sae_frame_apply_h")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let cfg = frame_grid(buffers.max_q, buffers.n_rows)?;
let mut b = stream.launch_builder(&kernel);
b.arg(x)
.arg(&buffers.htb_ptr)
.arg(&buffers.htb)
.arg(&buffers.q_of)
.arg(&mut buffers.hvec)
.arg(&k_i32)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: dense cross-block + pointers + hvec are live buffers sized
// for (n_rows × max_q) / (n_rows × k); kernel guards q_i and k.
unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
{
let kernel = module
.load_function("arrow_sae_frame_apply_ainv")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let cfg = frame_grid(buffers.max_q, buffers.n_rows)?;
let mut b = stream.launch_builder(&kernel);
b.arg(&buffers.ainv)
.arg(&buffers.hvec)
.arg(&buffers.q_of)
.arg(&mut buffers.svec)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: ainv/hvec/svec are live buffers sized for n_rows·max_q²
// and n_rows·max_q; the kernel guards row/coord bounds.
unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
{
let kernel = module
.load_function("arrow_sae_frame_scatter_h")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let cfg = frame_grid(buffers.k, buffers.n_rows)?;
let mut b = stream.launch_builder(&kernel);
b.arg(&buffers.svec)
.arg(&buffers.htb_ptr)
.arg(&buffers.htb)
.arg(&buffers.q_of)
.arg(out)
.arg(&k_i32)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: svec/cross-block/out are live buffers; the kernel atomically
// accumulates into out[a] for a<k and reads c<q_i.
unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
}
Ok(())
}
fn launch_sae_frame_diag_sub(
stream: &Arc<CudaStream>,
module: &Arc<CudaModule>,
buffers: &DeviceSaeFrameBuffers,
diag: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let kernel = module
.load_function("arrow_sae_frame_diag_sub")
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let k_i32 = checked_i32(buffers.k)?;
let max_q_i32 = checked_i32(buffers.max_q)?;
let n_rows_i32 = checked_i32(buffers.n_rows)?;
let cfg = frame_grid(buffers.k, buffers.n_rows)?;
let mut b = stream.launch_builder(&kernel);
b.arg(diag)
.arg(&buffers.ainv)
.arg(&buffers.htb_ptr)
.arg(&buffers.htb)
.arg(&buffers.q_of)
.arg(&k_i32)
.arg(&max_q_i32)
.arg(&n_rows_i32);
// SAFETY: diag + cross-block + ainv live buffers; kernel guards a<k, c/d<q.
unsafe { b.launch(cfg) }
.map(drop)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
}
pub(super) fn solve_sae_matrix_free_pcg_framed(
sys: &ArrowSchurSystem,
data: &DeviceSaePcgData,
ridge_t: f64,
ridge_beta: f64,
rhs_beta: &Array1<f64>,
max_iterations: usize,
relative_tolerance: f64,
) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
let k = rhs_beta.len();
if k == 0 || data.beta_dim != k || sys.k != k {
return Err(ArrowSchurGpuFailure::Unavailable);
}
let frame = data
.frame
.as_ref()
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let runtime = crate::gpu::device_runtime::GpuRuntime::global()
.filter(|rt| {
rt.policy().reduced_schur_matvec_should_offload(
sys.rows.len(),
sys.k,
sys.d,
max_iterations,
)
})
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let ctx = crate::gpu::device_runtime::cuda_context_for(runtime.selected_device().ordinal)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let stream = ctx
.new_stream()
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let vector_module = pcg_vector_module(&ctx)?;
let mut buffers = flatten_device_sae_frame_data(sys, data, frame, ridge_t, &stream)?;
let rhs_norm = rhs_beta.iter().map(|v| v * v).sum::<f64>().sqrt();
if rhs_norm == 0.0 {
return Ok((Array1::<f64>::zeros(k), PcgDiagnostics::default()));
}
let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
let rhs_dev = stream
.clone_htod(
rhs_beta
.as_slice()
.ok_or(ArrowSchurGpuFailure::Unavailable)?,
)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let diag_host = sae_frame_penalty_diag_host(data, frame, ridge_beta)?;
let mut diag_dev = stream
.clone_htod(&diag_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
launch_sae_frame_diag_sub(&stream, vector_module, &buffers, &mut diag_dev)?;
let diag_host = stream
.clone_dtoh(&diag_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut inv_diag = Vec::with_capacity(k);
for (idx, &d) in diag_host.iter().enumerate() {
if !d.is_finite() || d <= 1.0e-18 {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"framed SAE GPU PCG: non-positive Jacobi diagonal at {idx}: {d:e}"
),
});
}
inv_diag.push(1.0 / d);
}
let inv_diag_dev = stream
.clone_htod(&inv_diag)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut x_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut r_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
device_copy(&blas, &stream, k, &rhs_dev, &mut r_dev)?;
let mut z_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
let mut p_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
device_copy(&blas, &stream, k, &z_dev, &mut p_dev)?;
let mut ap_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut rz = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
if rz <= 0.0 || !rz.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("framed SAE GPU PCG: non-positive initial rᵀM⁻¹r={rz:e}"),
});
}
let mut diag = PcgDiagnostics {
precond_apply_calls: 1,
stopping_reason: PcgStopReason::MaxIter,
..PcgDiagnostics::default()
};
for _ in 0..max_iterations.max(1) {
launch_sae_frame_matvec(
&stream,
vector_module,
&mut buffers,
&p_dev,
&mut ap_dev,
ridge_beta,
)?;
diag.matvec_calls += 1;
diag.iterations += 1;
let pap = device_dot(&blas, &stream, k, &p_dev, &ap_dev)?;
if pap <= 0.0 || !pap.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("framed SAE GPU PCG: non-positive curvature pᵀAp={pap:e}"),
});
}
let alpha = rz / pap;
device_axpy(&blas, &stream, k, alpha, &p_dev, &mut x_dev)?;
device_axpy(&blas, &stream, k, -alpha, &ap_dev, &mut r_dev)?;
let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
if r_norm <= tol {
diag.final_relative_residual = r_norm / rhs_norm;
diag.stopping_reason = PcgStopReason::Converged;
break;
}
launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
diag.precond_apply_calls += 1;
let rz_new = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
if rz_new <= 0.0 || !rz_new.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("framed SAE GPU PCG: non-positive rᵀM⁻¹r={rz_new:e}"),
});
}
let beta = rz_new / rz;
launch_update_p(&stream, vector_module, &z_dev, beta, &mut p_dev, k)?;
rz = rz_new;
}
if diag.stopping_reason != PcgStopReason::Converged {
let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
diag.final_relative_residual = r_norm / rhs_norm;
diag.stopping_reason = PcgStopReason::MaxIter;
}
let x = stream
.clone_dtoh(&x_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
Ok((Array1::from_vec(x), diag))
}
/// #1551 stage-isolating triage seam: run the framed reduced-Schur matvec
/// `out = S·x` ONCE on the device (no PCG, no offload-floor gate) and return
/// `out`, so a tiny hand-verifiable fixture can diff it against the CPU oracle
/// `sae_framed_schur_matvec_cpu` element-by-element to localize the structural
/// divergence to a single kernel stage. Returns `Unavailable` only when CUDA
/// is genuinely absent (so the test skips cleanly off-device).
pub(super) fn solve_sae_matrix_free_pcg(
sys: &ArrowSchurSystem,
data: &DeviceSaePcgData,
ridge_t: f64,
ridge_beta: f64,
rhs_beta: &Array1<f64>,
max_iterations: usize,
relative_tolerance: f64,
) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
let k = rhs_beta.len();
if k == 0 || data.beta_dim != k || sys.k != k {
return Err(ArrowSchurGpuFailure::Unavailable);
}
// #1017/#1026 GUARD: the legacy `⊗ I_p` kernel must NEVER receive framed
// data (factored `G ⊗ W_{ij}` + dense per-row cross blocks); decline so a
// mis-route falls back to the CPU rather than returning a wrong step.
if data.frame.is_some() {
return Err(ArrowSchurGpuFailure::Unavailable);
}
// #1017 Phase-1 dispatch re-key: this is the matrix-free SAE reduced-Schur
// PCG — the production hot path, not a single dense factorization. The
// dense-Direct floor `dense_hessian_work_target_is_gpu(n, k)` keys on
// `2·n·k²` and is the WRONG gate here: it ignores the per-row frame depth
// `d` (the M dimension that multiplies the per-apply work) and the
// `1/cg_iters` staging amortisation, so it both undercounts the SAE batched
// work `n·k·d` and applies a cold single-launch breakeven to an apply that
// reuses device-resident frames `max_iterations` times. Key instead on the
// CG-amortised total batched work — the same predicate the host injection
// gate (`maybe_inject_gpu_schur_matvec`) consults — so few-row/wide-`k`/
// modest-`d` LLM shapes register the real `n × k × d × cg_iters` arithmetic.
// Kernels and numerics are untouched; only where the matvec runs changes,
// and the host falls back to the bit-identical CPU matvec when this declines.
let runtime = crate::gpu::device_runtime::GpuRuntime::global()
.filter(|rt| {
rt.policy().reduced_schur_matvec_should_offload(
sys.rows.len(),
sys.k,
sys.d,
max_iterations,
)
})
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let ctx = crate::gpu::device_runtime::cuda_context_for(runtime.selected_device().ordinal)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let stream = ctx
.new_stream()
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let vector_module = pcg_vector_module(&ctx)?;
let mut buffers = flatten_device_sae_data(sys, data, ridge_t, &stream)?;
let rhs_norm = rhs_beta.iter().map(|v| v * v).sum::<f64>().sqrt();
if rhs_norm == 0.0 {
return Ok((Array1::<f64>::zeros(k), PcgDiagnostics::default()));
}
let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
let rhs_dev = stream
.clone_htod(
rhs_beta
.as_slice()
.ok_or(ArrowSchurGpuFailure::Unavailable)?,
)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let diag_host = sae_penalty_diag_host(data, ridge_beta)?;
let mut diag_dev = stream
.clone_htod(&diag_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
launch_sae_diag_sub(&stream, vector_module, &buffers, &mut diag_dev)?;
let diag_host = stream
.clone_dtoh(&diag_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut inv_diag = Vec::with_capacity(k);
for (idx, &d) in diag_host.iter().enumerate() {
if !d.is_finite() || d <= 1.0e-18 {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"SAE matrix-free GPU PCG: non-positive Schur Jacobi diagonal at {idx}: {d:e}"
),
});
}
inv_diag.push(1.0 / d);
}
let inv_diag_dev = stream
.clone_htod(&inv_diag)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut x_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut r_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
device_copy(&blas, &stream, k, &rhs_dev, &mut r_dev)?;
let mut z_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
let mut p_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
device_copy(&blas, &stream, k, &z_dev, &mut p_dev)?;
let mut ap_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut rz = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
if rz <= 0.0 || !rz.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("SAE matrix-free GPU PCG: non-positive initial rᵀM⁻¹r={rz:e}"),
});
}
let mut diag = PcgDiagnostics {
precond_apply_calls: 1,
stopping_reason: PcgStopReason::MaxIter,
..PcgDiagnostics::default()
};
for _ in 0..max_iterations.max(1) {
launch_sae_matvec(
&stream,
vector_module,
&mut buffers,
&p_dev,
&mut ap_dev,
ridge_beta,
)?;
diag.matvec_calls += 1;
diag.iterations += 1;
let pap = device_dot(&blas, &stream, k, &p_dev, &ap_dev)?;
if pap <= 0.0 || !pap.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("SAE matrix-free GPU PCG: non-positive curvature pᵀAp={pap:e}"),
});
}
let alpha = rz / pap;
device_axpy(&blas, &stream, k, alpha, &p_dev, &mut x_dev)?;
device_axpy(&blas, &stream, k, -alpha, &ap_dev, &mut r_dev)?;
let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
if r_norm <= tol {
diag.final_relative_residual = r_norm / rhs_norm;
diag.stopping_reason = PcgStopReason::Converged;
break;
}
launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
diag.precond_apply_calls += 1;
let rz_new = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
if rz_new <= 0.0 || !rz_new.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("SAE matrix-free GPU PCG: non-positive rᵀM⁻¹r={rz_new:e}"),
});
}
let beta = rz_new / rz;
launch_update_p(&stream, vector_module, &z_dev, beta, &mut p_dev, k)?;
rz = rz_new;
}
if diag.stopping_reason != PcgStopReason::Converged {
let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
diag.final_relative_residual = r_norm / rhs_norm;
diag.stopping_reason = PcgStopReason::MaxIter;
}
let x = stream
.clone_dtoh(&x_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
Ok((Array1::from_vec(x), diag))
}
pub(super) fn solve_reduced_beta_pcg_with_diagnostics(
s_acc: &ndarray::Array2<f64>,
rhs_beta: &Array1<f64>,
max_iterations: usize,
relative_tolerance: f64,
) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
let k = rhs_beta.len();
// #1017 dispatch re-key: this is an ITERATIVE device-resident PCG, not a
// single GEMV. `S` (k×k) is uploaded once and reused for `max_iterations`
// `S·p` GEMVs while only convergence scalars cross PCIe, so the staging
// cost is amortised over the whole CG solve. Gating on the flops of ONE
// `Gemv{k,k}` (`2·k²`) understates the work by the iteration count and
// declines shapes (e.g. k≈512) whose total iterated arithmetic
// `2·k²·iters` clears the device floor by orders of magnitude — the same
// single-launch-breakeven miskey #1017 fixed for the framed reduced-Schur
// matvec. Key on the CG-amortised total work via a `Gemm{k,k,iters}` whose
// `flops()` is exactly `2·k²·iters`; numerics and kernels are untouched,
// and the host falls back to the bit-identical CPU PCG when this declines.
let cg_iters = max_iterations.max(1);
let runtime = crate::gpu::linalg_dispatch::route_through_gpu(
crate::gpu::linalg_dispatch::DispatchOp::Gemm {
m: k,
n: k,
k: cg_iters,
},
)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let stream = crate::gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
.and_then(|ctx| ctx.new_stream().ok())
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let ctx = crate::gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let vector_module = pcg_vector_module(&ctx)?;
// Jacobi diagonal from S; must be strictly positive for SPD.
let mut inv_diag = vec![0.0_f64; k];
for j in 0..k {
let djj = s_acc[[j, j]];
if !(djj > 0.0) {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!(
"reduced-β GPU PCG: Jacobi diagonal S[{j},{j}]={djj:e} not positive"
),
});
}
inv_diag[j] = 1.0 / djj;
}
// Upload S column-major (S[row,col] at col*k + row).
let mut s_host = vec![0.0_f64; k * k];
for col in 0..k {
for row in 0..k {
s_host[col * k + row] = s_acc[[row, col]];
}
}
let s_dev = stream
.clone_htod(&s_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
// Steihaug truncated-CG with Jacobi preconditioner, host scalar
// recurrences and a device `S·p` matvec. The streaming reduced solve
// uses an unbounded trust region (pure CG to tolerance).
let rhs_norm = rhs_beta.iter().map(|v| v * v).sum::<f64>().sqrt();
if rhs_norm == 0.0 {
return Ok((Array1::<f64>::zeros(k), PcgDiagnostics::default()));
}
let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
// Device-resident PCG state. Only convergence scalars cross back during
// the loop; x/r/z/p/Sp stay on CUDA until the final solution download.
let mut x_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut r_dev = stream
.clone_htod(
rhs_beta
.as_slice()
.ok_or(ArrowSchurGpuFailure::Unavailable)?,
)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let inv_diag_dev = stream
.clone_htod(&inv_diag)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut z_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
let mut p_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
device_copy(&blas, &stream, k, &z_dev, &mut p_dev)?;
let mut sp_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut rz = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
let mut diag = PcgDiagnostics {
precond_apply_calls: 1,
stopping_reason: PcgStopReason::MaxIter,
..PcgDiagnostics::default()
};
if rz <= 0.0 || !rz.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("reduced-β GPU PCG: non-positive initial rᵀM⁻¹r={rz:e}"),
});
}
let max_iters = max_iterations.max(1);
for _ in 0..max_iters {
// sp = S · p (device GEMV, S column-major k×k, op = N).
let gemv_cfg = GemvConfig::<f64> {
trans: cublasOperation_t::CUBLAS_OP_N,
m: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
alpha: 1.0,
lda: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
incx: 1,
beta: 0.0,
incy: 1,
};
// SAFETY: s_dev is k×k column-major, p_dev / sp_dev length k.
unsafe { blas.gemv(gemv_cfg, &s_dev, &p_dev, &mut sp_dev) }
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
diag.matvec_calls += 1;
diag.iterations += 1;
let p_sp = device_dot(&blas, &stream, k, &p_dev, &sp_dev)?;
if !(p_sp > 0.0) {
// Non-positive curvature on a (proximal-ridged) SPD system means
// numerical breakdown; surface so the caller escalates.
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("reduced-β GPU PCG: non-positive curvature pᵀSp={p_sp:e}"),
});
}
let alpha = rz / p_sp;
device_axpy(&blas, &stream, k, alpha, &p_dev, &mut x_dev)?;
device_axpy(&blas, &stream, k, -alpha, &sp_dev, &mut r_dev)?;
let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
if r_norm <= tol {
diag.final_relative_residual = r_norm / rhs_norm;
diag.stopping_reason = PcgStopReason::Converged;
break;
}
launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
diag.precond_apply_calls += 1;
let rz_new = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
if rz_new <= 0.0 || !rz_new.is_finite() {
return Err(ArrowSchurGpuFailure::SchurFactorFailed {
reason: format!("reduced-β GPU PCG: non-positive rᵀM⁻¹r={rz_new:e}"),
});
}
let beta = rz_new / rz;
launch_update_p(&stream, vector_module, &z_dev, beta, &mut p_dev, k)?;
rz = rz_new;
}
if diag.stopping_reason != PcgStopReason::Converged {
let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
diag.final_relative_residual = r_norm / rhs_norm;
diag.stopping_reason = PcgStopReason::MaxIter;
}
let x = stream
.clone_dtoh(&x_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
Ok((Array1::from_vec(x), diag))
}
fn device_copy(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
n: usize,
src: &CudaSlice<f64>,
dst: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let (src_ptr, _src_rec) = src.device_ptr(stream);
let (dst_ptr, _dst_rec) = dst.device_ptr_mut(stream);
// SAFETY: src and dst are live device allocations on this stream with at
// least n contiguous f64 entries and unit stride.
let status = unsafe {
cudarc::cublas::sys::cublasDcopy_v2(
*blas.handle(),
n_i,
src_ptr as *const f64,
1,
dst_ptr as *mut f64,
1,
)
};
if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
Ok(())
} else {
Err(ArrowSchurGpuFailure::Unavailable)
}
}
fn device_axpy(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
n: usize,
alpha: f64,
x: &CudaSlice<f64>,
y: &mut CudaSlice<f64>,
) -> Result<(), ArrowSchurGpuFailure> {
let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let (x_ptr, _x_rec) = x.device_ptr(stream);
let (y_ptr, _y_rec) = y.device_ptr_mut(stream);
// SAFETY: x and y are live device allocations on this stream with at
// least n contiguous f64 entries and unit stride; cuBLAS only reads alpha.
let status = unsafe {
cudarc::cublas::sys::cublasDaxpy_v2(
*blas.handle(),
n_i,
&alpha,
x_ptr as *const f64,
1,
y_ptr as *mut f64,
1,
)
};
if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
Ok(())
} else {
Err(ArrowSchurGpuFailure::Unavailable)
}
}
fn device_dot(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
n: usize,
x: &CudaSlice<f64>,
y: &CudaSlice<f64>,
) -> Result<f64, ArrowSchurGpuFailure> {
let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let (x_ptr, _x_rec) = x.device_ptr(stream);
let (y_ptr, _y_rec) = y.device_ptr(stream);
let mut result = 0.0_f64;
// SAFETY: x and y are live device allocations on this stream with at
// least n contiguous f64 entries and unit stride; result is a valid host
// out-pointer for the cuBLAS scalar.
let status = unsafe {
cudarc::cublas::sys::cublasDdot_v2(
*blas.handle(),
n_i,
x_ptr as *const f64,
1,
y_ptr as *const f64,
1,
&mut result,
)
};
if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
Ok(result)
} else {
Err(ArrowSchurGpuFailure::Unavailable)
}
}
fn device_nrm2(
blas: &CudaBlas,
stream: &Arc<CudaStream>,
n: usize,
x: &CudaSlice<f64>,
) -> Result<f64, ArrowSchurGpuFailure> {
let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
let (x_ptr, _x_rec) = x.device_ptr(stream);
let mut result = 0.0_f64;
// SAFETY: x is a live device allocation on this stream with at least n
// contiguous f64 entries and unit stride; result is a valid host
// out-pointer for the cuBLAS scalar.
let status = unsafe {
cudarc::cublas::sys::cublasDnrm2_v2(
*blas.handle(),
n_i,
x_ptr as *const f64,
1,
&mut result,
)
};
if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
Ok(result)
} else {
Err(ArrowSchurGpuFailure::Unavailable)
}
}
#[cfg(test)]
mod tests {
//! #1551 device-side framed-matvec triage. Lives inside `mod cuda` so it
//! can call the private kernel launchers directly (no test-only public
//! seam, which the ban-scanner forbids). A bare `#[cfg(test)] mod tests`
//! is the one form the scanner permits.
use super::*;
use crate::solver::arrow_schur::{
ArrowSchurSystem, DeviceSaeFrameData, DeviceSaePcgData, DeviceSaeSmoothBlock,
FactoredFrameGBlock,
};
use ndarray::Array2;
/// Run the framed reduced-Schur matvec `out = S·x` ONCE on the device
/// (no PCG, no offload gate) and return `out`.
fn device_matvec_once(
sys: &ArrowSchurSystem,
data: &DeviceSaePcgData,
ridge_t: f64,
ridge_beta: f64,
x_host: &[f64],
) -> Result<Vec<f64>, ArrowSchurGpuFailure> {
let k = x_host.len();
let frame = data
.frame
.as_ref()
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let runtime = crate::gpu::device_runtime::GpuRuntime::global()
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let ctx =
crate::gpu::device_runtime::cuda_context_for(runtime.selected_device().ordinal)
.ok_or(ArrowSchurGpuFailure::Unavailable)?;
let stream = ctx
.new_stream()
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let vector_module = pcg_vector_module(&ctx)?;
let mut buffers = flatten_device_sae_frame_data(sys, data, frame, ridge_t, &stream)?;
let x_dev = stream
.clone_htod(x_host)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
let mut out_dev = stream
.alloc_zeros::<f64>(k)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
launch_sae_frame_matvec(
&stream,
vector_module,
&mut buffers,
&x_dev,
&mut out_dev,
ridge_beta,
)?;
stream
.clone_dtoh(&out_dev)
.map_err(|_| ArrowSchurGpuFailure::Unavailable)
}
/// #1551 stage-isolating matvec triage on a TINY hand-verifiable fixture:
/// diff the device framed matvec `S·e_col` against the CPU oracle
/// `sae_framed_schur_matvec_cpu` for every identity column, reporting the
/// worst-divergent border index so the structural 91% localizes to one
/// kernel stage. Skips cleanly off-device.
#[test]
fn framed_sae_device_matvec_stage_diff_tiny_1551() {
if crate::gpu::device_runtime::GpuRuntime::global().is_none() {
return;
}
let p = 3usize;
let ranks = vec![2usize, 3usize];
let basis_sizes = vec![2usize, 2usize];
let mut border_offsets = Vec::new();
let mut acc = 0usize;
for k in 0..2 {
border_offsets.push(acc);
acc += basis_sizes[k] * ranks[k];
}
let border_dim = acc; // 2·2 + 2·3 = 10
let frame_of = |k: usize| -> Array2<f64> {
Array2::from_shape_fn((p, ranks[k]), |(i, j)| {
0.1 + 0.2 * ((i + 1) as f64) * ((j + 1 + 2 * k) as f64)
})
};
let frames: Vec<Array2<f64>> = (0..2).map(frame_of).collect();
let w_of = |i: usize, j: usize| -> Array2<f64> {
let (ui, uj) = (&frames[i], &frames[j]);
Array2::from_shape_fn((ranks[i], ranks[j]), |(a, b)| {
(0..p).map(|c| ui[[c, a]] * uj[[c, b]]).sum()
})
};
let mut frame_blocks = Vec::new();
for &(i, j) in &[(0usize, 0usize), (1usize, 1usize), (0, 1), (1, 0)] {
let (mi, mj) = (basis_sizes[i], basis_sizes[j]);
let mut g =
Array2::<f64>::from_shape_fn((mi, mj), |(r, c)| 0.1 * (r + 2 * c + 1) as f64);
if i == j {
for r in 0..mi.min(mj) {
g[[r, r]] += mi as f64 + 2.0;
}
}
frame_blocks.push(FactoredFrameGBlock {
atom_i: i,
atom_j: j,
g,
w: w_of(i, j),
});
}
let mut smooth_blocks = Vec::new();
for k in 0..2 {
let m = basis_sizes[k];
let mut s =
Array2::<f64>::from_shape_fn((m, m), |(r, c)| 0.05 * (r + c + 1) as f64);
for r in 0..m {
s[[r, r]] += 1.0;
}
smooth_blocks.push(DeviceSaeSmoothBlock {
global_offset: border_offsets[k],
factor_a: s,
});
}
let smooth_ranks = ranks.clone();
let n = 2usize;
let q = 2usize;
let mut sys = ArrowSchurSystem::new(n, q, border_dim);
let mut row_htbeta = Vec::new();
for i in 0..n {
let mut htt =
Array2::<f64>::from_shape_fn((q, q), |(r, c)| 0.3 * (r + c + 1) as f64);
for r in 0..q {
htt[[r, r]] += q as f64 + 2.0;
}
sys.rows[i].htt = htt;
let mut slab = vec![0.0_f64; q * border_dim];
for c in 0..q {
for col in 0..border_dim {
let v = 0.01 * ((c + 1) * (col + 1) + i) as f64;
slab[c * border_dim + col] = v;
sys.rows[i].htbeta[[c, col]] = v;
}
}
row_htbeta.push(slab);
}
let data = DeviceSaePcgData {
p,
beta_dim: border_dim,
a_phi: std::sync::Arc::from(Vec::new().into_boxed_slice()),
local_jac: std::sync::Arc::from(Vec::new().into_boxed_slice()),
smooth_blocks,
sparse_g_blocks: Vec::new(),
frame: Some(DeviceSaeFrameData {
ranks,
basis_sizes,
border_offsets,
frame_blocks,
smooth_ranks,
row_htbeta,
}),
};
let ridge_t = 1e-7;
let ridge_beta = 1e-6;
let mut first_bad: Option<usize> = None;
let mut worst = 0.0_f64;
let mut worst_at = 0usize;
let mut worst_dev = 0.0_f64;
let mut worst_cpu = 0.0_f64;
for col in 0..border_dim {
let mut x = vec![0.0_f64; border_dim];
x[col] = 1.0;
let dev = match device_matvec_once(&sys, &data, ridge_t, ridge_beta, &x) {
Ok(v) => v,
Err(_) => return,
};
let mut cpu = vec![0.0_f64; border_dim];
super::super::sae_framed_schur_matvec_cpu(
&sys, &data, ridge_t, ridge_beta, &x, &mut cpu,
)
.expect("cpu matvec");
for r in 0..border_dim {
let d = (dev[r] - cpu[r]).abs();
if d > 1e-9 && first_bad.is_none() {
first_bad = Some(r * border_dim + col);
}
if d > worst {
worst = d;
worst_at = r * border_dim + col;
worst_dev = dev[r];
worst_cpu = cpu[r];
}
}
}
assert!(
worst <= 1e-9,
"[#1551 stage-diff] device framed matvec != CPU oracle: worst abs={worst:e} at \
(row*K+col)={worst_at} (dev={worst_dev:e} cpu={worst_cpu:e}), \
first_bad_idx={first_bad:?}; border layout: atom0 [0..4) rank2, atom1 [4..10) \
rank3 — which atom-range the bad row/col falls in pins the stage (smooth=diag, \
G⊗W=cross, reduced-Schur=dense per-row)",
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::solver::arrow_schur::ArrowSchurSystem;
use ndarray::{Array2, ArrayView1};
fn build_fixture(n: usize, d: usize, k: usize, seed: u64) -> ArrowSchurSystem {
let mut sys = ArrowSchurSystem::new(n, d, k);
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15);
let mut sample = || -> f64 {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((state >> 33) as f64) / ((1u64 << 31) as f64) - 1.0
};
for row in &mut sys.rows {
let mut a = Array2::<f64>::zeros((d, d));
for r in 0..d {
for c in 0..d {
a[[r, c]] = sample();
}
}
let mut htt = a.t().dot(&a);
for r in 0..d {
htt[[r, r]] += d as f64 + 1.0;
}
row.htt = htt;
for r in 0..d {
for c in 0..k {
row.htbeta[[r, c]] = 0.1 * sample();
}
row.gt[r] = sample();
}
}
let mut hbb_a = Array2::<f64>::zeros((k, k));
for r in 0..k {
for c in 0..k {
hbb_a[[r, c]] = sample();
}
}
let mut hbb = hbb_a.t().dot(&hbb_a);
for r in 0..k {
hbb[[r, r]] += k as f64 + 1.0;
}
sys.hbb = hbb;
for r in 0..k {
sys.gb[r] = sample();
}
sys
}
fn device_pcg_fixture(k: usize) -> (Array2<f64>, Array1<f64>) {
let mut s = Array2::<f64>::zeros((k, k));
for row in 0..k {
s[[row, row]] = 2.5 + 0.001 * ((row % 17) as f64);
if row + 1 < k {
s[[row, row + 1]] = -0.05;
s[[row + 1, row]] = -0.05;
}
if row + 7 < k {
s[[row, row + 7]] = 0.01;
s[[row + 7, row]] = 0.01;
}
}
let rhs = Array1::from_shape_fn(k, |idx| ((idx as f64 + 1.0) * 0.013).sin());
(s, rhs)
}
fn dense_pcg_cpu_reference(
s: &Array2<f64>,
rhs: &Array1<f64>,
max_iterations: usize,
relative_tolerance: f64,
) -> Array1<f64> {
let k = rhs.len();
let rhs_norm = rhs.iter().map(|v| v * v).sum::<f64>().sqrt();
if rhs_norm == 0.0 {
return Array1::<f64>::zeros(k);
}
let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
let inv_diag: Vec<f64> = (0..k).map(|idx| 1.0 / s[[idx, idx]]).collect();
let mut x = Array1::<f64>::zeros(k);
let mut r = rhs.clone();
let mut z = Array1::from_shape_fn(k, |idx| inv_diag[idx] * r[idx]);
let mut p = z.clone();
let mut sp = Array1::<f64>::zeros(k);
let mut rz = r.iter().zip(z.iter()).map(|(a, b)| a * b).sum::<f64>();
for _ in 0..max_iterations.max(1) {
for row in 0..k {
let mut acc = 0.0;
for col in 0..k {
acc += s[[row, col]] * p[col];
}
sp[row] = acc;
}
let p_sp = p.iter().zip(sp.iter()).map(|(a, b)| a * b).sum::<f64>();
let alpha = rz / p_sp;
for idx in 0..k {
x[idx] += alpha * p[idx];
r[idx] -= alpha * sp[idx];
}
let r_norm = r.iter().map(|v| v * v).sum::<f64>().sqrt();
if r_norm <= tol {
break;
}
for idx in 0..k {
z[idx] = inv_diag[idx] * r[idx];
}
let rz_next = r.iter().zip(z.iter()).map(|(a, b)| a * b).sum::<f64>();
let beta = rz_next / rz;
for idx in 0..k {
p[idx] = z[idx] + beta * p[idx];
}
rz = rz_next;
}
x
}
#[test]
fn device_resident_pcg_matches_cpu_reference_when_cuda_admits() {
let (s, rhs) = device_pcg_fixture(512);
let max_iterations = 200usize;
let relative_tolerance = 1.0e-12;
let cpu = dense_pcg_cpu_reference(&s, &rhs, max_iterations, relative_tolerance);
let (device, diag) = match solve_reduced_beta_pcg_with_diagnostics(
&s,
&rhs,
max_iterations,
relative_tolerance,
) {
Ok(result) => result,
// #1017 — fail loud, never skip-pass: this fixture clears the device
// offload floor, so a CUDA device that is PRESENT yet declines/returns
// Err means the device PCG kernel does not run on GPU (a real fault that
// must not masquerade as a pass via this skip). Legit skip ONLY when no
// usable CUDA device exists (CPU CI). The exact `ArrowSchurGpuFailure`
// variant is folded into the assert message as the diagnostic.
Err(failure) => {
assert!(
crate::gpu::device_runtime::GpuRuntime::global().is_none(),
"#1017: CUDA device present but the device reduced-beta PCG \
declined/faulted instead of returning a result (tag: {failure:?}) — \
the kernel does not run correctly on GPU"
);
return;
}
};
let max_err = cpu
.iter()
.zip(device.iter())
.map(|(a, b)| (a - b).abs())
.fold(0.0_f64, f64::max);
assert!(
max_err <= 1.0e-10,
"device resident PCG parity failed: max_err={max_err:e}, diag={diag:?}"
);
assert!(diag.matvec_calls > 0);
assert_eq!(diag.matvec_calls, diag.iterations);
}
#[test]
fn dense_reference_matches_independent_solve() {
let sys = build_fixture(4, 5, 3, 7);
let solution = solve_arrow_newton_step_dense_reference(&sys, 0.0, 0.0).unwrap();
// Re-solve by an independent matrix build and a textbook
// Gaussian-elimination Cholesky to guard against typos in the
// reference implementation itself.
let n = sys.rows.len();
let d = sys.d;
let k = sys.k;
let total = n * d + k;
let mut h = Array2::<f64>::zeros((total, total));
let mut g = ndarray::Array1::<f64>::zeros(total);
for (i, row) in sys.rows.iter().enumerate() {
let base = i * d;
for c in 0..d {
for r in 0..d {
h[[base + r, base + c]] = row.htt[[r, c]];
}
}
for c in 0..k {
for r in 0..d {
h[[base + r, n * d + c]] = row.htbeta[[r, c]];
h[[n * d + c, base + r]] = row.htbeta[[r, c]];
}
}
for r in 0..d {
g[base + r] = row.gt[r];
}
}
for c in 0..k {
for r in 0..k {
h[[n * d + r, n * d + c]] += sys.hbb[[r, c]];
}
g[n * d + c] = sys.gb[c];
}
let l = cholesky_factor_in_place(h.view(), CholeskyGuard::NonnegativePivot).unwrap();
let rhs = g.mapv(|v| -v);
let expected = cholesky_solve_vector(l.view(), rhs.view());
for i in 0..n * d {
assert!(
(solution.delta_t[i] - expected[i]).abs() < 1e-10 * (1.0 + expected[i].abs()),
"delta_t[{i}] mismatch: got {} expected {}",
solution.delta_t[i],
expected[i]
);
}
for a in 0..k {
assert!(
(solution.delta_beta[a] - expected[n * d + a]).abs()
< 1e-10 * (1.0 + expected[n * d + a].abs()),
"delta_beta[{a}] mismatch"
);
}
}
/// #1017: the row-procedural reduced-Schur matvec (the matrix-free SAE
/// host backend) auto-fans its per-row point-elimination sum across rayon
/// over fixed row chunks when at the top level (`n ≥
/// SCHUR_MATVEC_PARALLEL_ROW_MIN`), and stays serial when already inside a
/// rayon worker. The chunk-ordered fold makes the parallel result
/// **deterministic** (two parallel calls are bit-identical — scheduling
/// cannot change the numbers) and it agrees with the serial accumulation up
/// to ULP-scale chunk reassociation (the #1017 verification gate). That
/// reassociation is a genuine f64 departure from serial, so the criterion
/// ranking across topology candidates is stable only up to the reassociation
/// margin: a near-tie winner inside that margin can flip. This is NOT an
/// exact no-move guarantee (#1211); for that, the ranking path must use the
/// fixed-order serial accumulation.
#[test]
fn row_procedural_matvec_parallel_deterministic_and_matches_serial() {
use crate::solver::arrow_schur::SCHUR_MATVEC_PARALLEL_ROW_MIN;
let n = SCHUR_MATVEC_PARALLEL_ROW_MIN + 96; // trips the parallel path
let d = 3usize;
let k = 24usize;
let mut sys = build_fixture(n, d, k, 0xA17C_0FFE);
// Install a matrix-free forward/transpose pair that reads the dense
// `htbeta` slabs the fixture already populated, so the procedural
// backend has a well-defined operator to apply (and exercises exactly
// the sparse gather/scatter the SAE Kronecker path drives).
let slabs: Vec<Array2<f64>> = sys.rows.iter().map(|row| row.htbeta.clone()).collect();
let forward_slabs = slabs.clone();
let transpose_slabs = slabs;
sys.set_row_htbeta_operator(
move |row: usize, x: ArrayView1<'_, f64>, out: &mut Array1<f64>| {
let h = &forward_slabs[row];
for r in 0..h.nrows() {
let mut acc = 0.0_f64;
for c in 0..h.ncols() {
acc += h[[r, c]] * x[c];
}
out[r] = acc;
}
},
move |row: usize, v: ArrayView1<'_, f64>, out: &mut Array1<f64>| {
let h = &transpose_slabs[row];
for r in 0..h.nrows() {
for c in 0..h.ncols() {
out[c] += h[[r, c]] * v[r];
}
}
},
);
let matvec = gpu_schur_matvec_backend(&sys, 0.0, 0.0)
.expect("row-procedural matvec backend builds for matrix-free system");
let x = Array1::from_shape_fn(k, |i| ((i as f64 + 1.0) * 0.37).sin());
// Top-level call: auto-selects the parallel chunk-fold. Run twice and
// assert bit-identity — the chunk-ordered reduction must not depend on
// thread scheduling.
let mut out_parallel_a = Array1::<f64>::zeros(k);
matvec(&x, &mut out_parallel_a);
let mut out_parallel_b = Array1::<f64>::zeros(k);
matvec(&x, &mut out_parallel_b);
for a in 0..k {
assert_eq!(
out_parallel_a[a].to_bits(),
out_parallel_b[a].to_bits(),
"row-procedural matvec parallel reduction is non-deterministic at index {a}"
);
}
// Inside a rayon worker: auto-selects the serial path (nested-rayon
// guard). `install` runs the closure on a pool thread, so
// `current_thread_index()` is `Some`. The serial running sum and the
// chunk-ordered parallel fold differ only by f64 reassociation.
let mut out_serial = Array1::<f64>::zeros(k);
rayon::ThreadPoolBuilder::new()
.num_threads(2)
.build()
.expect("build rayon pool")
.install(|| matvec(&x, &mut out_serial));
let max_abs = out_serial.iter().fold(0.0_f64, |m, v| m.max(v.abs()));
for a in 0..k {
let diff = (out_parallel_a[a] - out_serial[a]).abs();
assert!(
diff <= 1e-12 * (1.0 + max_abs),
"row-procedural matvec parallel vs serial diverged beyond reassociation \
at index {a}: {} vs {} (diff={diff:e})",
out_parallel_a[a],
out_serial[a]
);
}
}
/// #1017/#1026 — the frames-engaged CPU reduced-Schur matvec
/// [`sae_framed_schur_matvec_cpu`] (the bit-parity oracle the GPU kernel
/// mirrors) must equal the dense reduced Schur `S = (P_ββ + ρ_β I) −
/// Σ_i H_βt^(i)(H_tt^(i)+ρ_t I)⁻¹ H_tβ^(i)` formed by the canonical dense
/// reference, on a small framed system with mixed per-atom ranks
/// (`r_k < p` framed + `r_k = p` un-framed). Size-independent gate.
#[test]
fn framed_sae_schur_matvec_matches_dense_reference() {
use crate::solver::arrow_schur::{
BetaPenaltyOp, DeviceSaeFrameData, DeviceSaePcgData, DeviceSaeSmoothBlock,
FactoredFrameGBlock, FactoredFrameKroneckerOp, IdentityRightKroneckerPenaltyOp,
};
let p = 4usize;
// Three atoms: ranks 2 (framed), 4 (un-framed), 3 (framed).
let ranks = vec![2usize, 4usize, 3usize];
let basis_sizes = vec![2usize, 1usize, 2usize];
let n_atoms = ranks.len();
let mut border_offsets = Vec::with_capacity(n_atoms);
let mut acc = 0usize;
for k in 0..n_atoms {
border_offsets.push(acc);
acc += basis_sizes[k] * ranks[k];
}
let border_dim = acc; // 2*2 + 1*4 + 2*3 = 14
let mut state = 0x1234_5678_9abc_def0u64;
let mut sample = || -> f64 {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((state >> 33) as f64) / ((1u64 << 31) as f64) - 1.0
};
// Per-atom orthonormal-ish frames U_k (p × r_k) for the W = U_iᵀU_j
// factors; un-framed atom (r=p) uses U = I_p.
let mut frames: Vec<Array2<f64>> = Vec::with_capacity(n_atoms);
for k in 0..n_atoms {
let r = ranks[k];
let mut u = Array2::<f64>::zeros((p, r));
for i in 0..p {
for j in 0..r {
u[[i, j]] = if r == p && i == j {
1.0
} else if r == p {
0.0
} else {
sample()
};
}
}
frames.push(u);
}
let w_of = |i: usize, j: usize| -> Array2<f64> {
let (ui, uj) = (&frames[i], &frames[j]);
let (ri, rj) = (ranks[i], ranks[j]);
let mut w = Array2::<f64>::zeros((ri, rj));
for a in 0..ri {
for b in 0..rj {
let mut s = 0.0;
for c in 0..p {
s += ui[[c, a]] * uj[[c, b]];
}
w[[a, b]] = s;
}
}
w
};
// Co-occurring data-fit blocks: all diagonal pairs + one cross (0,2).
let mut frame_blocks: Vec<FactoredFrameGBlock> = Vec::new();
let mut pairs = vec![(0usize, 0usize), (1, 1), (2, 2), (0, 2), (2, 0)];
pairs.sort();
for &(i, j) in &pairs {
let (mi, mj) = (basis_sizes[i], basis_sizes[j]);
let mut g = Array2::<f64>::zeros((mi, mj));
for r in 0..mi {
for c in 0..mj {
g[[r, c]] = 0.3 * sample();
}
}
// Make diagonal blocks SPD-leaning so S stays PD.
if i == j {
for r in 0..mi.min(mj) {
g[[r, r]] += mi as f64 + 2.0;
}
}
frame_blocks.push(FactoredFrameGBlock {
atom_i: i,
atom_j: j,
g,
w: w_of(i, j),
});
}
// Smooth blocks λ S_k (M_k × M_k), SPD.
let mut smooth_blocks: Vec<DeviceSaeSmoothBlock> = Vec::with_capacity(n_atoms);
let mut smooth_ranks: Vec<usize> = Vec::with_capacity(n_atoms);
for k in 0..n_atoms {
let m = basis_sizes[k];
let mut a = Array2::<f64>::zeros((m, m));
for r in 0..m {
for c in 0..m {
a[[r, c]] = 0.2 * sample();
}
}
let mut s = a.t().dot(&a);
for r in 0..m {
s[[r, r]] += 1.0;
}
smooth_blocks.push(DeviceSaeSmoothBlock {
global_offset: border_offsets[k],
factor_a: s,
});
smooth_ranks.push(ranks[k]);
}
// Build the system: n rows, dense htbeta slabs (q_i × border_dim).
let n = 6usize;
let q = 3usize;
let mut sys = ArrowSchurSystem::new(n, q, border_dim);
let mut row_htbeta: Vec<Vec<f64>> = Vec::with_capacity(n);
for i in 0..n {
// SPD htt.
let mut a = Array2::<f64>::zeros((q, q));
for r in 0..q {
for c in 0..q {
a[[r, c]] = sample();
}
}
let mut htt = a.t().dot(&a);
for r in 0..q {
htt[[r, r]] += q as f64 + 1.0;
}
sys.rows[i].htt = htt;
let mut slab = vec![0.0_f64; q * border_dim];
for c in 0..q {
for col in 0..border_dim {
let v = 0.15 * sample();
slab[c * border_dim + col] = v;
sys.rows[i].htbeta[[c, col]] = v;
}
}
row_htbeta.push(slab);
}
// Dense H_ββ from the SAME penalty ops (so the dense reference's S
// matches the device penalty side exactly).
let data_op =
FactoredFrameKroneckerOp::new(ranks.clone(), basis_sizes.clone(), frame_blocks.clone())
.expect("frame op");
let mut hbb = data_op.to_dense();
for k in 0..n_atoms {
let op = IdentityRightKroneckerPenaltyOp {
factor_a: smooth_blocks[k].factor_a.clone(),
p: ranks[k],
global_offset: border_offsets[k],
k: border_dim,
};
let d = op.to_dense();
for r in 0..border_dim {
for c in 0..border_dim {
hbb[[r, c]] += d[[r, c]];
}
}
}
sys.hbb = hbb;
let data = DeviceSaePcgData {
p,
beta_dim: border_dim,
a_phi: std::sync::Arc::from(Vec::new().into_boxed_slice()),
local_jac: std::sync::Arc::from(Vec::new().into_boxed_slice()),
smooth_blocks,
sparse_g_blocks: Vec::new(),
frame: Some(DeviceSaeFrameData {
ranks: ranks.clone(),
basis_sizes: basis_sizes.clone(),
border_offsets: border_offsets.clone(),
frame_blocks,
smooth_ranks,
row_htbeta,
}),
};
let ridge_t = 1e-7;
let ridge_beta = 1e-6;
// Dense reference reduced Schur S (border_dim × border_dim), formed
// exactly as solve_arrow_newton_step_dense_reference assembles the
// bordered Hessian and eliminates the t-block.
let mut s_dense = Array2::<f64>::zeros((border_dim, border_dim));
for r in 0..border_dim {
for c in 0..border_dim {
s_dense[[r, c]] = sys.hbb[[r, c]];
}
s_dense[[r, r]] += ridge_beta;
}
for row in &sys.rows {
let mut htt = row.htt.clone();
for d in 0..q {
htt[[d, d]] += ridge_t;
}
let factor = cholesky_factor_in_place(htt.view(), CholeskyGuard::NonnegativePivot)
.expect("htt PD");
// Y = (htt)⁻¹ htbeta (q × border_dim); S -= htbetaᵀ Y.
let mut y = Array2::<f64>::zeros((q, border_dim));
for col in 0..border_dim {
let mut e = Array1::<f64>::zeros(q);
for r in 0..q {
e[r] = row.htbeta[[r, col]];
}
let solved = cholesky_solve_vector(factor.view(), e.view());
for r in 0..q {
y[[r, col]] = solved[r];
}
}
for r in 0..border_dim {
for c in 0..border_dim {
let mut acc = 0.0;
for d in 0..q {
acc += row.htbeta[[d, r]] * y[[d, c]];
}
s_dense[[r, c]] -= acc;
}
}
}
// Probe vectors: compare S·x from the device-data CPU oracle vs dense S·x.
let mut max_rel = 0.0_f64;
for trial in 0..4 {
let x: Vec<f64> = (0..border_dim)
.map(|a| 0.3 * ((a as f64 + trial as f64) * 0.21).cos() - 0.1)
.collect();
let mut got = vec![0.0_f64; border_dim];
sae_framed_schur_matvec_cpu(&sys, &data, ridge_t, ridge_beta, &x, &mut got)
.expect("framed matvec");
let mut want = vec![0.0_f64; border_dim];
for r in 0..border_dim {
let mut acc = 0.0;
for c in 0..border_dim {
acc += s_dense[[r, c]] * x[c];
}
want[r] = acc;
}
let scale = want.iter().fold(0.0_f64, |m, v| m.max(v.abs())).max(1.0);
for a in 0..border_dim {
let rel = (got[a] - want[a]).abs() / scale;
max_rel = max_rel.max(rel);
}
}
assert!(
max_rel <= 1e-10,
"framed SAE Schur matvec vs dense reference diverged: max_rel={max_rel:e}"
);
}
/// #1017/#1026 GPU arm: when a CUDA device admits the framed SAE PCG, its
/// solved `δβ` must match the CPU dense reduced-system solve of the SAME
/// framed system (size-independent — a small device validates the kernel).
/// Skips cleanly (returns) when no device is available or the policy
/// declines (`solve_sae_matrix_free_pcg` → `Unavailable`).
#[test]
fn framed_sae_device_pcg_matches_cpu_when_cuda_admits() {
use crate::solver::arrow_schur::{
BetaPenaltyOp, DeviceSaeFrameData, DeviceSaePcgData, DeviceSaeSmoothBlock,
FactoredFrameGBlock, FactoredFrameKroneckerOp, IdentityRightKroneckerPenaltyOp,
};
// Large enough to clear the device-offload policy floor (k ≥ 32 and
// n·k·d·iters ≥ MATVEC_OFFLOAD_FLOPS_MIN) so the GPU kernel actually
// runs on a device rather than the policy declining.
let p = 6usize;
let n_atoms = 8usize;
let ranks: Vec<usize> = (0..n_atoms)
.map(|k| if k % 2 == 0 { 3usize } else { p })
.collect();
let basis_sizes: Vec<usize> = (0..n_atoms).map(|_| 3usize).collect();
let mut border_offsets = Vec::with_capacity(n_atoms);
let mut acc = 0usize;
for k in 0..n_atoms {
border_offsets.push(acc);
acc += basis_sizes[k] * ranks[k];
}
let border_dim = acc; // Σ M_k·r_k = 4·(3·3) + 4·(3·6) = 36 + 72 = 108
let mut state = 0xfeed_face_dead_beefu64;
let mut sample = || -> f64 {
state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((state >> 33) as f64) / ((1u64 << 31) as f64) - 1.0
};
let mut frames: Vec<Array2<f64>> = Vec::new();
for k in 0..n_atoms {
let r = ranks[k];
let mut u = Array2::<f64>::zeros((p, r));
for i in 0..p {
for j in 0..r {
u[[i, j]] = if r == p && i == j {
1.0
} else if r == p {
0.0
} else {
sample()
};
}
}
frames.push(u);
}
let w_of = |i: usize, j: usize| {
let (ui, uj) = (&frames[i], &frames[j]);
let (ri, rj) = (ranks[i], ranks[j]);
let mut w = Array2::<f64>::zeros((ri, rj));
for a in 0..ri {
for b in 0..rj {
let mut s = 0.0;
for c in 0..p {
s += ui[[c, a]] * uj[[c, b]];
}
w[[a, b]] = s;
}
}
w
};
let mut pairs: Vec<(usize, usize)> = (0..n_atoms).map(|k| (k, k)).collect();
// A few off-diagonal cross blocks (symmetric pairs).
for &(i, j) in &[(0usize, 1usize), (2, 4), (3, 6)] {
pairs.push((i, j));
pairs.push((j, i));
}
let mut frame_blocks = Vec::new();
for &(i, j) in &pairs {
let (mi, mj) = (basis_sizes[i], basis_sizes[j]);
let mut g = Array2::<f64>::zeros((mi, mj));
for r in 0..mi {
for c in 0..mj {
g[[r, c]] = 0.25 * sample();
}
}
if i == j {
for r in 0..mi.min(mj) {
g[[r, r]] += mi as f64 + 2.0;
}
}
frame_blocks.push(FactoredFrameGBlock {
atom_i: i,
atom_j: j,
g,
w: w_of(i, j),
});
}
let mut smooth_blocks = Vec::new();
let mut smooth_ranks = Vec::new();
for k in 0..n_atoms {
let m = basis_sizes[k];
let mut a = Array2::<f64>::zeros((m, m));
for r in 0..m {
for c in 0..m {
a[[r, c]] = 0.2 * sample();
}
}
let mut s = a.t().dot(&a);
for r in 0..m {
s[[r, r]] += 1.0;
}
smooth_blocks.push(DeviceSaeSmoothBlock {
global_offset: border_offsets[k],
factor_a: s,
});
smooth_ranks.push(ranks[k]);
}
let n = 400usize;
let q = 4usize;
let mut sys = ArrowSchurSystem::new(n, q, border_dim);
let mut row_htbeta = Vec::new();
for i in 0..n {
let mut a = Array2::<f64>::zeros((q, q));
for r in 0..q {
for c in 0..q {
a[[r, c]] = sample();
}
}
let mut htt = a.t().dot(&a);
for r in 0..q {
htt[[r, r]] += q as f64 + 1.0;
}
sys.rows[i].htt = htt;
let mut slab = vec![0.0_f64; q * border_dim];
for c in 0..q {
for col in 0..border_dim {
// Small entries: with 400 rows the reduced-Schur subtraction
// Σ_i H_βtᵀ H_tt⁻¹ H_tβ must not overwhelm the PD penalty.
let v = 0.02 * sample();
slab[c * border_dim + col] = v;
sys.rows[i].htbeta[[c, col]] = v;
}
}
row_htbeta.push(slab);
}
let data_op =
FactoredFrameKroneckerOp::new(ranks.clone(), basis_sizes.clone(), frame_blocks.clone())
.expect("frame op");
let mut hbb = data_op.to_dense();
for k in 0..n_atoms {
let op = IdentityRightKroneckerPenaltyOp {
factor_a: smooth_blocks[k].factor_a.clone(),
p: ranks[k],
global_offset: border_offsets[k],
k: border_dim,
};
let d = op.to_dense();
for r in 0..border_dim {
for c in 0..border_dim {
hbb[[r, c]] += d[[r, c]];
}
}
}
sys.hbb = hbb;
let data = DeviceSaePcgData {
p,
beta_dim: border_dim,
a_phi: std::sync::Arc::from(Vec::new().into_boxed_slice()),
local_jac: std::sync::Arc::from(Vec::new().into_boxed_slice()),
smooth_blocks,
sparse_g_blocks: Vec::new(),
frame: Some(DeviceSaeFrameData {
ranks: ranks.clone(),
basis_sizes: basis_sizes.clone(),
border_offsets: border_offsets.clone(),
frame_blocks,
smooth_ranks,
row_htbeta,
}),
};
let ridge_t = 1e-7;
let ridge_beta = 1e-6;
let rhs: Array1<f64> =
Array1::from_shape_fn(border_dim, |a| ((a as f64 + 1.0) * 0.17).sin());
let (device, diag) =
match solve_sae_matrix_free_pcg(&sys, &data, ridge_t, ridge_beta, &rhs, 400, 1e-12) {
Ok(result) => result,
// #1017 — fail loud, never skip-pass: this fixture clears the device
// offload floor, so a CUDA device that is PRESENT yet declines means the
// framed device PCG kernel does not run on GPU (the fault must not pass
// silently). Legit skip ONLY when no usable CUDA device exists (CPU CI).
// The exact `ArrowSchurGpuFailure` variant is folded into the assert.
Err(failure) => {
assert!(
crate::gpu::device_runtime::GpuRuntime::global().is_none(),
"#1017: CUDA device present but the framed device SAE PCG \
declined/faulted instead of returning a result (tag: {failure:?}) — \
the kernel does not run correctly on GPU"
);
return;
}
};
// CPU dense reduced-system solve of the SAME framed system: form S via
// the CPU oracle matvec on the identity, then solve S·δβ = rhs.
let mut s_dense = Array2::<f64>::zeros((border_dim, border_dim));
for col in 0..border_dim {
let mut e = vec![0.0_f64; border_dim];
e[col] = 1.0;
let mut sc = vec![0.0_f64; border_dim];
sae_framed_schur_matvec_cpu(&sys, &data, ridge_t, ridge_beta, &e, &mut sc)
.expect("cpu matvec");
for r in 0..border_dim {
s_dense[[r, col]] = sc[r];
}
}
let factor = cholesky_factor_in_place(s_dense.view(), CholeskyGuard::NonnegativePivot)
.expect("S PD");
let cpu = cholesky_solve_vector(factor.view(), rhs.view());
let scale = cpu.iter().fold(0.0_f64, |m, v| m.max(v.abs())).max(1.0);
let mut max_rel = 0.0_f64;
for a in 0..border_dim {
max_rel = max_rel.max((device[a] - cpu[a]).abs() / scale);
}
// #1551 divergence triage (max_rel=0.91 once the device actually engages):
// disambiguate matvec-bug vs PCG-non-convergence vs operator-mismatch.
// Residual of the DEVICE solution against the CPU operator S_cpu: if the
// device solved the SAME operator and converged, ‖S_cpu·device − rhs‖ ≈ 0;
// a large residual means the device matvec is a DIFFERENT operator (kernel
// bug), whereas a small residual with large max_rel would indicate a
// (near-)singular S where both solves are valid. Also surface what the
// device PCG thought it did (stopping reason / iters / final residual).
let mut s_dev_resid = 0.0_f64;
{
let sx = s_dense.dot(&device);
for a in 0..border_dim {
s_dev_resid = s_dev_resid.max((sx[a] - rhs[a]).abs());
}
}
let s_cpu_resid = {
let sc = s_dense.dot(&cpu);
let mut m = 0.0_f64;
for a in 0..border_dim {
m = m.max((sc[a] - rhs[a]).abs());
}
m
};
assert!(
max_rel <= 1e-7,
"[#1551 framed-triage] max_rel={max_rel:e} | device-vs-CPU-operator residual \
‖S_cpu·device−rhs‖={s_dev_resid:e} (CPU's own ={s_cpu_resid:e}) | device PCG \
stop={:?} iters={} final_rel_resid={:e} — large operator-residual ⇒ device matvec \
is a different operator (kernel bug); small ⇒ PCG/precond or singular-S issue",
diag.stopping_reason,
diag.iterations,
diag.final_relative_residual,
);
}
}