rusting_brain 1.0.0

A Rust neural-network library for learning, training, and inference from small models to small size LLM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
//! The device-resident training path: a whole decoder layer without a round trip.
//!
//! [`gpu_transformer`](crate::gpu_transformer) accelerates the matmul-bound
//! pieces of the *host* modules, which means every sublayer uploads its input
//! and downloads its output, because the host operation that follows needs the
//! values. This module is the other half: activations live in device buffers
//! from the embedding gather to the logits, and everything between two GEMMs -
//! RMSNorm, RoPE, the causal softmax, SwiGLU, and the MoE router's top-k and
//! gating - is a kernel from [`crate::cuda_training`]'s module.
//!
//! Host traffic per training step is therefore:
//!
//! * token ids up, logits down, `dL/dlogits` up. The loss stays on the host.
//! * the RMSNorm scales up and their gradients down, once per layer per step.
//!   Those weights stay host-resident so that cached decode keeps working.
//! * one `[rows * top_k]` routing table down per MoE layer, and the token lists
//!   back up. cuBLAS takes its GEMM dimensions on the host, so the number of
//!   tokens routed to each expert has to reach the host before the expert GEMMs
//!   can be shaped. This is one small copy per layer, not one per expert.
//!
//! Batching is what makes this pay. Every buffer is `[batch * seq_len, width]`,
//! the per-head attention GEMMs are strided-batched over the sequences, and an
//! expert sees the tokens routed to it from the *whole* batch in one GEMM.

use crate::batch::TokenBatch;
use crate::cuda_training::{cfg, cuda_err};
use crate::ffn::SwiGlu;
use crate::gpu_transformer::{
    DeviceParam, GpuContext, gemm_lhs_transposed, gemm_lhs_transposed_batched, gemm_plain,
    gemm_plain_batched, gemm_rhs_transposed, gemm_rhs_transposed_batched,
};
use crate::matrix::Matrix;
use crate::moe::MoeLayer;
use crate::network::NetworkError;
use crate::param::{Linear, Param};
use crate::rope::Rope;
use crate::transformer::TransformerLm;
use crate::transformer_block::{FeedForward, TransformerBlock};
use cudarc::driver::{
    CudaFunction, CudaModule, CudaSlice, CudaView, CudaViewMut, DevicePtr, DevicePtrMut,
    PushKernelArg,
};
use half::bf16;
use std::sync::Arc;

/// Every fused kernel, resolved once per device.
pub(crate) struct ModelKernels {
    rmsnorm_forward: CudaFunction,
    rmsnorm_backward: CudaFunction,
    rope: CudaFunction,
    causal_softmax: CudaFunction,
    causal_softmax_backward: CudaFunction,
    swiglu_forward: CudaFunction,
    swiglu_backward: CudaFunction,
    softmax_lse: CudaFunction,
    topk_gate: CudaFunction,
    gather: CudaFunction,
    gather_scaled: CudaFunction,
    scatter_scaled: CudaFunction,
    scatter: CudaFunction,
    scatter_negated: CudaFunction,
    row_dot: CudaFunction,
    stats: CudaFunction,
    grad_probabilities: CudaFunction,
    aux_grad: CudaFunction,
    grad_logits: CudaFunction,
    add: CudaFunction,
    cross_entropy: CudaFunction,
    cross_entropy_bf16: CudaFunction,
    to_bf16: CudaFunction,
    from_bf16: CudaFunction,
    accumulate_bf16: CudaFunction,
}

impl ModelKernels {
    pub(crate) fn load(module: &Arc<CudaModule>) -> Result<Self, NetworkError> {
        let get = |name: &str| {
            module
                .load_function(name)
                .map_err(cuda_err("CUDA kernel lookup"))
        };
        Ok(Self {
            rmsnorm_forward: get("rmsnorm_fwd")?,
            rmsnorm_backward: get("rmsnorm_bwd")?,
            rope: get("rope_rotate")?,
            causal_softmax: get("causal_softmax")?,
            causal_softmax_backward: get("causal_softmax_bwd")?,
            swiglu_forward: get("swiglu_fwd")?,
            swiglu_backward: get("swiglu_bwd")?,
            softmax_lse: get("softmax_lse")?,
            topk_gate: get("topk_gate")?,
            gather: get("gather_rows")?,
            gather_scaled: get("gather_scale_rows")?,
            scatter_scaled: get("scatter_add_scaled")?,
            scatter: get("scatter_add_rows")?,
            scatter_negated: get("scatter_rows_neg")?,
            row_dot: get("row_dot_scatter")?,
            stats: get("moe_stats")?,
            grad_probabilities: get("moe_grad_probs")?,
            aux_grad: get("moe_aux_grad")?,
            grad_logits: get("router_grad_logits")?,
            add: get("add_inplace")?,
            cross_entropy: get("ce_loss_grad")?,
            cross_entropy_bf16: get("ce_loss_grad_bf16")?,
            to_bf16: get("to_bf16")?,
            from_bf16: get("from_bf16")?,
            accumulate_bf16: get("accumulate_bf16")?,
        })
    }
}

/// RoPE's `cos` and `sin` tables on the device.
///
/// Every layer is built from the same [`Rope`] configuration, so one upload
/// serves the whole model and is kept for the life of the context.
pub(crate) struct DeviceRope {
    cos: CudaSlice<f32>,
    sin: CudaSlice<f32>,
    head_dim: usize,
    max_seq_len: usize,
}

/// What [`backward`] needs from [`forward`], all of it device-resident.
pub(crate) struct GpuCache {
    rows: usize,
    seq_len: usize,
    sequences: usize,
    ids: CudaSlice<u32>,
    valid_tokens: usize,
    blocks: Vec<BlockCache>,
    final_input: CudaSlice<f32>,
    final_inverse_rms: CudaSlice<f32>,
    final_weight: CudaSlice<f32>,
    final_output: CudaSlice<f32>,
    auxiliary_loss: f32,
}

impl std::fmt::Debug for GpuCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GpuCache")
            .field("rows", &self.rows)
            .field("seq_len", &self.seq_len)
            .finish()
    }
}

impl GpuCache {
    pub(crate) fn auxiliary_loss(&self) -> f32 {
        self.auxiliary_loss
    }
}

struct BlockCache {
    input: CudaSlice<f32>,
    attention_weight: CudaSlice<f32>,
    attention_inverse_rms: CudaSlice<f32>,
    attention_normed: CudaSlice<f32>,
    queries: CudaSlice<f32>,
    keys: CudaSlice<f32>,
    values: CudaSlice<f32>,
    probabilities: CudaSlice<f32>,
    merged: CudaSlice<f32>,
    residual: CudaSlice<f32>,
    feed_forward_weight: CudaSlice<f32>,
    feed_forward_inverse_rms: CudaSlice<f32>,
    feed_forward_normed: CudaSlice<f32>,
    feed_forward: FfnCache,
}

/// The three buffers a SwiGLU backward pass cannot recover from its output.
struct SwiGluCache {
    gate: CudaSlice<f32>,
    up: CudaSlice<f32>,
    hidden: CudaSlice<f32>,
}

enum FfnCache {
    Dense(SwiGluCache),
    Moe(Box<MoeGpuCache>),
}

struct MoeGpuCache {
    probabilities: CudaSlice<f32>,
    log_sum_exp: CudaSlice<f32>,
    expert_of: CudaSlice<i32>,
    /// One entry per routed token slot, grouped by expert: the token it came
    /// from, the flat assignment slot, and the gate it was scaled by.
    token_of: CudaSlice<u32>,
    slot_of: CudaSlice<u32>,
    gates: CudaSlice<f32>,
    /// Where each expert's group starts in those buffers, and how long it is.
    offsets: Vec<usize>,
    counts: Vec<usize>,
    routed: usize,
    input: CudaSlice<f32>,
    expert: SwiGluCache,
    output: CudaSlice<f32>,
    shared: Option<SwiGluCache>,
}

/// A borrowed device, plus the kernel launches, so the model code below reads
/// as a sequence of operations rather than a sequence of `unsafe` blocks.
struct Gpu<'a> {
    context: &'a Arc<GpuContext>,
}

impl Gpu<'_> {
    fn zeros(&self, len: usize) -> Result<CudaSlice<f32>, NetworkError> {
        self.context
            .stream
            .alloc_zeros::<f32>(len.max(1))
            .map_err(cuda_err("device allocation"))
    }

    /// An allocation whose contents are whatever the driver last left there.
    ///
    /// Only for a buffer the very next operation overwrites completely: a GEMM
    /// with `beta = 0`, or a kernel that writes every element. The zeroing
    /// `zeros` does is a full-bandwidth pass over the buffer, which on the
    /// chunked LM head alone cost more than every memcpy in a step combined.
    fn uninit(&self, len: usize) -> Result<CudaSlice<f32>, NetworkError> {
        unsafe { self.context.stream.alloc::<f32>(len.max(1)) }
            .map_err(cuda_err("device allocation"))
    }

    /// [`Gpu::uninit`] for a BF16 buffer.
    fn uninit_bf16(&self, len: usize) -> Result<CudaSlice<bf16>, NetworkError> {
        unsafe { self.context.stream.alloc::<bf16>(len.max(1)) }
            .map_err(cuda_err("device allocation"))
    }

    /// `dst[..n] = bf16(src[..n])`, rounded to nearest even.
    fn cast_to_bf16(
        &self,
        dst: &mut CudaSlice<bf16>,
        src: &CudaView<'_, f32>,
        n: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.to_bf16)
                .arg(dst)
                .arg(src)
                .arg(&(n as i32))
                .launch(cfg(n))
                .map_err(cuda_err("BF16 cast kernel"))?;
        }
        Ok(())
    }

    /// `dst[..n] = f32(src[..n])`, which is exact.
    fn cast_from_bf16(
        &self,
        dst: &mut CudaViewMut<'_, f32>,
        src: &CudaSlice<bf16>,
        n: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.from_bf16)
                .arg(dst)
                .arg(src)
                .arg(&(n as i32))
                .launch(cfg(n))
                .map_err(cuda_err("BF16 widening kernel"))?;
        }
        Ok(())
    }

    /// `acc[..n] += f32(src[..n])`, the FP32 half of a BF16 gradient GEMM.
    fn accumulate_bf16(
        &self,
        acc: &mut CudaSlice<f32>,
        src: &CudaSlice<bf16>,
        n: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.accumulate_bf16)
                .arg(acc)
                .arg(src)
                .arg(&(n as i32))
                .launch(cfg(n))
                .map_err(cuda_err("BF16 accumulate kernel"))?;
        }
        Ok(())
    }

    fn upload(&self, data: &[f32]) -> Result<CudaSlice<f32>, NetworkError> {
        self.context
            .stream
            .clone_htod(data)
            .map_err(cuda_err("host to device copy"))
    }

    fn upload_indices(&self, data: &[u32]) -> Result<CudaSlice<u32>, NetworkError> {
        self.context
            .stream
            .clone_htod(data)
            .map_err(cuda_err("host to device copy"))
    }

    fn upload_flags(&self, data: &[i32]) -> Result<CudaSlice<i32>, NetworkError> {
        self.context
            .stream
            .clone_htod(data)
            .map_err(cuda_err("host to device copy"))
    }

    fn download(&self, source: &CudaSlice<f32>) -> Result<Vec<f32>, NetworkError> {
        self.context
            .stream
            .clone_dtoh(source)
            .map_err(cuda_err("device to host copy"))
    }

    fn upload_signed(&self, data: &[i32]) -> Result<CudaSlice<i32>, NetworkError> {
        self.context
            .stream
            .clone_htod(data)
            .map_err(cuda_err("host to device copy"))
    }

    fn download_signed(&self, source: &CudaSlice<i32>) -> Result<Vec<i32>, NetworkError> {
        self.context
            .stream
            .clone_dtoh(source)
            .map_err(cuda_err("device to host copy"))
    }

    fn duplicate(&self, source: &CudaSlice<f32>) -> Result<CudaSlice<f32>, NetworkError> {
        self.context
            .stream
            .clone_dtod(source)
            .map_err(cuda_err("device to device copy"))
    }

    /// `[rows, width]` back into a host matrix.
    fn matrix(
        &self,
        source: &CudaSlice<f32>,
        rows: usize,
        width: usize,
    ) -> Result<Matrix, NetworkError> {
        let mut matrix = Matrix::new(rows, width);
        self.context
            .stream
            .memcpy_dtoh(source, &mut matrix.data)
            .map_err(cuda_err("device to host copy"))?;
        Ok(matrix)
    }

    /// Adds one slice of a downloaded scale-gradient block into a host
    /// parameter's gradient.
    ///
    /// The RMSNorm scales are the only weights the device path does not own,
    /// so this is the one place a gradient crosses back in the plain
    /// (unnegated) convention. The whole backward pass writes its scale
    /// gradients into a single device buffer and downloads it once, because a
    /// download in the middle of the pass drains the stream: thirteen of them
    /// left the device idle for about 20 ms of every step.
    fn accumulate_host_grad(param: &mut Param, values: &[f32]) {
        for (slot, value) in param.grad.data.iter_mut().zip(values) {
            *slot += value;
        }
    }

    fn rope_tables(&self, rope: &Rope) -> Result<Arc<DeviceRope>, NetworkError> {
        let mut slot = self
            .context
            .rope
            .lock()
            .map_err(|_| NetworkError::Cuda("the rope table lock was poisoned".into()))?;
        if let Some(tables) = slot.as_ref()
            && tables.head_dim == rope.head_dim()
            && tables.max_seq_len == rope.max_seq_len()
        {
            return Ok(tables.clone());
        }
        let tables = Arc::new(DeviceRope {
            cos: self.upload(rope.cos())?,
            sin: self.upload(rope.sin())?,
            head_dim: rope.head_dim(),
            max_seq_len: rope.max_seq_len(),
        });
        *slot = Some(tables.clone());
        Ok(tables)
    }

    /// `out[rows, weight.rows] = x . weight^T`.
    fn linear<X: DevicePtr<f32>>(
        &self,
        weight: &DeviceParam,
        x: &X,
        rows: usize,
    ) -> Result<CudaSlice<f32>, NetworkError> {
        let mut out = self.uninit(rows * weight.rows())?;
        gemm_rhs_transposed(
            &self.context.blas,
            x,
            weight.cols(),
            weight.value(),
            weight.cols(),
            &mut out,
            weight.rows(),
            rows,
            weight.rows(),
            weight.cols(),
            1.0,
            0.0,
        )?;
        Ok(out)
    }

    /// `out = alpha * x . weight^T + beta * out`, for a caller that already has
    /// the destination buffer (a residual, say).
    #[allow(clippy::too_many_arguments)]
    fn linear_into<X: DevicePtr<f32>, O: DevicePtrMut<f32>>(
        &self,
        weight: &DeviceParam,
        x: &X,
        out: &mut O,
        rows: usize,
        beta: f32,
    ) -> Result<(), NetworkError> {
        gemm_rhs_transposed(
            &self.context.blas,
            x,
            weight.cols(),
            weight.value(),
            weight.cols(),
            out,
            weight.rows(),
            rows,
            weight.rows(),
            weight.cols(),
            1.0,
            beta,
        )
    }

    /// `out = grad_output . weight + beta * out`, the input-gradient half of a
    /// linear layer.
    fn linear_backward_input<G: DevicePtr<f32>, O: DevicePtrMut<f32>>(
        &self,
        weight: &DeviceParam,
        grad_output: &G,
        out: &mut O,
        rows: usize,
        beta: f32,
    ) -> Result<(), NetworkError> {
        gemm_plain(
            &self.context.blas,
            grad_output,
            weight.rows(),
            weight.value(),
            weight.cols(),
            out,
            weight.cols(),
            rows,
            weight.cols(),
            weight.rows(),
            1.0,
            beta,
        )
    }

    /// `negated_grad -= grad_output^T . input`, which is the device gradient
    /// convention the shared optimizer kernels expect.
    fn accumulate_weight_grad<G: DevicePtr<f32>, X: DevicePtr<f32>>(
        &self,
        weight: &mut DeviceParam,
        grad_output: &G,
        input: &X,
        rows: usize,
    ) -> Result<(), NetworkError> {
        let (units, cols) = (weight.rows(), weight.cols());
        gemm_lhs_transposed(
            &self.context.blas,
            grad_output,
            units,
            input,
            cols,
            weight.negated_grad_mut(),
            cols,
            rows,
            units,
            cols,
            -1.0,
            1.0,
        )
    }

    fn rmsnorm(
        &self,
        input: &CudaSlice<f32>,
        weight: &CudaSlice<f32>,
        rows: usize,
        cols: usize,
        eps: f32,
    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), NetworkError> {
        let mut out = self.uninit(rows * cols)?;
        let mut inverse = self.uninit(rows)?;
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.rmsnorm_forward)
                .arg(&mut out)
                .arg(&mut inverse)
                .arg(input)
                .arg(weight)
                .arg(&(rows as i32))
                .arg(&(cols as i32))
                .arg(&eps)
                .launch(row_grid(rows))
                .map_err(cuda_err("RMSNorm kernel"))?;
        }
        Ok((out, inverse))
    }

    /// Returns `dL/dinput` and accumulates the scale gradient on the device.
    #[allow(clippy::too_many_arguments)]
    fn rmsnorm_backward(
        &self,
        input: &CudaSlice<f32>,
        grad_output: &CudaSlice<f32>,
        weight: &CudaSlice<f32>,
        inverse: &CudaSlice<f32>,
        grad_weight: &mut CudaViewMut<'_, f32>,
        rows: usize,
        cols: usize,
    ) -> Result<CudaSlice<f32>, NetworkError> {
        let mut grad_input = self.uninit(rows * cols)?;
        let smem = rmsnorm_smem(cols);
        let mut config = row_grid(rows);
        config.shared_mem_bytes = smem.unwrap_or(0);
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.rmsnorm_backward)
                .arg(&mut grad_input)
                .arg(grad_weight)
                .arg(input)
                .arg(grad_output)
                .arg(weight)
                .arg(inverse)
                .arg(&(rows as i32))
                .arg(&(cols as i32))
                .arg(&(i32::from(smem.is_some())))
                .launch(config)
                .map_err(cuda_err("RMSNorm backward kernel"))?;
        }
        Ok(grad_input)
    }

    #[allow(clippy::too_many_arguments)]
    fn rope(
        &self,
        tensor: &mut CudaSlice<f32>,
        tables: &DeviceRope,
        rows: usize,
        heads: usize,
        head_dim: usize,
        seq_len: usize,
        direction: f32,
    ) -> Result<(), NetworkError> {
        let elements = rows * heads * head_dim / 2;
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.rope)
                .arg(tensor)
                .arg(&tables.cos)
                .arg(&tables.sin)
                .arg(&(rows as i32))
                .arg(&(heads as i32))
                .arg(&(head_dim as i32))
                .arg(&(seq_len as i32))
                .arg(&direction)
                .launch(cfg(elements))
                .map_err(cuda_err("RoPE kernel"))?;
        }
        Ok(())
    }

    fn causal_softmax(
        &self,
        scores: &mut CudaSlice<f32>,
        rows: usize,
        seq_len: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.causal_softmax)
                .arg(scores)
                .arg(&(rows as i32))
                .arg(&(seq_len as i32))
                .launch(warp_per_row_grid(rows))
                .map_err(cuda_err("causal softmax kernel"))?;
        }
        Ok(())
    }

    fn causal_softmax_backward(
        &self,
        grad: &mut CudaSlice<f32>,
        probabilities: &CudaSlice<f32>,
        rows: usize,
        seq_len: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.causal_softmax_backward)
                .arg(grad)
                .arg(probabilities)
                .arg(&(rows as i32))
                .arg(&(seq_len as i32))
                .launch(warp_per_row_grid(rows))
                .map_err(cuda_err("causal softmax backward kernel"))?;
        }
        Ok(())
    }

    fn add(
        &self,
        target: &mut CudaSlice<f32>,
        source: &CudaSlice<f32>,
        len: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.add)
                .arg(target)
                .arg(source)
                .arg(&(len as i32))
                .launch(cfg(len))
                .map_err(cuda_err("addition kernel"))?;
        }
        Ok(())
    }

    fn gather(
        &self,
        out: &mut CudaSlice<f32>,
        source: &CudaSlice<f32>,
        rows_of: &CudaSlice<u32>,
        rows: usize,
        width: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.gather)
                .arg(out)
                .arg(source)
                .arg(rows_of)
                .arg(&0i32)
                .arg(&(rows as i32))
                .arg(&(width as i32))
                .launch(cfg(rows * width))
                .map_err(cuda_err("row gather kernel"))?;
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn gather_scaled(
        &self,
        out: &mut CudaSlice<f32>,
        source: &CudaSlice<f32>,
        rows_of: &CudaSlice<u32>,
        scale: &CudaSlice<f32>,
        rows: usize,
        width: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.gather_scaled)
                .arg(out)
                .arg(source)
                .arg(rows_of)
                .arg(scale)
                .arg(&(rows as i32))
                .arg(&(width as i32))
                .launch(cfg(rows * width))
                .map_err(cuda_err("scaled row gather kernel"))?;
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn scatter_scaled(
        &self,
        out: &mut CudaSlice<f32>,
        source: &CudaSlice<f32>,
        rows_of: &CudaSlice<u32>,
        scale: &CudaSlice<f32>,
        rows: usize,
        width: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.scatter_scaled)
                .arg(out)
                .arg(source)
                .arg(rows_of)
                .arg(scale)
                .arg(&(rows as i32))
                .arg(&(width as i32))
                .launch(cfg(rows * width))
                .map_err(cuda_err("scaled row scatter kernel"))?;
        }
        Ok(())
    }

    fn scatter(
        &self,
        out: &mut CudaSlice<f32>,
        source: &CudaSlice<f32>,
        rows_of: &CudaSlice<u32>,
        rows: usize,
        width: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.scatter)
                .arg(out)
                .arg(source)
                .arg(rows_of)
                .arg(&(rows as i32))
                .arg(&(width as i32))
                .launch(cfg(rows * width))
                .map_err(cuda_err("row scatter kernel"))?;
        }
        Ok(())
    }

    /// Scatters `-upstream` into a device gradient, which is the embedding
    /// table's backward pass under the negated-gradient convention.
    fn scatter_negated(
        &self,
        grad: &mut CudaSlice<f32>,
        upstream: &CudaSlice<f32>,
        rows_of: &CudaSlice<u32>,
        rows: usize,
        width: usize,
    ) -> Result<(), NetworkError> {
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.scatter_negated)
                .arg(grad)
                .arg(upstream)
                .arg(rows_of)
                .arg(&(rows as i32))
                .arg(&(width as i32))
                .launch(cfg(rows * width))
                .map_err(cuda_err("embedding scatter kernel"))?;
        }
        Ok(())
    }

    fn swiglu(
        &self,
        gate: &CudaSlice<f32>,
        up: &CudaSlice<f32>,
        len: usize,
    ) -> Result<CudaSlice<f32>, NetworkError> {
        let mut hidden = self.uninit(len)?;
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.swiglu_forward)
                .arg(&mut hidden)
                .arg(gate)
                .arg(up)
                .arg(&(len as i32))
                .launch(cfg(len))
                .map_err(cuda_err("SwiGLU kernel"))?;
        }
        Ok(hidden)
    }

    fn swiglu_backward(
        &self,
        cache: &SwiGluCache,
        grad_hidden: &CudaSlice<f32>,
        len: usize,
    ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), NetworkError> {
        let mut grad_gate = self.uninit(len)?;
        let mut grad_up = self.uninit(len)?;
        unsafe {
            self.context
                .stream
                .launch_builder(&self.context.model.swiglu_backward)
                .arg(&mut grad_gate)
                .arg(&mut grad_up)
                .arg(&cache.gate)
                .arg(&cache.up)
                .arg(grad_hidden)
                .arg(&(len as i32))
                .launch(cfg(len))
                .map_err(cuda_err("SwiGLU backward kernel"))?;
        }
        Ok((grad_gate, grad_up))
    }
}

/// The device mirror of a projection, or an error naming the layer that is
/// still host-resident.
/// The output projection: an untied `lm_head`, or the embedding table when the
/// weights are tied.
fn head_of(model: &TransformerLm) -> Result<&DeviceParam, NetworkError> {
    match &model.lm_head {
        Some(head) => device_of(head),
        None => model.embedding.weight.device.as_ref().ok_or_else(|| {
            NetworkError::Cuda("the embedding table is not resident on the device".into())
        }),
    }
}

fn head_of_mut(model: &mut TransformerLm) -> Result<&mut DeviceParam, NetworkError> {
    match &mut model.lm_head {
        Some(head) => device_of_mut(head),
        None => model.embedding.weight.device.as_mut().ok_or_else(|| {
            NetworkError::Cuda("the embedding table is not resident on the device".into())
        }),
    }
}

fn device_of(linear: &Linear) -> Result<&DeviceParam, NetworkError> {
    linear.weight.device.as_ref().ok_or_else(|| {
        NetworkError::Cuda("a projection is not resident on the device".into())
    })
}

fn device_of_mut(linear: &mut Linear) -> Result<&mut DeviceParam, NetworkError> {
    linear.weight.device.as_mut().ok_or_else(|| {
        NetworkError::Cuda("a projection is not resident on the device".into())
    })
}

/// The device path implements the SwiGLU shape only, which is what
/// [`TransformerBuilder`](crate::transformer::TransformerBuilder) builds.
fn unsupported(kind: &str) -> NetworkError {
    NetworkError::UnsupportedCuda(format!(
        "the device training path implements SwiGLU feed-forwards and MoE layers, not {kind}"
    ))
}

/// Device-resident forward pass over a packed batch.
///
/// Returns the logits on the host, because the caller's loss is a host
/// computation, and a cache of device buffers for [`backward`]. The logits are
/// `[rows, vocab_size]`, which for a real vocabulary is the largest tensor in
/// the step by a wide margin; [`train_step`] exists so that the training path
/// never has to materialize it.
pub(crate) fn forward(
    model: &TransformerLm,
    context: &Arc<GpuContext>,
    batch: &TokenBatch,
) -> Result<(Matrix, GpuCache), NetworkError> {
    let cache = forward_hidden(model, context, batch)?;
    let gpu = Gpu { context };
    let logits = gpu.linear(head_of(model)?, &cache.final_output, cache.rows)?;
    let logits = gpu.matrix(&logits, cache.rows, model.embedding.vocab_size())?;
    Ok((logits, cache))
}

/// Everything [`forward`] does except the language-model head, which the two
/// callers want in different shapes.
fn forward_hidden(
    model: &TransformerLm,
    context: &Arc<GpuContext>,
    batch: &TokenBatch,
) -> Result<GpuCache, NetworkError> {
    let gpu = Gpu { context };
    let rows = batch.rows();
    let seq_len = batch.seq_len();
    let sequences = batch.batch();
    let d_model = model.config.d_model;
    let vocab = model.embedding.vocab_size();

    for &id in batch.ids() {
        if id as usize >= vocab {
            return Err(NetworkError::TokenOutOfRange {
                id,
                vocab_size: vocab,
            });
        }
    }

    let layout = batch.layout();
    let flags: Vec<i32> = (0..rows).map(|row| i32::from(layout.is_valid(row))).collect();
    let valid_tokens = flags.iter().filter(|&&flag| flag != 0).count();
    let valid = gpu.upload_flags(&flags)?;
    let ids = gpu.upload_indices(batch.ids())?;

    let embedding = model.embedding.weight.device.as_ref().ok_or_else(|| {
        NetworkError::Cuda("the embedding table is not resident on the device".into())
    })?;
    let mut hidden = gpu.uninit(rows * d_model)?;
    gpu.gather(&mut hidden, embedding.value(), &ids, rows, d_model)?;

    let mut blocks = Vec::with_capacity(model.blocks.len());
    let mut auxiliary_loss = 0.0;

    for block in &model.blocks {
        let (output, cache) = forward_block(
            &gpu,
            block,
            hidden,
            &valid,
            valid_tokens,
            rows,
            seq_len,
            sequences,
            &mut auxiliary_loss,
        )?;
        blocks.push(cache);
        hidden = output;
    }

    let final_weight = gpu.upload(&model.final_norm.weight.value.data)?;
    let (final_output, final_inverse_rms) = gpu.rmsnorm(
        &hidden,
        &final_weight,
        rows,
        d_model,
        model.final_norm.eps,
    )?;

    Ok(GpuCache {
        rows,
        seq_len,
        sequences,
        ids,
        valid_tokens,
        blocks,
        final_input: hidden,
        final_inverse_rms,
        final_weight,
        final_output,
        auxiliary_loss,
    })
}

/// One decoder block: pre-norm attention, then a pre-norm feed-forward, both
/// residual. `input` is consumed into the cache, which is what the backward
/// pass needs it for.
#[allow(clippy::too_many_arguments)]
fn forward_block(
    gpu: &Gpu<'_>,
    block: &TransformerBlock,
    input: CudaSlice<f32>,
    valid: &CudaSlice<i32>,
    valid_tokens: usize,
    rows: usize,
    seq_len: usize,
    sequences: usize,
    auxiliary_loss: &mut f32,
) -> Result<(CudaSlice<f32>, BlockCache), NetworkError> {
    let attention = &block.attention;
    let d_model = attention.d_model();
    let heads = attention.num_heads();
    let kv_heads = attention.num_kv_heads();
    let head_dim = attention.head_dim();
    let group = heads / kv_heads;
    let scale = (head_dim as f32).sqrt().recip();
    let query_width = heads * head_dim;
    let kv_width = kv_heads * head_dim;

    let attention_weight = gpu.upload(&block.attention_norm.weight.value.data)?;
    let (attention_normed, attention_inverse_rms) = gpu.rmsnorm(
        &input,
        &attention_weight,
        rows,
        d_model,
        block.attention_norm.eps,
    )?;

    let mut queries = gpu.linear(device_of(&attention.query)?, &attention_normed, rows)?;
    let mut keys = gpu.linear(device_of(&attention.key)?, &attention_normed, rows)?;
    let values = gpu.linear(device_of(&attention.value)?, &attention_normed, rows)?;

    let tables = gpu.rope_tables(&attention.rope)?;
    if seq_len > tables.max_seq_len {
        return Err(NetworkError::SequenceTooLong {
            length: seq_len,
            max_seq_len: tables.max_seq_len,
        });
    }
    gpu.rope(&mut queries, &tables, rows, heads, head_dim, seq_len, 1.0)?;
    gpu.rope(&mut keys, &tables, rows, kv_heads, head_dim, seq_len, 1.0)?;

    // Scores are `[head][sequence][query, key]`. Every head is one batched GEMM
    // over the sequences, and the 1/sqrt(head_dim) scale rides along in alpha.
    let mut probabilities = gpu.uninit(heads * sequences * seq_len * seq_len)?;
    for head in 0..heads {
        let kv_base = (head / group) * head_dim;
        let query = queries.slice(head * head_dim..);
        let key = keys.slice(kv_base..);
        let mut scores = probabilities.slice_mut(head * sequences * seq_len * seq_len..);
        gemm_rhs_transposed_batched(
            &gpu.context.blas,
            &query,
            query_width,
            &key,
            kv_width,
            &mut scores,
            seq_len,
            seq_len,
            seq_len,
            head_dim,
            scale,
            0.0,
            sequences,
            seq_len * query_width,
            seq_len * kv_width,
            seq_len * seq_len,
        )?;
    }
    gpu.causal_softmax(&mut probabilities, heads * sequences * seq_len, seq_len)?;

    let mut merged = gpu.uninit(rows * query_width)?;
    for head in 0..heads {
        let kv_base = (head / group) * head_dim;
        let scores = probabilities.slice(head * sequences * seq_len * seq_len..);
        let value = values.slice(kv_base..);
        let mut out = merged.slice_mut(head * head_dim..);
        gemm_plain_batched(
            &gpu.context.blas,
            &scores,
            seq_len,
            &value,
            kv_width,
            &mut out,
            query_width,
            seq_len,
            head_dim,
            seq_len,
            1.0,
            0.0,
            sequences,
            seq_len * seq_len,
            seq_len * kv_width,
            seq_len * query_width,
        )?;
    }

    // The residual is the output projection's GEMM with beta = 1 over a copy of
    // the block input, so the addition costs no extra kernel.
    let mut residual = gpu.duplicate(&input)?;
    gpu.linear_into(
        device_of(&attention.output)?,
        &merged,
        &mut residual,
        rows,
        1.0,
    )?;

    let feed_forward_weight = gpu.upload(&block.feed_forward_norm.weight.value.data)?;
    let (feed_forward_normed, feed_forward_inverse_rms) = gpu.rmsnorm(
        &residual,
        &feed_forward_weight,
        rows,
        d_model,
        block.feed_forward_norm.eps,
    )?;

    let mut output = gpu.duplicate(&residual)?;
    let feed_forward = match &block.feed_forward {
        FeedForward::SwiGlu(ffn) => FfnCache::Dense(forward_swiglu(
            gpu,
            ffn,
            &feed_forward_normed,
            &mut output,
            rows,
        )?),
        FeedForward::Gelu(_) => return Err(unsupported("a GELU MLP")),
        FeedForward::Moe(moe) => {
            let (cache, losses) = forward_moe(
                gpu,
                moe,
                &feed_forward_normed,
                &mut output,
                valid,
                valid_tokens,
                rows,
            )?;
            *auxiliary_loss += losses;
            FfnCache::Moe(Box::new(cache))
        }
    };

    Ok((
        output,
        BlockCache {
            input,
            attention_weight,
            attention_inverse_rms,
            attention_normed,
            queries,
            keys,
            values,
            probabilities,
            merged,
            residual,
            feed_forward_weight,
            feed_forward_inverse_rms,
            feed_forward_normed,
            feed_forward,
        },
    ))
}

/// `out += down(silu(gate(x)) * up(x))`.
fn forward_swiglu(
    gpu: &Gpu<'_>,
    ffn: &SwiGlu,
    input: &CudaSlice<f32>,
    out: &mut CudaSlice<f32>,
    rows: usize,
) -> Result<SwiGluCache, NetworkError> {
    let width = ffn.d_ff();
    let gate = gpu.linear(device_of(&ffn.gate)?, input, rows)?;
    let up = gpu.linear(device_of(&ffn.up)?, input, rows)?;
    let hidden = gpu.swiglu(&gate, &up, rows * width)?;
    gpu.linear_into(device_of(&ffn.down)?, &hidden, out, rows, 1.0)?;
    Ok(SwiGluCache { gate, up, hidden })
}

/// The routed feed-forward.
///
/// The router's softmax, top-k and gate renormalization are one kernel each.
/// The routing table then comes back to the host once, so the per-expert token
/// counts can shape the expert GEMMs, and the tokens are gathered into one
/// contiguous buffer grouped by expert: three GEMMs per non-empty expert for
/// the whole batch, not three per expert per sequence.
#[allow(clippy::too_many_arguments)]
fn forward_moe(
    gpu: &Gpu<'_>,
    moe: &MoeLayer,
    input: &CudaSlice<f32>,
    out: &mut CudaSlice<f32>,
    valid: &CudaSlice<i32>,
    valid_tokens: usize,
    rows: usize,
) -> Result<(MoeGpuCache, f32), NetworkError> {
    let experts = moe.config.num_experts;
    let top_k = moe.config.experts_per_token;
    let d_model = moe.d_model();
    let width = moe.config.d_ff;

    let logits = gpu.linear(device_of(&moe.router.projection)?, input, rows)?;
    let mut probabilities = gpu.zeros(rows * experts)?;
    let mut log_sum_exp = gpu.zeros(rows)?;
    unsafe {
        gpu.context
            .stream
            .launch_builder(&gpu.context.model.softmax_lse)
            .arg(&mut probabilities)
            .arg(&mut log_sum_exp)
            .arg(&logits)
            .arg(&(rows as i32))
            .arg(&(experts as i32))
            .launch(cfg(rows))
            .map_err(cuda_err("router softmax kernel"))?;
    }

    let mut expert_of = gpu
        .context
        .stream
        .alloc_zeros::<i32>(rows * top_k)
        .map_err(cuda_err("device allocation"))?;
    let mut gate_of = gpu.zeros(rows * top_k)?;
    unsafe {
        gpu.context
            .stream
            .launch_builder(&gpu.context.model.topk_gate)
            .arg(&mut expert_of)
            .arg(&mut gate_of)
            .arg(&probabilities)
            .arg(valid)
            .arg(&(rows as i32))
            .arg(&(experts as i32))
            .arg(&(top_k as i32))
            .launch(cfg(rows))
            .map_err(cuda_err("router top-k kernel"))?;
    }

    // The one deliberate round trip: cuBLAS needs each expert's token count on
    // the host to shape its GEMM.
    let assigned = gpu.download_signed(&expert_of)?;
    let gates_host = gpu.download(&gate_of)?;

    let mut counts = vec![0usize; experts];
    for &expert in &assigned {
        if expert >= 0 {
            counts[expert as usize] += 1;
        }
    }
    let mut offsets = Vec::with_capacity(experts);
    let mut routed = 0;
    for &count in &counts {
        offsets.push(routed);
        routed += count;
    }

    let mut cursor = offsets.clone();
    let mut token_host = vec![0u32; routed.max(1)];
    let mut slot_host = vec![0u32; routed.max(1)];
    let mut gate_host = vec![0f32; routed.max(1)];
    for (slot, &expert) in assigned.iter().enumerate() {
        if expert < 0 {
            continue;
        }
        let position = &mut cursor[expert as usize];
        token_host[*position] = (slot / top_k) as u32;
        slot_host[*position] = slot as u32;
        gate_host[*position] = gates_host[slot];
        *position += 1;
    }

    let token_of = gpu.upload_indices(&token_host)?;
    let slot_of = gpu.upload_indices(&slot_host)?;
    let gates = gpu.upload(&gate_host)?;

    // Every one of these is written in full before it is read: `gather` and
    // `gather_scaled` touch every routed row, and the per-expert loops
    // partition the routed rows between them with `beta = 0` on the first
    // write of each slice.
    let mut gathered = gpu.uninit(routed * d_model)?;
    if routed > 0 {
        gpu.gather(&mut gathered, input, &token_of, routed, d_model)?;
    }

    let mut gate_activations = gpu.uninit(routed * width)?;
    let mut up_activations = gpu.uninit(routed * width)?;
    for (expert, module) in moe.experts.iter().enumerate() {
        let count = counts[expert];
        if count == 0 {
            continue;
        }
        let rows_in = gathered.slice(offsets[expert] * d_model..);
        let mut gate = gate_activations.slice_mut(offsets[expert] * width..);
        gpu.linear_into(device_of(&module.gate)?, &rows_in, &mut gate, count, 0.0)?;
        let mut up = up_activations.slice_mut(offsets[expert] * width..);
        gpu.linear_into(device_of(&module.up)?, &rows_in, &mut up, count, 0.0)?;
    }
    let hidden = gpu.swiglu(&gate_activations, &up_activations, routed * width)?;

    let mut expert_output = gpu.uninit(routed * d_model)?;
    for (expert, module) in moe.experts.iter().enumerate() {
        let count = counts[expert];
        if count == 0 {
            continue;
        }
        let rows_in = hidden.slice(offsets[expert] * width..);
        let mut rows_out = expert_output.slice_mut(offsets[expert] * d_model..);
        gpu.linear_into(device_of(&module.down)?, &rows_in, &mut rows_out, count, 0.0)?;
    }
    if routed > 0 {
        gpu.scatter_scaled(out, &expert_output, &token_of, &gates, routed, d_model)?;
    }

    let shared = match &moe.shared {
        Some(module) => Some(forward_swiglu(gpu, module, input, out, rows)?),
        None => None,
    };

    // One download of `num_experts + 1` floats carries both auxiliary losses:
    // the per-expert probability mass, and the summed squared log-sum-exp.
    let mut sums = gpu.zeros(experts + 1)?;
    unsafe {
        gpu.context
            .stream
            .launch_builder(&gpu.context.model.stats)
            .arg(&mut sums)
            .arg(&probabilities)
            .arg(&log_sum_exp)
            .arg(valid)
            .arg(&(rows as i32))
            .arg(&(experts as i32))
            .launch(cfg(rows))
            .map_err(cuda_err("MoE statistics kernel"))?;
    }
    let sums = gpu.download(&sums)?;

    let mut auxiliary = 0.0;
    if valid_tokens > 0 {
        let slots = (valid_tokens * top_k) as f32;
        let balance: f32 = (0..experts)
            .map(|expert| {
                (counts[expert] as f32 / slots) * (sums[expert] / valid_tokens as f32)
            })
            .sum();
        auxiliary += experts as f32 * moe.config.aux_loss_weight * balance;
        auxiliary += moe.config.router_z_loss_weight * sums[experts] / valid_tokens as f32;
    }

    Ok((
        MoeGpuCache {
            probabilities,
            log_sum_exp,
            expert_of,
            token_of,
            slot_of,
            gates,
            offsets,
            counts,
            routed,
            input: gathered,
            expert: SwiGluCache {
                gate: gate_activations,
                up: up_activations,
                hidden,
            },
            output: expert_output,
            shared,
        },
        auxiliary,
    ))
}

/// Device-resident backward pass.
///
/// `grad_logits` arrives from the host loss and every gradient produced here
/// stays on the device, except the RMSNorm scales, which are host-owned so that
/// cached decode keeps working.
pub(crate) fn backward(
    model: &mut TransformerLm,
    context: &Arc<GpuContext>,
    cache: &GpuCache,
    grad_logits: &Matrix,
) -> Result<(), NetworkError> {
    let gpu = Gpu { context };
    let rows = cache.rows;
    let d_model = model.config.d_model;

    if grad_logits.rows != rows {
        return Err(NetworkError::InvalidInput {
            expected: rows,
            actual: grad_logits.rows,
        });
    }

    let upstream = gpu.upload(&grad_logits.data)?;
    let mut grad_final = gpu.zeros(rows * d_model)?;
    {
        // Tied weights land in the same gradient buffer the embedding scatter
        // writes to at the end, which is what tying means.
        let head = head_of_mut(model)?;
        gpu.linear_backward_input(head, &upstream, &mut grad_final, rows, 0.0)?;
        gpu.accumulate_weight_grad(head, &upstream, &cache.final_output, rows)?;
    }

    backward_from_final(model, context, cache, &grad_final)
}

/// Forward, loss and backward with the logits never leaving the device.
///
/// The `[rows, vocab_size]` logits dominate a training step: at batch 256 and
/// sequence 128 over a 32k vocabulary they are 4 GiB, and the host loss paid
/// for them four times over - a 4 GiB download, a 4 GiB host allocation, a
/// single-threaded softmax over a billion elements, and a 4 GiB upload. On an
/// RTX 3060 that was 86% of the step while the GPU sat idle.
///
/// Here the head runs one chunk of rows at a time. Each chunk's logits are
/// turned into their own gradient in place by `ce_loss_grad` and consumed by
/// the head's backward before the next chunk is produced, so the peak cost is
/// one chunk rather than the whole matrix, and nothing crosses the bus except
/// the row targets going out and one loss scalar coming back. Capping the
/// chunk instead of the batch is also what lets a large batch run at all: the
/// full logits for batch 1024 do not fit in 12 GiB, one chunk always does.
///
/// Returns the mean language-modelling loss and the summed auxiliary losses.
pub(crate) fn train_step(
    model: &mut TransformerLm,
    context: &Arc<GpuContext>,
    batch: &TokenBatch,
) -> Result<(f32, f32), NetworkError> {
    let vocab = model.embedding.vocab_size();
    let predicted = batch.predicted();
    if predicted == 0 {
        return Err(NetworkError::InvalidConfig(
            "a causal language-modelling loss needs at least two tokens".into(),
        ));
    }
    // The kernel carries targets as `int`, and -1 marks a row that predicts
    // nothing, so a vocabulary that does not fit in a positive `i32` is
    // refused rather than silently aliased onto that marker.
    if vocab > i32::MAX as usize {
        return Err(NetworkError::InvalidConfig(format!(
            "the device loss supports vocabularies up to {}, got {vocab}",
            i32::MAX
        )));
    }
    let targets = causal_targets(batch, vocab)?;

    let cache = forward_hidden(model, context, batch)?;
    let gpu = Gpu { context };
    let rows = cache.rows;
    let d_model = model.config.d_model;

    let targets = gpu.upload_signed(&targets)?;
    let mut loss = gpu.zeros(1)?;
    let mut grad_final = gpu.zeros(rows * d_model)?;
    let inverse_predicted = 1.0 / predicted as f32;
    let logit_bytes = if gpu.context.mixed_precision { 2 } else { 4 };
    let chunk = head_chunk_rows(rows, vocab, logit_bytes);

    {
        let head = head_of_mut(model)?;
        let mut reduced = gpu
            .context
            .mixed_precision
            .then(|| HeadBf16::new(&gpu, head, chunk))
            .transpose()?;
        let mut start = 0;
        while start < rows {
            let count = chunk.min(rows - start);
            let input = cache.final_output.slice(start * d_model..(start + count) * d_model);
            let targets = targets.slice(start..start + count);
            let mut out = grad_final.slice_mut(start * d_model..(start + count) * d_model);
            if let Some(reduced) = reduced.as_mut() {
                reduced.chunk(
                    &gpu,
                    head,
                    &input,
                    &targets,
                    &mut loss,
                    &mut out,
                    count,
                    inverse_predicted,
                )?;
                start += count;
                continue;
            }
            let mut logits = gpu.linear(head, &input, count)?;
            unsafe {
                gpu.context
                    .stream
                    .launch_builder(&gpu.context.model.cross_entropy)
                    .arg(&mut logits)
                    .arg(&mut loss)
                    .arg(&targets)
                    .arg(&(count as i32))
                    .arg(&(vocab as i32))
                    .arg(&inverse_predicted)
                    .launch(row_per_block(count))
                    .map_err(cuda_err("cross-entropy kernel"))?;
            }
            // `logits` now holds dL/dlogits for this chunk.
            gpu.linear_backward_input(head, &logits, &mut out, count, 0.0)?;
            gpu.accumulate_weight_grad(head, &logits, &input, count)?;
            start += count;
        }
    }

    // After the backward pass, not before: this download drains the stream,
    // and the backward pass does not need the value.
    backward_from_final(model, context, &cache, &grad_final)?;
    let lm_loss = gpu.download(&loss)?[0] / predicted as f32;
    Ok((lm_loss, cache.auxiliary_loss))
}

/// The LM head run in BF16, behind [`crate::TransformerBuilder::mixed_precision`].
///
/// The head is the one part of the step where reduced precision is worth its
/// casts: its three GEMMs are about three quarters of all GEMM time, because
/// every one of them is `vocab`-wide. Weights, optimizer state and the
/// gradient that leaves for the rest of the network all stay FP32; only the
/// head's own multiplier inputs, its logits and its two gradient products are
/// BF16, and cuBLAS still accumulates those in FP32.
///
/// No loss scaling. BF16 has FP32's exponent range, so the smallest gradient
/// here, around `1 / predicted_tokens`, is some thirty orders of magnitude
/// above the smallest normal BF16 and nothing underflows that FP32 would have
/// kept.
struct HeadBf16 {
    /// The head weight, cast once per step.
    weight: CudaSlice<bf16>,
    /// One chunk's product `-dL/dW`, widened into the FP32 gradient after
    /// every chunk rather than accumulated in BF16.
    weight_grad: CudaSlice<bf16>,
    input: CudaSlice<bf16>,
    logits: CudaSlice<bf16>,
    grad_input: CudaSlice<bf16>,
}

impl HeadBf16 {
    fn new(gpu: &Gpu, head: &DeviceParam, chunk: usize) -> Result<Self, NetworkError> {
        let (vocab, d_model) = (head.rows(), head.cols());
        let mut weight = gpu.uninit_bf16(vocab * d_model)?;
        gpu.cast_to_bf16(&mut weight, &head.value().slice(..), vocab * d_model)?;
        Ok(Self {
            weight,
            weight_grad: gpu.uninit_bf16(vocab * d_model)?,
            input: gpu.uninit_bf16(chunk * d_model)?,
            logits: gpu.uninit_bf16(chunk * vocab)?,
            grad_input: gpu.uninit_bf16(chunk * d_model)?,
        })
    }

    /// Forward, loss and both gradients for one chunk of rows.
    ///
    /// `grad_input` is overwritten, and `head`'s negated gradient accumulated
    /// into, exactly as the FP32 path does.
    #[allow(clippy::too_many_arguments)]
    fn chunk(
        &mut self,
        gpu: &Gpu,
        head: &mut DeviceParam,
        input: &CudaView<'_, f32>,
        targets: &CudaView<'_, i32>,
        loss: &mut CudaSlice<f32>,
        grad_input: &mut CudaViewMut<'_, f32>,
        count: usize,
        inverse_predicted: f32,
    ) -> Result<(), NetworkError> {
        let (vocab, d_model) = (head.rows(), head.cols());
        let blas = &gpu.context.blas;
        gpu.cast_to_bf16(&mut self.input, input, count * d_model)?;
        gemm_rhs_transposed(
            blas,
            &self.input,
            d_model,
            &self.weight,
            d_model,
            &mut self.logits,
            vocab,
            count,
            vocab,
            d_model,
            bf16::ONE,
            bf16::ZERO,
        )?;
        unsafe {
            gpu.context
                .stream
                .launch_builder(&gpu.context.model.cross_entropy_bf16)
                .arg(&mut self.logits)
                .arg(loss)
                .arg(targets)
                .arg(&(count as i32))
                .arg(&(vocab as i32))
                .arg(&inverse_predicted)
                .launch(row_per_block(count))
                .map_err(cuda_err("cross-entropy kernel"))?;
        }
        // `self.logits` now holds dL/dlogits for this chunk.
        gemm_plain(
            blas,
            &self.logits,
            vocab,
            &self.weight,
            d_model,
            &mut self.grad_input,
            d_model,
            count,
            d_model,
            vocab,
            bf16::ONE,
            bf16::ZERO,
        )?;
        gpu.cast_from_bf16(grad_input, &self.grad_input, count * d_model)?;
        gemm_lhs_transposed(
            blas,
            &self.logits,
            vocab,
            &self.input,
            d_model,
            &mut self.weight_grad,
            d_model,
            count,
            vocab,
            d_model,
            bf16::NEG_ONE,
            bf16::ZERO,
        )?;
        gpu.accumulate_bf16(head.negated_grad_mut(), &self.weight_grad, vocab * d_model)
    }
}

/// Next-token target per row, or -1 where a row predicts nothing.
///
/// Padding rows and the last position of every sequence predict nothing, which
/// is the same rule [`crate::causal_lm_loss_batch`] applies on the host.
fn causal_targets(batch: &TokenBatch, vocab: usize) -> Result<Vec<i32>, NetworkError> {
    let seq_len = batch.seq_len();
    let ids = batch.ids();
    let mut targets = vec![-1i32; batch.rows()];
    for (sequence, &length) in batch.lengths().iter().enumerate() {
        for position in 0..length.saturating_sub(1) {
            let row = sequence * seq_len + position;
            let id = ids[row + 1];
            if id as usize >= vocab {
                return Err(NetworkError::TokenOutOfRange {
                    id,
                    vocab_size: vocab,
                });
            }
            targets[row] = id as i32;
        }
    }
    Ok(targets)
}

/// How many rows of logits to hold at once.
///
/// Small enough that the chunk fits comfortably alongside the activations,
/// large enough that the head's GEMMs still have a tall `M`. A 32k vocabulary
/// gives about 2000 rows, which cuBLAS is already happy with.
fn head_chunk_rows(rows: usize, vocab: usize, logit_bytes: usize) -> usize {
    #[cfg(test)]
    {
        let forced = CHUNK_ROWS_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed);
        if forced > 0 {
            return forced.min(rows.max(1));
        }
    }
    // ponytail: one fixed budget, not a tuned schedule. Make it a builder knob
    // if a model ever wants a different trade against activation memory.
    const BUDGET_BYTES: usize = 256 << 20;
    (BUDGET_BYTES / (vocab * logit_bytes)).clamp(1, rows.max(1))
}

/// Forces a chunk size so a test can drive the loop over several chunks.
///
/// A real vocabulary needs thousands of rows before the budget splits the
/// head, which no parity-sized model reaches. Results must not depend on the
/// chunk size, so a test that leaves this set only slows its neighbours down.
#[cfg(test)]
pub(crate) static CHUNK_ROWS_OVERRIDE: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// One block per row, sized for `ce_loss_grad`'s shared-memory reduction.
fn row_per_block(rows: usize) -> cudarc::driver::LaunchConfig {
    cudarc::driver::LaunchConfig {
        grid_dim: (rows.max(1) as u32, 1, 1),
        block_dim: (256, 1, 1),
        shared_mem_bytes: 0,
    }
}

/// Blocks per launch for the kernels that grid-stride over rows.
///
/// A row count in the hundreds of thousands does not need a block each: the
/// cap keeps enough blocks to fill the device several times over while
/// cutting the number of blocks that contend for a shared gradient column.
const ROW_GRID_BLOCKS: usize = 2048;

/// One warp per row, eight rows per block.
fn warp_per_row_grid(rows: usize) -> cudarc::driver::LaunchConfig {
    cudarc::driver::LaunchConfig {
        grid_dim: (rows.div_ceil(8).clamp(1, ROW_GRID_BLOCKS) as u32, 1, 1),
        block_dim: (256, 1, 1),
        shared_mem_bytes: 0,
    }
}

fn row_grid(rows: usize) -> cudarc::driver::LaunchConfig {
    cudarc::driver::LaunchConfig {
        grid_dim: (rows.clamp(1, ROW_GRID_BLOCKS) as u32, 1, 1),
        block_dim: (256, 1, 1),
        shared_mem_bytes: 0,
    }
}

/// Shared memory for `rmsnorm_bwd`'s per-block scale-gradient accumulator, or
/// `None` for a width that will not fit in the 48 KiB a block gets by default.
fn rmsnorm_smem(cols: usize) -> Option<u32> {
    let bytes = cols.checked_mul(4)?;
    (bytes <= 48 << 10).then_some(bytes as u32)
}

/// The rest of the backward pass, once the gradient with respect to the final
/// normalization's output is known.
///
/// [`backward`] gets there from a host `dL/dlogits`; [`train_step`] gets there
/// from the fused loss, one chunk of rows at a time.
fn backward_from_final(
    model: &mut TransformerLm,
    context: &Arc<GpuContext>,
    cache: &GpuCache,
    grad_final: &CudaSlice<f32>,
) -> Result<(), NetworkError> {
    let gpu = Gpu { context };
    let rows = cache.rows;
    let d_model = model.config.d_model;

    // Every RMSNorm scale gradient in the model, in one buffer: slot 0 is the
    // final norm, then two slots per block. See [`Gpu::accumulate_host_grad`]
    // for why they are not downloaded where they are produced.
    let mut grad_norms = gpu.zeros(norm_slots(model.blocks.len()) * d_model)?;
    let mut grad_hidden = gpu.rmsnorm_backward(
        &cache.final_input,
        grad_final,
        &cache.final_weight,
        &cache.final_inverse_rms,
        &mut grad_norms.slice_mut(0..d_model),
        rows,
        d_model,
    )?;

    for (index, (block, block_cache)) in
        model.blocks.iter_mut().zip(&cache.blocks).enumerate().rev()
    {
        grad_hidden = backward_block(
            &gpu,
            block,
            block_cache,
            &grad_hidden,
            cache,
            &mut grad_norms,
            index,
        )?;
    }

    {
        let embedding = model.embedding.weight.device.as_mut().ok_or_else(|| {
            NetworkError::Cuda("the embedding table is not resident on the device".into())
        })?;
        gpu.scatter_negated(
            embedding.negated_grad_mut(),
            &grad_hidden,
            &cache.ids,
            rows,
            d_model,
        )?;
    }

    // The one host round trip of the backward pass, after everything else is
    // enqueued.
    let values = gpu.download(&grad_norms)?;
    let at = |slot: usize| &values[slot * d_model..(slot + 1) * d_model];
    Gpu::accumulate_host_grad(&mut model.final_norm.weight, at(0));
    for (index, block) in model.blocks.iter_mut().enumerate() {
        let (attention, feed_forward) = norm_slot(index);
        Gpu::accumulate_host_grad(&mut block.attention_norm.weight, at(attention));
        Gpu::accumulate_host_grad(&mut block.feed_forward_norm.weight, at(feed_forward));
    }
    Ok(())
}

/// Slots in the scale-gradient block: the final norm, then two per block.
fn norm_slots(blocks: usize) -> usize {
    1 + 2 * blocks
}

/// The `(attention_norm, feed_forward_norm)` slots of block `index`.
fn norm_slot(index: usize) -> (usize, usize) {
    (1 + 2 * index, 2 + 2 * index)
}

#[allow(clippy::too_many_arguments)]
fn backward_block(
    gpu: &Gpu<'_>,
    block: &mut TransformerBlock,
    cache: &BlockCache,
    grad_output: &CudaSlice<f32>,
    batch: &GpuCache,
    grad_norms: &mut CudaSlice<f32>,
    index: usize,
) -> Result<CudaSlice<f32>, NetworkError> {
    let rows = batch.rows;
    let d_model = block.attention.d_model();
    let (attention_slot, feed_forward_slot) = norm_slot(index);

    let mut grad_normed = match block.feed_forward {
        FeedForward::SwiGlu(_) => gpu.uninit(rows * d_model)?,
        _ => gpu.zeros(rows * d_model)?,
    };
    match (&mut block.feed_forward, &cache.feed_forward) {
        (FeedForward::SwiGlu(ffn), FfnCache::Dense(ffn_cache)) => backward_swiglu(
            gpu,
            ffn,
            ffn_cache,
            &cache.feed_forward_normed,
            grad_output,
            &mut grad_normed,
            rows,
        )?,
        (FeedForward::Moe(moe), FfnCache::Moe(moe_cache)) => backward_moe(
            gpu,
            moe,
            moe_cache,
            &cache.feed_forward_normed,
            grad_output,
            &mut grad_normed,
            batch.valid_tokens,
            rows,
        )?,
        (FeedForward::Gelu(_), _) => return Err(unsupported("a GELU MLP")),
        _ => {
            return Err(NetworkError::Cuda(
                "the device cache does not match the layer that produced it".into(),
            ));
        }
    }

    let mut grad_residual = gpu.rmsnorm_backward(
        &cache.residual,
        &grad_normed,
        &cache.feed_forward_weight,
        &cache.feed_forward_inverse_rms,
        &mut grad_norms.slice_mut(feed_forward_slot * d_model..(feed_forward_slot + 1) * d_model),
        rows,
        d_model,
    )?;
    // The residual passes the upstream gradient through untouched alongside the
    // branch gradient.
    gpu.add(&mut grad_residual, grad_output, rows * d_model)?;

    let grad_attention_normed = backward_attention(gpu, block, cache, &grad_residual, batch)?;

    let mut grad_input = gpu.rmsnorm_backward(
        &cache.input,
        &grad_attention_normed,
        &cache.attention_weight,
        &cache.attention_inverse_rms,
        &mut grad_norms.slice_mut(attention_slot * d_model..(attention_slot + 1) * d_model),
        rows,
        d_model,
    )?;
    gpu.add(&mut grad_input, &grad_residual, rows * d_model)?;

    Ok(grad_input)
}

/// Attention backward, head by head, each head one batched GEMM per operand.
///
/// RoPE is orthogonal, so its backward pass is the same rotation applied with
/// the opposite sign, and the `1/sqrt(head_dim)` scale rides in the alpha of
/// the two GEMMs that read the score gradient.
fn backward_attention(
    gpu: &Gpu<'_>,
    block: &mut TransformerBlock,
    cache: &BlockCache,
    grad_output: &CudaSlice<f32>,
    batch: &GpuCache,
) -> Result<CudaSlice<f32>, NetworkError> {
    let rows = batch.rows;
    let seq_len = batch.seq_len;
    let sequences = batch.sequences;
    let attention = &mut block.attention;
    let d_model = attention.d_model();
    let heads = attention.num_heads();
    let kv_heads = attention.num_kv_heads();
    let head_dim = attention.head_dim();
    let group = heads / kv_heads;
    let scale = (head_dim as f32).sqrt().recip();
    let query_width = heads * head_dim;
    let kv_width = kv_heads * head_dim;
    let block_size = seq_len * seq_len;

    let mut grad_merged = gpu.uninit(rows * query_width)?;
    gpu.linear_backward_input(
        device_of(&attention.output)?,
        grad_output,
        &mut grad_merged,
        rows,
        0.0,
    )?;
    gpu.accumulate_weight_grad(
        device_of_mut(&mut attention.output)?,
        grad_output,
        &cache.merged,
        rows,
    )?;

    // Every head overwrites its own slice of `grad_scores`, so the buffer does
    // not need clearing. `grad_values` does: query heads in a group accumulate
    // into the same key/value head.
    let mut grad_scores = gpu.uninit(heads * sequences * block_size)?;
    let mut grad_values = gpu.zeros(rows * kv_width)?;
    for head in 0..heads {
        let kv_base = (head / group) * head_dim;
        let upstream = grad_merged.slice(head * head_dim..);
        let value = cache.values.slice(kv_base..);
        let mut scores = grad_scores.slice_mut(head * sequences * block_size..);
        gemm_rhs_transposed_batched(
            &gpu.context.blas,
            &upstream,
            query_width,
            &value,
            kv_width,
            &mut scores,
            seq_len,
            seq_len,
            seq_len,
            head_dim,
            1.0,
            0.0,
            sequences,
            seq_len * query_width,
            seq_len * kv_width,
            block_size,
        )?;

        // Query heads in one group share a key/value head, so the value
        // gradient accumulates across them.
        let probabilities = cache.probabilities.slice(head * sequences * block_size..);
        let mut grad_value = grad_values.slice_mut(kv_base..);
        gemm_lhs_transposed_batched(
            &gpu.context.blas,
            &probabilities,
            seq_len,
            &upstream,
            query_width,
            &mut grad_value,
            kv_width,
            seq_len,
            seq_len,
            head_dim,
            1.0,
            1.0,
            sequences,
            block_size,
            seq_len * query_width,
            seq_len * kv_width,
        )?;
    }

    gpu.causal_softmax_backward(
        &mut grad_scores,
        &cache.probabilities,
        heads * sequences * seq_len,
        seq_len,
    )?;

    let mut grad_queries = gpu.uninit(rows * query_width)?;
    let mut grad_keys = gpu.zeros(rows * kv_width)?;
    for head in 0..heads {
        let kv_base = (head / group) * head_dim;
        let scores = grad_scores.slice(head * sequences * block_size..);
        let key = cache.keys.slice(kv_base..);
        let mut grad_query = grad_queries.slice_mut(head * head_dim..);
        gemm_plain_batched(
            &gpu.context.blas,
            &scores,
            seq_len,
            &key,
            kv_width,
            &mut grad_query,
            query_width,
            seq_len,
            head_dim,
            seq_len,
            scale,
            0.0,
            sequences,
            block_size,
            seq_len * kv_width,
            seq_len * query_width,
        )?;

        let query = cache.queries.slice(head * head_dim..);
        let mut grad_key = grad_keys.slice_mut(kv_base..);
        gemm_lhs_transposed_batched(
            &gpu.context.blas,
            &scores,
            seq_len,
            &query,
            query_width,
            &mut grad_key,
            kv_width,
            seq_len,
            seq_len,
            head_dim,
            scale,
            1.0,
            sequences,
            block_size,
            seq_len * query_width,
            seq_len * kv_width,
        )?;
    }

    let tables = gpu.rope_tables(&attention.rope)?;
    gpu.rope(
        &mut grad_queries,
        &tables,
        rows,
        heads,
        head_dim,
        seq_len,
        -1.0,
    )?;
    gpu.rope(
        &mut grad_keys,
        &tables,
        rows,
        kv_heads,
        head_dim,
        seq_len,
        -1.0,
    )?;

    let mut grad_input = gpu.uninit(rows * d_model)?;
    gpu.linear_backward_input(
        device_of(&attention.query)?,
        &grad_queries,
        &mut grad_input,
        rows,
        0.0,
    )?;
    gpu.linear_backward_input(
        device_of(&attention.key)?,
        &grad_keys,
        &mut grad_input,
        rows,
        1.0,
    )?;
    gpu.linear_backward_input(
        device_of(&attention.value)?,
        &grad_values,
        &mut grad_input,
        rows,
        1.0,
    )?;
    gpu.accumulate_weight_grad(
        device_of_mut(&mut attention.query)?,
        &grad_queries,
        &cache.attention_normed,
        rows,
    )?;
    gpu.accumulate_weight_grad(
        device_of_mut(&mut attention.key)?,
        &grad_keys,
        &cache.attention_normed,
        rows,
    )?;
    gpu.accumulate_weight_grad(
        device_of_mut(&mut attention.value)?,
        &grad_values,
        &cache.attention_normed,
        rows,
    )?;

    Ok(grad_input)
}

/// Accumulates the three projection gradients and adds `dL/dinput` into
/// `grad_input`, which the caller has already zeroed.
fn backward_swiglu(
    gpu: &Gpu<'_>,
    ffn: &mut SwiGlu,
    cache: &SwiGluCache,
    input: &CudaSlice<f32>,
    grad_output: &CudaSlice<f32>,
    grad_input: &mut CudaSlice<f32>,
    rows: usize,
) -> Result<(), NetworkError> {
    let width = ffn.d_ff();
    let mut grad_hidden = gpu.uninit(rows * width)?;
    gpu.linear_backward_input(
        device_of(&ffn.down)?,
        grad_output,
        &mut grad_hidden,
        rows,
        0.0,
    )?;
    gpu.accumulate_weight_grad(
        device_of_mut(&mut ffn.down)?,
        grad_output,
        &cache.hidden,
        rows,
    )?;

    let (grad_gate, grad_up) = gpu.swiglu_backward(cache, &grad_hidden, rows * width)?;

    // The gate projection *writes* `grad_input`; it is the first of the two,
    // and in the MoE layer the shared expert runs before anything scatters
    // into the same buffer. That is what lets the caller leave it uninitialized.
    gpu.linear_backward_input(device_of(&ffn.gate)?, &grad_gate, grad_input, rows, 0.0)?;
    gpu.accumulate_weight_grad(device_of_mut(&mut ffn.gate)?, &grad_gate, input, rows)?;
    gpu.linear_backward_input(device_of(&ffn.up)?, &grad_up, grad_input, rows, 1.0)?;
    gpu.accumulate_weight_grad(device_of_mut(&mut ffn.up)?, &grad_up, input, rows)?;
    Ok(())
}

/// MoE backward.
///
/// Everything is one launch or one GEMM per expert over the whole batch: the
/// gate gradients are a row-wise dot product, the expert gradients run on the
/// same grouped buffers the forward pass built, and the router's top-k
/// renormalization, softmax, load-balancing loss and z-loss are three kernels
/// over `[rows, num_experts]`.
#[allow(clippy::too_many_arguments)]
fn backward_moe(
    gpu: &Gpu<'_>,
    moe: &mut MoeLayer,
    cache: &MoeGpuCache,
    input: &CudaSlice<f32>,
    grad_output: &CudaSlice<f32>,
    grad_input: &mut CudaSlice<f32>,
    valid_tokens: usize,
    rows: usize,
) -> Result<(), NetworkError> {
    let experts = moe.config.num_experts;
    let top_k = moe.config.experts_per_token;
    let d_model = moe.d_model();
    let width = moe.config.d_ff;
    let routed = cache.routed;

    if let (Some(shared), Some(shared_cache)) = (moe.shared.as_mut(), &cache.shared) {
        backward_swiglu(
            gpu,
            shared,
            shared_cache,
            input,
            grad_output,
            grad_input,
            rows,
        )?;
    }

    let mut grad_gates = gpu.zeros(rows * top_k)?;
    if routed > 0 {
        unsafe {
            gpu.context
                .stream
                .launch_builder(&gpu.context.model.row_dot)
                .arg(&mut grad_gates)
                .arg(&cache.slot_of)
                .arg(grad_output)
                .arg(&cache.token_of)
                .arg(&cache.output)
                .arg(&(routed as i32))
                .arg(&(d_model as i32))
                .launch(warp_per_row_grid(routed))
                .map_err(cuda_err("gate gradient kernel"))?;
        }

        let mut grad_expert_output = gpu.uninit(routed * d_model)?;
        gpu.gather_scaled(
            &mut grad_expert_output,
            grad_output,
            &cache.token_of,
            &cache.gates,
            routed,
            d_model,
        )?;

        let mut grad_hidden = gpu.uninit(routed * width)?;
        for (expert, module) in moe.experts.iter_mut().enumerate() {
            let count = cache.counts[expert];
            if count == 0 {
                continue;
            }
            let offset = cache.offsets[expert];
            let upstream = grad_expert_output.slice(offset * d_model..);
            let mut grad = grad_hidden.slice_mut(offset * width..);
            gpu.linear_backward_input(device_of(&module.down)?, &upstream, &mut grad, count, 0.0)?;
            let hidden = cache.expert.hidden.slice(offset * width..);
            gpu.accumulate_weight_grad(
                device_of_mut(&mut module.down)?,
                &upstream,
                &hidden,
                count,
            )?;
        }

        let (grad_gate, grad_up) = gpu.swiglu_backward(&cache.expert, &grad_hidden, routed * width)?;

        let mut grad_expert_input = gpu.uninit(routed * d_model)?;
        for (expert, module) in moe.experts.iter_mut().enumerate() {
            let count = cache.counts[expert];
            if count == 0 {
                continue;
            }
            let offset = cache.offsets[expert];
            let rows_in = cache.input.slice(offset * d_model..);

            let upstream = grad_gate.slice(offset * width..);
            let mut grad = grad_expert_input.slice_mut(offset * d_model..);
            gpu.linear_backward_input(device_of(&module.gate)?, &upstream, &mut grad, count, 0.0)?;
            gpu.accumulate_weight_grad(
                device_of_mut(&mut module.gate)?,
                &upstream,
                &rows_in,
                count,
            )?;

            let upstream = grad_up.slice(offset * width..);
            let mut grad = grad_expert_input.slice_mut(offset * d_model..);
            gpu.linear_backward_input(device_of(&module.up)?, &upstream, &mut grad, count, 1.0)?;
            gpu.accumulate_weight_grad(
                device_of_mut(&mut module.up)?,
                &upstream,
                &rows_in,
                count,
            )?;
        }

        gpu.scatter(
            grad_input,
            &grad_expert_input,
            &cache.token_of,
            routed,
            d_model,
        )?;
    }

    // Gate gradients flow back through the top-k renormalization, then through
    // the softmax. The load-balancing loss adds a term on the probabilities;
    // the z-loss acts on the logits directly.
    let mut grad_probabilities = gpu.zeros(rows * experts)?;
    unsafe {
        gpu.context
            .stream
            .launch_builder(&gpu.context.model.grad_probabilities)
            .arg(&mut grad_probabilities)
            .arg(&grad_gates)
            .arg(&cache.probabilities)
            .arg(&cache.expert_of)
            .arg(&(rows as i32))
            .arg(&(experts as i32))
            .arg(&(top_k as i32))
            .launch(cfg(rows))
            .map_err(cuda_err("router gate gradient kernel"))?;
    }

    if moe.config.aux_loss_weight != 0.0 && valid_tokens > 0 {
        let slots = (valid_tokens * top_k) as f32;
        let loads: Vec<f32> = cache
            .counts
            .iter()
            .map(|&count| count as f32 / slots)
            .collect();
        let loads = gpu.upload(&loads)?;
        let scale = moe.config.aux_loss_weight * experts as f32 / valid_tokens as f32;
        unsafe {
            gpu.context
                .stream
                .launch_builder(&gpu.context.model.aux_grad)
                .arg(&mut grad_probabilities)
                .arg(&loads)
                .arg(&cache.expert_of)
                .arg(&(rows as i32))
                .arg(&(experts as i32))
                .arg(&(top_k as i32))
                .arg(&scale)
                .launch(cfg(rows * experts))
                .map_err(cuda_err("load-balancing gradient kernel"))?;
        }
    }

    let z_factor = if moe.config.router_z_loss_weight != 0.0 {
        2.0 * moe.config.router_z_loss_weight / valid_tokens.max(1) as f32
    } else {
        0.0
    };
    let mut grad_logits = gpu.zeros(rows * experts)?;
    unsafe {
        gpu.context
            .stream
            .launch_builder(&gpu.context.model.grad_logits)
            .arg(&mut grad_logits)
            .arg(&grad_probabilities)
            .arg(&cache.probabilities)
            .arg(&cache.log_sum_exp)
            .arg(&cache.expert_of)
            .arg(&(rows as i32))
            .arg(&(experts as i32))
            .arg(&(top_k as i32))
            .arg(&z_factor)
            .launch(cfg(rows))
            .map_err(cuda_err("router logit gradient kernel"))?;
    }

    gpu.linear_backward_input(
        device_of(&moe.router.projection)?,
        &grad_logits,
        grad_input,
        rows,
        1.0,
    )?;
    gpu.accumulate_weight_grad(
        device_of_mut(&mut moe.router.projection)?,
        &grad_logits,
        input,
        rows,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cuda_training::cuda_doctor;
    use crate::norm::RmsNorm;

    /// Same contract as the other CUDA tests: no device means the parity tests
    /// report success without running, a broken device is a failure.
    fn cuda_or_skip() -> Option<Arc<GpuContext>> {
        match cuda_doctor(0, 8192) {
            Ok(_) => Some(GpuContext::new(0).expect("the CUDA doctor passed")),
            Err(NetworkError::Cuda(message))
                if message.contains("NO_DEVICE") || message.contains("no CUDA-capable device") =>
            {
                None
            }
            Err(error) => panic!("CUDA is present but the CUDA doctor failed: {error}"),
        }
    }

    fn ramp(len: usize) -> Vec<f32> {
        ramp_from(len, 0)
    }

    /// A second, differently phased ramp, so an operand and its upstream
    /// gradient are not the same numbers.
    fn ramp_from(len: usize, offset: usize) -> Vec<f32> {
        (0..len)
            .map(|i| (((i + offset) * 37) % 23) as f32 / 11.0 - 1.0)
            .collect()
    }

    fn assert_close(label: &str, device: &[f32], host: &[f32], tolerance: f32) {
        assert_eq!(device.len(), host.len(), "{label}: length");
        for (index, (a, b)) in device.iter().zip(host).enumerate() {
            assert!(
                (a - b).abs() <= tolerance,
                "{label}[{index}]: {a} on the device vs {b} on the host"
            );
        }
    }

    #[test]
    fn the_rmsnorm_kernels_match_the_host_or_skip_without_device() {
        let Some(context) = cuda_or_skip() else {
            return;
        };
        let gpu = Gpu { context: &context };
        let (rows, cols) = (5, 8);

        let mut norm = RmsNorm::new(cols, 1e-6);
        norm.weight.value.data = ramp(cols).iter().map(|v| 1.0 + v * 0.25).collect();
        let input = Matrix::from_vec(rows, cols, ramp(rows * cols));
        let grad_output = Matrix::from_vec(rows, cols, ramp_from(rows * cols, 3));

        let weight = gpu.upload(&norm.weight.value.data).unwrap();
        let device_input = gpu.upload(&input.data).unwrap();
        let (output, inverse) = gpu
            .rmsnorm(&device_input, &weight, rows, cols, norm.eps)
            .unwrap();
        assert_close(
            "rmsnorm forward",
            &gpu.download(&output).unwrap(),
            &norm.forward(&input).data,
            1e-5,
        );

        let device_grad = gpu.upload(&grad_output.data).unwrap();
        let mut grad_weight = gpu.zeros(cols).unwrap();
        let grad_input = gpu
            .rmsnorm_backward(
                &device_input,
                &device_grad,
                &weight,
                &inverse,
                &mut grad_weight.slice_mut(..),
                rows,
                cols,
            )
            .unwrap();

        let host_grad_input = norm.backward(&input, &grad_output);
        assert_close(
            "rmsnorm grad_input",
            &gpu.download(&grad_input).unwrap(),
            &host_grad_input.data,
            1e-5,
        );
        assert_close(
            "rmsnorm grad_weight",
            &gpu.download(&grad_weight).unwrap(),
            &norm.weight.grad.data,
            1e-5,
        );
    }

    #[test]
    fn the_rope_kernel_matches_the_host_or_skips_without_device() {
        let Some(context) = cuda_or_skip() else {
            return;
        };
        let gpu = Gpu { context: &context };
        let (sequences, seq_len, heads, head_dim) = (2, 3, 2, 4);
        let rows = sequences * seq_len;

        let rope = Rope::new(head_dim, 16, 10_000.0).unwrap();
        let mut host = Matrix::from_vec(rows, heads * head_dim, ramp(rows * heads * head_dim));
        let mut device = gpu.upload(&host.data).unwrap();
        let tables = gpu.rope_tables(&rope).unwrap();

        gpu.rope(&mut device, &tables, rows, heads, head_dim, seq_len, 1.0)
            .unwrap();
        rope.apply_batched(&mut host, heads, seq_len).unwrap();
        assert_close("rope", &gpu.download(&device).unwrap(), &host.data, 1e-5);

        // The inverse is the same kernel with the opposite sign, which is what
        // the backward pass uses.
        gpu.rope(&mut device, &tables, rows, heads, head_dim, seq_len, -1.0)
            .unwrap();
        rope.apply_inverse_batched(&mut host, heads, seq_len).unwrap();
        assert_close(
            "rope inverse",
            &gpu.download(&device).unwrap(),
            &host.data,
            1e-5,
        );
    }

    #[test]
    fn the_causal_softmax_kernel_masks_and_normalizes_or_skips_without_device() {
        let Some(context) = cuda_or_skip() else {
            return;
        };
        let gpu = Gpu { context: &context };
        let (sequences, seq_len) = (2, 4);
        let rows = sequences * seq_len;

        let scores = ramp(rows * seq_len);
        let mut device = gpu.upload(&scores).unwrap();
        gpu.causal_softmax(&mut device, rows, seq_len).unwrap();
        let probabilities = gpu.download(&device).unwrap();

        for row in 0..rows {
            let visible = row % seq_len + 1;
            let slice = &probabilities[row * seq_len..(row + 1) * seq_len];

            let mut expected = vec![0.0f32; seq_len];
            let source = &scores[row * seq_len..row * seq_len + visible];
            let max = source.iter().copied().fold(f32::NEG_INFINITY, f32::max);
            let total: f32 = source.iter().map(|v| (v - max).exp()).sum();
            for (slot, &value) in expected.iter_mut().zip(source) {
                *slot = (value - max).exp() / total;
            }

            assert_close(&format!("causal softmax row {row}"), slice, &expected, 1e-6);
            // Everything past the diagonal is masked, not merely small.
            assert!(slice[visible..].iter().all(|&p| p == 0.0));
        }

        // The backward pass of a softmax whose upstream gradient is constant is
        // zero, which is a check the masking cannot pass by accident.
        let mut grad = gpu.upload(&vec![1.0; rows * seq_len]).unwrap();
        gpu.causal_softmax_backward(&mut grad, &device, rows, seq_len)
            .unwrap();
        assert_close(
            "causal softmax backward",
            &gpu.download(&grad).unwrap(),
            &vec![0.0; rows * seq_len],
            1e-6,
        );
    }

    #[test]
    fn the_swiglu_kernel_matches_the_host_formula_or_skips_without_device() {
        let Some(context) = cuda_or_skip() else {
            return;
        };
        let gpu = Gpu { context: &context };
        let len = 16;

        let gate = ramp(len);
        let up = ramp_from(len, 5);
        let cache = SwiGluCache {
            gate: gpu.upload(&gate).unwrap(),
            up: gpu.upload(&up).unwrap(),
            hidden: gpu.zeros(len).unwrap(),
        };
        let hidden = gpu.swiglu(&cache.gate, &cache.up, len).unwrap();

        let silu = |x: f32| x / (1.0 + (-x).exp());
        let expected: Vec<f32> = gate.iter().zip(&up).map(|(&g, &u)| silu(g) * u).collect();
        assert_close("swiglu", &gpu.download(&hidden).unwrap(), &expected, 1e-6);

        let grad_hidden = gpu.upload(&vec![1.0; len]).unwrap();
        let (grad_gate, grad_up) = gpu.swiglu_backward(&cache, &grad_hidden, len).unwrap();

        // Compared against a central difference of the same formula.
        let epsilon = 1e-3;
        let numeric: Vec<f32> = gate
            .iter()
            .zip(&up)
            .map(|(&g, &u)| (silu(g + epsilon) * u - silu(g - epsilon) * u) / (2.0 * epsilon))
            .collect();
        assert_close(
            "swiglu grad_gate",
            &gpu.download(&grad_gate).unwrap(),
            &numeric,
            2e-3,
        );
        assert_close(
            "swiglu grad_up",
            &gpu.download(&grad_up).unwrap(),
            &gate.iter().map(|&g| silu(g)).collect::<Vec<_>>(),
            1e-6,
        );
    }

    #[test]
    fn the_router_kernels_select_and_renormalize_or_skip_without_device() {
        let Some(context) = cuda_or_skip() else {
            return;
        };
        let gpu = Gpu { context: &context };
        let (rows, experts, top_k) = (4, 5, 2);

        let logits = ramp(rows * experts);
        let device_logits = gpu.upload(&logits).unwrap();
        let mut probabilities = gpu.zeros(rows * experts).unwrap();
        let mut log_sum_exp = gpu.zeros(rows).unwrap();
        unsafe {
            gpu.context
                .stream
                .launch_builder(&gpu.context.model.softmax_lse)
                .arg(&mut probabilities)
                .arg(&mut log_sum_exp)
                .arg(&device_logits)
                .arg(&(rows as i32))
                .arg(&(experts as i32))
                .launch(cfg(rows))
                .unwrap();
        }

        // The last row is padding, which must be routed nowhere.
        let flags: Vec<i32> = (0..rows).map(|row| i32::from(row + 1 < rows)).collect();
        let valid = gpu.upload_flags(&flags).unwrap();
        let mut expert_of = gpu.context.stream.alloc_zeros::<i32>(rows * top_k).unwrap();
        let mut gate_of = gpu.zeros(rows * top_k).unwrap();
        unsafe {
            gpu.context
                .stream
                .launch_builder(&gpu.context.model.topk_gate)
                .arg(&mut expert_of)
                .arg(&mut gate_of)
                .arg(&probabilities)
                .arg(&valid)
                .arg(&(rows as i32))
                .arg(&(experts as i32))
                .arg(&(top_k as i32))
                .launch(cfg(rows))
                .unwrap();
        }

        let probabilities = gpu.download(&probabilities).unwrap();
        let log_sum_exp = gpu.download(&log_sum_exp).unwrap();
        let assigned = gpu.download_signed(&expert_of).unwrap();
        let gates = gpu.download(&gate_of).unwrap();

        for row in 0..rows {
            let slice = &probabilities[row * experts..(row + 1) * experts];
            let sum: f32 = slice.iter().sum();
            assert!((sum - 1.0).abs() < 1e-5, "row {row} softmax sums to {sum}");

            let source = &logits[row * experts..(row + 1) * experts];
            let max = source.iter().copied().fold(f32::NEG_INFINITY, f32::max);
            let expected = max + source.iter().map(|v| (v - max).exp()).sum::<f32>().ln();
            assert!((log_sum_exp[row] - expected).abs() < 1e-5);

            let selected = &assigned[row * top_k..(row + 1) * top_k];
            if row + 1 == rows {
                assert!(selected.iter().all(|&expert| expert < 0), "padding routed");
                assert!(gates[row * top_k..(row + 1) * top_k].iter().all(|&g| g == 0.0));
                continue;
            }

            // The selected experts are the top-k, and their gates renormalize.
            let mut order: Vec<usize> = (0..experts).collect();
            order.sort_by(|&a, &b| slice[b].total_cmp(&slice[a]));
            assert_eq!(
                selected.iter().map(|&e| e as usize).collect::<Vec<_>>(),
                order[..top_k],
                "row {row} top-{top_k}"
            );
            let total: f32 = selected.iter().map(|&e| slice[e as usize]).sum();
            for (rank, &expert) in selected.iter().enumerate() {
                let expected = slice[expert as usize] / total;
                assert!((gates[row * top_k + rank] - expected).abs() < 1e-6);
            }
        }
    }
}