cortiq-engine 0.9.16

Portable inference runtime for the CMF model format, with no ML framework underneath: runs on CPU, and on GPU (Vulkan / Metal / DX12) with the `gpu` feature; tokenizer, chat templates and dynamic per-skill weight overlay.
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
//! Inkling-2-Mini on CUDA, beside the hybrid arm whose matvecs and routed
//! experts it borrows (`inkling` has the semantics).
//!
//! Every matrix goes through the arm's tensor-core matvec in its codec (q4tp
//! or q8_2f); the routed experts are the arm's slot launches (`hy_moe_router`,
//! `hy_moe_select`, a gate/up pair whose epilogue is Inkling's softcapped
//! SwiGLU, the down launch, `hy_moe_combine`); the stages between them are
//! `inkling.cu`. A decode or verify call takes at most 16 rows (`NMAX`); its
//! launches are recorded once per row count and replayed (CUDA graphs). A
//! prompt goes up to `CMF_INKLING_ROWS` (512) rows a call on the prompt path:
//! every weight expanded to f16 and multiplied by cuBLAS, the routed experts
//! grouped by expert (the hybrid prompt path's `hy_moe_group`), so a chunk reads
//! each expert once instead of once every 16 rows. Every one of the 48 layer
//! applications keeps its own keys and values (f16; a local layer's in a ring of
//! its window and a call's rows, a full layer's for the context cap) and its four
//! convolution rings.

use super::*;
use crate::inkling::{Cfg, Globals, Layer};
use std::collections::HashMap;
use std::sync::Mutex;

const SRC: &str = include_str!("../inkling.cu");
/// Block states a row holds (the embedding and the closed blocks).
const MAXB: usize = 4;

/// Keys a tile of the decode attention takes (`AT` in `inkling.cu`).
const ATILE: usize = 256;

/// Bytes of a prompt chunk's attention scores (`attn_gemm`): the rows of a
/// chunk are as many as fit.
const ATT_SCORES: usize = 128 << 20;

/// `CMF_INKLING_MOE_MMA=0`: a prompt call's experts through the hybrid arm's
/// grouped tensor-core launches (32 rows a job, two bf16 planes) instead of
/// `ink_moe_mma` (64 rows a job, f16 rows, 128 output rows a block).
fn moe_mma_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_MOE_MMA").as_deref() != Ok("0"))
}

/// `CMF_INKLING_MOE_MMA2=0`: `ink_moe_mma` (every warp loads the job's rows
/// itself) instead of `ink_moe_mma2` (the rows staged once a block through a
/// cp.async pipeline; L4, a 512-row call's experts 174 → 135 ms, the same sums).
fn mma2_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_MOE_MMA2").as_deref() != Ok("0"))
}

/// Output tiles of 16 rows an `ink_moe_mma` block takes (4 warps × `MT`).
const MMA_TILES: usize = 8;

/// `CMF_INKLING_ATTN_GEMM=0`: a prompt call's attention a block a head and row
/// (`ink_attn`) instead of the cuBLAS products.
fn attn_gemm_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_ATTN_GEMM").as_deref() != Ok("0"))
}

/// `CMF_INKLING_PERSIST=1`: a decode row's expert matvecs as a resident grid
/// taking the places in turn instead of a block a place (G4: 179.6 against
/// 190.8 tok/s — the many blocks' loads in flight win over the partial wave).
fn persist_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_PERSIST").as_deref() == Ok("1"))
}

/// `CMF_INKLING_ROWMAP=0`: a prompt call's expert input as a gathered f16
/// copy of every pick (`ink_gather16`) instead of the rows read in place.
fn rowmap_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_ROWMAP").as_deref() != Ok("0"))
}

/// `CMF_INKLING_GATE2=0`: a prompt call's message gates through the normed copy
/// of their inputs (`ink_gate_norm`) and two product GEMMs.
fn gate2_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_GATE2").as_deref() != Ok("0"))
}

/// `ink_mix2`'s block: two float4s of the row a thread (its `MIX_TPB`).
fn mix_tpb(hidden: usize) -> u32 {
    ((hidden / 4).div_ceil(2).div_ceil(32) * 32) as u32
}

/// `CMF_INKLING_QRKV2=1`: the decode sinks and per-token taps inside the qr+kv
/// launch (`ink_qrkv2`) instead of `ink_fmv3` before it (G4: slower, the dots
/// serialize in the query and key blocks).
fn qrkv2_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_QRKV2").as_deref() == Ok("1"))
}

/// `CMF_INKLING_POSTMIX=1`: a decode row's attention post and MoE mix in one
/// block (`ink_post_mix`) instead of `ink_post` (nine blocks) and `ink_mix2`.
fn postmix_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_POSTMIX").as_deref() == Ok("1"))
}

/// `CMF_INKLING_FLASH=0`: a prompt call's attention through the cuBLAS score
/// products (`attn_gemm`) instead of `ink_attn_flash`.
fn flash_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_FLASH").as_deref() != Ok("0"))
}

/// `CMF_INKLING_SPLIT=0`: a decode call's attention a block a head and row
/// (`ink_attn`) instead of a block a tile of keys.
fn split_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_SPLIT").as_deref() != Ok("0"))
}

/// Rows of a prompt call (`CMF_INKLING_ROWS`; by the card's size 4096 at 40
/// GB and more, 2048 at 24 GB, else 1024 — RTX PRO 6000 with flash attention,
/// prompt tok/s 1024 / 2048 / 4096 rows: 2k 11.4K / 12.4K / 12.4K, 16k 10.2K /
/// 11.5K / 12.1K; 16 reads a prompt on the decode path, 16 rows a call).
fn bmax() -> usize {
    static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *N.get_or_init(|| {
        let by_card = match super::super::card_total() >> 30 {
            g if g >= 40 => 4096,
            g if g >= 24 => 2048,
            _ => 1024,
        };
        std::env::var("CMF_INKLING_ROWS").ok().and_then(|v| v.parse::<usize>().ok()).map_or(by_card, |n| n.clamp(NMAX, 4096))
    })
}

struct Fx {
    mix: cs::CUfunction,
    mix2: cs::CUfunction,
    rms3: cs::CUfunction,
    gd3: cs::CUfunction,
    go3: cs::CUfunction,
    merge_g: cs::CUfunction,
    post_mx: cs::CUfunction,
    qrkv2: cs::CUfunction,
    qrkv: cs::CUfunction,
    fmv3: cs::CUfunction,
    post_mix: cs::CUfunction,
    gate_rr: cs::CUfunction,
    rms_h: cs::CUfunction,
    ogate_h: cs::CUfunction,
    gate_d: cs::CUfunction,
    gate_mix2: cs::CUfunction,
    rms: cs::CUfunction,
    gate_down: cs::CUfunction,
    gate_out: cs::CUfunction,
    fmv: cs::CUfunction,
    qr: cs::CUfunction,
    kv: cs::CUfunction,
    attn: cs::CUfunction,
    ogate: cs::CUfunction,
    post: cs::CUfunction,
    softcap: cs::CUfunction,
    attn_split: cs::CUfunction,
    attn_merge: cs::CUfunction,
    h16: cs::CUfunction,
    f16: cs::CUfunction,
    attn_soft: cs::CUfunction,
    attn_flash: cs::CUfunction,
    gather16: cs::CUfunction,
    moe_mma: cs::CUfunction,
    moe_mma2: cs::CUfunction,
    ring_snap: cs::CUfunction,
    ring_back: cs::CUfunction,
    ds_mix: cs::CUfunction,
    ds_ctx: cs::CUfunction,
    ds_qk: cs::CUfunction,
    ds_attn: cs::CUfunction,
    planes: cs::CUfunction,
    ds_markov: cs::CUfunction,
    ds_pick: cs::CUfunction,
    argmax_rows: cs::CUfunction,
    gate_norm: cs::CUfunction,
    gate_mix: cs::CUfunction,
    kv_rows: cs::CUfunction,
    ring_rows: cs::CUfunction,
    post_rows: cs::CUfunction,
}

/// A loop layer's message gate: down `[R][2H]`, forget and gain `[H][R]`.
struct GateD {
    down: Buf,
    forget: Buf,
    gain: Buf,
    /// F's rows then G's ([2H][R]): a prompt call's two products in one GEMM
    fg: Buf,
}

/// A device address inside a buffer another field owns.
#[derive(Clone, Copy)]
struct DPtr {
    ptr: u64,
}

struct LayerD {
    sliding: bool,
    boundary: bool,
    /// The attention input's queries (1 or 3); None on layer 0.
    aq: Option<(Buf, usize)>,
    mq: Buf,
    norms: [Buf; 3],
    post_norm: Buf,
    /// q, gate, rel from the query input's planes; k; v; o.
    qset: MmaSet,
    /// q, gate, rel, k and v together, for a local layer's first pass (one input row).
    qkv: Option<MmaSet>,
    /// q, gate, rel, k, v in one launch from three input planes (k's and v's
    /// rows at planes 1 and 2: `Dev::xpb`), for the calls whose inputs differ
    qkv3: MmaSet,
    kset: MmaSet,
    vset: MmaSet,
    oset: MmaSet,
    sink: Buf,
    q_scale: Buf,
    rel_scale: Buf,
    rel_table: Buf,
    /// The table as `ink_attn_flash` reads its bands: [E][hi, lo][DR] bf16
    rel_tb: Buf,
    extent: usize,
    tk: Buf,
    tv: Buf,
    dk: Option<Buf>,
    dv: Option<Buf>,
    tpa: Buf,
    tpm: Buf,
    router: Buf,
    bias: Buf,
    e: usize,
    inter: usize,
    gu_t: Buf,
    dn_t: Buf,
    kd: (Option<usize>, Option<usize>),
    bpj_gu: u32,
    bpj_dn: u32,
    gates: Option<[GateD; 4]>,
    /// q, gate, rel, k, v, o for the prompt path's GEMMs.
    dense: [Arc<DevMat>; 6],
    _mats: Vec<Arc<DevMat>>,
}

/// One application's caches: K and V (f16 `[row][NKV·HD]`, `ring` > 0 a ring
/// of that many rows), the k, v, post-attention and post-MoE rings.
struct SlotD {
    k: Buf,
    v: Buf,
    ring: usize,
    rings: [Buf; 4],
    /// A decode call's input rows of each ring (`NMAX` rows) and the rings'
    /// snapshot: a draft verify rolls them back to its accepted prefix.
    hist: [Buf; 4],
    snap: [Buf; 4],
}

/// `struct RingRef` of inkling.cu.
#[repr(C)]
#[derive(Clone, Copy)]
struct RingRef {
    live: u64,
    snap: u64,
    hist: u64,
    width: i32,
    pad: i32,
}

/// One dense layer of the DSpark drafter on the card.
struct DLayerD {
    qkv: MmaSet,
    kctx: MmaSet,
    vctx: MmaSet,
    kctx_m: Arc<DevMat>,
    vctx_m: Arc<DevMat>,
    o: MmaSet,
    gu: MmaSet,
    down: MmaSet,
    in_norm: Buf,
    post_norm: Buf,
    q_norm: Buf,
    k_norm: Buf,
    kc_norm: Buf,
    /// The layer's keys and values (f16 `[cell][NKV·HD]`; a sliding layer's a
    /// ring of its window and more).
    ck: Buf,
    cv: Buf,
    cap: usize,
    ring: bool,
    _mats: Vec<Arc<DevMat>>,
}

/// The DSpark drafter on the card: its layers and caches, the taps the target
/// leaves in every call, the block's rows and the Markov head.
struct DraftD {
    layers: Vec<DLayerD>,
    /// Application indices whose input rows are tapped (the last target, the
    /// final normed state, is every call's).
    taps: Vec<usize>,
    /// `[targets][rows][H]` f32.
    tap: Buf,
    alpha: Buf,
    /// The mixes' norms `[mixes][H]`.
    norms: Buf,
    /// The block's final norm.
    fnorm: Buf,
    mixp: [Buf; 2],
    mixh: Buf,
    ckb: Buf,
    cvb: Buf,
    /// The Markov head's context of recent positions `[FR][H]`.
    fr: Buf,
    masks: Buf,
    x: Buf,
    xp: [Buf; 2],
    dq: Buf,
    dk: Buf,
    dv: Buf,
    att: Buf,
    ap: [Buf; 2],
    gp: [Buf; 2],
    hf: Buf,
    hp: [Buf; 2],
    dcr: Buf,
    head: MmaSet,
    dlog: Buf,
    rnn_w: Buf,
    rnn_b: Buf,
    ch: Buf,
    cf: Buf,
    state: Buf,
    prev: Buf,
    ids: Buf,
    w1: Buf,
    folds: Vec<MmaSet>,
    fold_b: Buf,
    latp: [Buf; 2],
    block: usize,
    rank: usize,
    window: usize,
    theta: f32,
    eps: f32,
    inter: usize,
    _mats: Vec<Arc<DevMat>>,
}

/// Positions whose Markov context the ring keeps.
const FR: usize = 16;

/// The prompt path's scratch: the f16 inputs of the weight GEMMs, the band a
/// weight expands into, the grouped experts' entries, planes and jobs.
struct Big {
    x16: [Buf; 3],
    o16: Buf,
    wd: Buf,
    wd_elems: usize,
    lg: Buf,
    pidx: Buf,
    pwt: Buf,
    pos: Buf,
    src: Buf,
    xg: [Buf; 2],
    qq: [Buf; 2],
    ys: Buf,
    gu_a: Buf,
    dn_a: Buf,
    /// A message gate's normed halves `[rows][2H]` and its F and G products
    /// `[rows][H]` (`gate_big`).
    gxn: Buf,
    gtf: Buf,
    gtg: Buf,
    /// The attention through cuBLAS (`attn_gemm`): the queries as f16, the
    /// scores of a chunk of rows `[NH][rows][keys]` f32 and their softmax f16.
    q16: Buf,
    sc: Buf,
    pr: Buf,
    /// q4tp dense weights kept expanded to f16 between prompt calls (by the
    /// matrix's body address), while `wf16_left` bytes of the budget remain
    /// (`CMF_INKLING_WF16_MB`, default the card's free memory past 4 GB, at
    /// most 4 GB)
    wf16: std::cell::RefCell<HashMap<u64, Buf>>,
    wf16_left: std::cell::Cell<usize>,
}

struct Dev {
    fx: Fx,
    hfx: Arc<HFuncs>,
    /// Rows the row buffers hold: a prompt call's cap (`NMAX` without the
    /// prompt path).
    rows: usize,
    big: Option<Big>,
    /// A prompt call's first position (the host's copy of `cr[0]`).
    big_pos0: std::cell::Cell<usize>,
    /// Every application's four rings as `RingRef`s (`ink_ring_snap` / `back`).
    rings_tab: Buf,
    nrings: usize,
    draft: Option<DraftD>,
    layers: Vec<LayerD>,
    slots: Vec<SlotD>,
    head: MmaSet,
    msg_q: Buf,
    final_q: Buf,
    final_norm: Buf,
    /// The running sums (two, alternating), the block states, the prelude's
    /// output, the previous pass's blocks and output.
    h: [Buf; 2],
    blk: Buf,
    pre_h: Buf,
    bank: Buf,
    bank_out: Buf,
    msg: Buf,
    in3: Buf,
    gin: Buf,
    gd: Buf,
    x: [Buf; 3],
    /// the three input rows' planes, views of `xpb` (plane j at j·rows·hidden)
    xp: [[DPtr; 2]; 3],
    xpb: [Buf; 2],
    yq: Buf,
    yg: Buf,
    yr: Buf,
    yk: Buf,
    yv: Buf,
    sk: Buf,
    /// The key tiles' softmax partials of a decode call's attention
    /// (`ink_attn_split`): `[NMAX][NH][tiles of the cap][HD + 2]`.
    part: Buf,
    dkb: Buf,
    dvb: Buf,
    att: Buf,
    po: [Buf; 2],
    ya: Buf,
    r: Buf,
    m: Buf,
    mg: Buf,
    xm: Buf,
    pm: [Buf; 2],
    logits_e: Buf,
    sg: Buf,
    wsel: Buf,
    gu_a: Buf,
    dn_a: Buf,
    qq: [Buf; 2],
    dns: Buf,
    y: Buf,
    fin: Buf,
    pf: [Buf; 2],
    logits: Buf,
    cr: Buf,
    /// A verify call's greedy pick of each row (`NMAX` ids).
    pick: Buf,
    /// `hy_moe_route1`'s finished-block counter (the last block re-arms it)
    rcnt: Buf,
    smax: usize,
    /// Recorded calls by (rows, logits rows) and the pointers they hold.
    graphs: HashMap<(usize, usize), GraphRec>,
    /// Positions the full slots hold.
    cap: usize,
}
unsafe impl Send for Dev {}

static DEVICES: Mutex<Option<HashMap<u64, Dev>>> = Mutex::new(None);

/// Stages of `CMF_INKLING_PROF=1` (each closed by a stream sync; the calls
/// then run without graphs).
const STAGES: [&str; 14] = ["mix", "msg+gates", "norms", "proj", "qr+kv", "attn", "o", "post", "moe in", "moe", "head", "moe route", "moe gu", "moe down"];
static STAGE_NS: [std::sync::atomic::AtomicU64; 14] = [const { std::sync::atomic::AtomicU64::new(0) }; 14];
static PROF_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// A prompt call's stages, apart from the decode calls' (`CMF_INKLING_PROF=1`).
static BIG_NS: [std::sync::atomic::AtomicU64; 14] = [const { std::sync::atomic::AtomicU64::new(0) }; 14];
static IN_BIG: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

fn prof() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_PROF").as_deref() == Ok("1"))
}

/// Closes stage `i` when profiling: syncs and adds its time.
fn st(c: &Ctx, i: usize, t: &mut std::time::Instant) -> Res<()> {
    if prof() {
        c.sync()?;
        let to = if IN_BIG.load(Ordering::Relaxed) { &BIG_NS } else { &STAGE_NS };
        to[i].fetch_add(t.elapsed().as_nanos() as u64, Ordering::Relaxed);
        *t = std::time::Instant::now();
    }
    Ok(())
}

/// The stage table of the decode calls so far (`CMF_INKLING_PROF=1`).
fn prof_report() {
    let calls = PROF_CALLS.load(Ordering::Relaxed).max(1);
    let row: Vec<String> = STAGES.iter().zip(&STAGE_NS).map(|(n, v)| format!("{n} {:.2}", v.load(Ordering::Relaxed) as f64 / 1e6 / calls as f64)).collect();
    tracing::info!("inkling2_loop CUDA ms a call ({calls} calls): {}", row.join(", "));
}

/// One prompt call's stage table (`CMF_INKLING_PROF=1`), then cleared.
fn prof_report_big(n: usize) {
    let tot: u64 = BIG_NS.iter().map(|v| v.load(Ordering::Relaxed)).sum();
    let row: Vec<String> = STAGES.iter().zip(&BIG_NS).filter(|(_, v)| v.load(Ordering::Relaxed) > 0).map(|(name, v)| format!("{name} {:.1}", v.swap(0, Ordering::Relaxed) as f64 / 1e6)).collect();
    tracing::info!("inkling2_loop CUDA prompt call of {n} rows, {:.1} ms ({:.0} rows/s): {}", tot as f64 / 1e6, n as f64 / (tot as f64 / 1e9), row.join(", "));
}
static DECLINED: Mutex<Vec<u64>> = Mutex::new(Vec::new());

fn gw_of(t: &crate::qtensor::QTensor) -> Option<(Arc<CmfModel>, GraphW<'static>)> {
    let (model, idx, kind, _) = t.graph_weight()?;
    // q4tp (6) and q8_2f (7): the codecs the arm's matvecs read from the file
    if !matches!(kind, 6 | 7) {
        return None;
    }
    Some((model.clone(), GraphW { idx, kind, row_scale: &[], data: &[], prism: crate::gpu::GraphPrismOp::None, affine: false }))
}

fn mat(c: &Ctx, st: &mut State, t: &crate::qtensor::QTensor) -> Res<Arc<DevMat>> {
    let (model, gw) = gw_of(t).ok_or("an Inkling matrix outside q4tp / q8_2f")?;
    hmat(c, st, &model, &gw, t.rows(), t.cols())
}

/// The stack fits the arm: its geometry and every matrix's codec.
pub(crate) fn admits(g: &Globals, layers: &[Layer], cfg: &Cfg) -> bool {
    let ok_geom = cfg.hd == 128 && cfg.nh % cfg.nkv == 0 && cfg.dim % 256 == 0 && cfg.d_rel <= 32 && cfg.window <= 1024 && cfg.rel_extent <= 1024 && cfg.block > 0 && cfg.layers / cfg.block <= MAXB;
    let q = |t: &crate::qtensor::QTensor| gw_of(t).is_some();
    ok_geom
        && q(&g.lm_head)
        && layers.iter().all(|l| {
            let a = &l.attn;
            q(&a.q) && q(&a.k) && q(&a.v) && q(&a.o) && q(&a.gate) && q(&a.rel) && l.moe.experts.iter().all(|[x, y, z]| q(x) && q(y) && q(z)) && a.k_conv.kernel == 4 && a.v_conv.kernel == 4
        })
}

/// The relative table [DR][E] f32 as [E][2][DR] bf16: each distance's row
/// split into a high and a low part (round to nearest even, as `f2bf`).
fn rel_band(t: &[f32], dr: usize) -> Vec<u16> {
    let bf = |x: f32| -> u16 {
        let b = x.to_bits();
        ((b.wrapping_add(0x7FFF + ((b >> 16) & 1))) >> 16) as u16
    };
    let e = t.len() / dr.max(1);
    let mut out = vec![0u16; e * 2 * dr];
    for d in 0..e {
        for j in 0..dr {
            let x = t[j * e + d];
            let hi = bf(x);
            let lo = bf(x - f32::from_bits((hi as u32) << 16));
            out[(d * 2) * dr + j] = hi;
            out[(d * 2 + 1) * dr + j] = lo;
        }
    }
    out
}

fn f32b(v: &[f32]) -> Res<Buf> {
    Buf::from_slice(v)
}

fn job(m: &DevMat, rows: usize, kind: i32) -> HyJob {
    HyJob { w: m.w.ptr, aux0: m.aux0(), aux1: m.aux1(), y: 0, res: 0, rows: rows as i32, kind, blk0: 0, ystride: 0, xoff: 0, nr: 0, lim: 0.0, pad: [0; 3] }
}

/// Card bytes of one Inkling matrix in its codec's card layout (q4tp planes,
/// q8_2f int8 tiles with both column fields): what `mat` / `hmat_pair` carve
/// out of a build's arena. Other matrices take no arena room.
fn dev_bytes(t: &crate::qtensor::QTensor, rows: usize, cols: usize) -> usize {
    match gw_of(t) {
        Some((_, gw)) if gw.kind == 7 => i8_layout(rows, cols, 2).2,
        Some(_) => planes_bytes(rows, cols),
        None => 0,
    }
}

/// Layers as ranges for a log line: `0-5, 18-23`.
fn ranges(ls: &[usize]) -> String {
    let mut out: Vec<String> = Vec::new();
    let mut i = 0;
    while i < ls.len() {
        let mut j = i;
        while j + 1 < ls.len() && ls[j + 1] == ls[j] + 1 {
            j += 1;
        }
        out.push(if j > i { format!("{}-{}", ls[i], ls[j]) } else { ls[i].to_string() });
        i = j + 1;
    }
    out.join(", ")
}

/// Card bytes `build` takes after the weights beside the K/V: the row planes
/// of a call (`Dev`), the slots' rings, and the prompt path's planes and
/// attention scores (`Big`, when `big_on`), sized as `build` sizes them.
fn rows_bytes(cfg: &Cfg, rows: usize, e: usize, k: usize, inter: usize, big_on: bool) -> usize {
    let (h, nh, nkv, hd) = (cfg.dim, cfg.nh, cfg.nkv, cfg.hd);
    let (qs, kvs, r) = (nh * hd, nkv * hd, rows);
    let f4 = |n: usize| n * 4;
    let h2 = |n: usize| n * 2 + 64;
    let smax = (NMAX * k).min(e);
    // f32 planes of `rows x hidden`: h 2, blk and bank MAXB each, pre_h,
    // bank_out, msg 4, in3 3, gin 4, x 3, r, m, mg, xm, y, fin
    let planes = f4(r * h) * (2 + 2 * MAXB + 2 + 4 + 3 + 4 + 3 + 6);
    // f16 planes: xpb 2 x 3, pm 2, pf 2; the attention's and the router's
    let half = h2(3 * r * h) * 2 + h2(r * h) * 4 + f4(r * qs) + h2(r * qs) * 2 + f4(r * nh) + f4(r * nkv * 4) * 2 + f4(r * e) + f4(r * 256);
    let part = f4(NMAX * nh * cfg.max_seq.div_ceil(ATILE) * (hd + 2));
    let experts = h2(smax * NMAX * h) * 2 + f4(smax * NMAX * h) + f4(NMAX * smax);
    let rings = cfg.slots() * (2 * f4(6 * kvs + 6 * h) + f4(2 * NMAX * (kvs + h)));
    let big = if big_on {
        let nk = r * k;
        h2(r * h) * 3 + h2(r * qs) * 2 + wd_cap() + f4(r * e) + f4(nk) * 4 + h2(nk * h) * 2 + h2(nk * inter) * 2 + f4(nk * h) + f4(r * h) * 5 + ATT_SCORES + ATT_SCORES / 2
    } else {
        0
    };
    planes + half + part + experts + rings + big
}

/// The stack's place when the card has no room for all of it (the 15 GB
/// Inkling-2-Mini file on a 12 or 16 GB card): the dense part, the head and
/// the drafter on the card, and of the routed experts the ones the stack reads
/// most — a loop layer is applied `passes` times a token, so a byte of its
/// experts is read that many times as often as one of a layer outside the
/// loop. What is left lives in mapped host memory, where the same kernels read
/// it over the bus; the hybrid arm's placement spills in build order instead,
/// which on this stack would push loop layers out before the layers before it.
///
/// Opens the build's arenas (the card's and the host's) and returns each
/// layer's budget for experts on the card in bytes (`ARENA_EXP_DEV` while that
/// layer builds), or `None` when every weight fits the card or the overflow is
/// off (`CMF_HYB_HOST_EXPERTS=0`): the build then runs as it did before.
///
/// The card keeps, past the weights, the K/V of every application, the row
/// planes the build takes after them (`rows_bytes`) and a GiB for cuBLAS, the
/// call graphs and what the first calls allocate: on an RTX 3060 (12 GB) the
/// plain eighth of the card (1.5 GiB) beside the K/V of 16 384 positions left
/// 0.45 GB, and a 4096-token prompt's graph failed to instantiate. The knobs
/// are the hybrid arm's, so any card places the same way: `CMF_GPU_VRAM_MB`
/// (a smaller card, for a check on a big one), `CMF_HYB_RESERVE_MB` (the room
/// past the K/V instead of the planes and the GiB), `CMF_MAX_SEQ` (the K/V).
#[allow(clippy::too_many_arguments)]
fn place_experts(st: &mut State, g: &Globals, layers: &[Layer], cfg: &Cfg, rows: usize, e: usize, k: usize, inter: usize, big_on: bool) -> Res<Option<Vec<usize>>> {
    if std::env::var("CMF_HYB_HOST_EXPERTS").as_deref() == Ok("0") {
        return Ok(None);
    }
    let uid = g.model.uid();
    let hidden = cfg.dim;
    // a matrix the state holds already (another build of this model) takes no room
    let one = |st: &State, t: &crate::qtensor::QTensor| match gw_of(t) {
        Some((_, w)) if st.hyb.mats.contains_key(&(uid, w.idx)) => 0,
        _ => dev_bytes(t, t.rows(), t.cols()),
    };
    // the dense part: the attention's six matrices a layer, the head, the drafter
    let mut dense = one(st, &g.lm_head);
    for l in layers {
        let a = &l.attn;
        dense += [&a.q, &a.gate, &a.rel, &a.k, &a.v, &a.o].into_iter().map(|t| one(st, t)).sum::<usize>();
    }
    if let Some(dr) = &g.draft {
        for d in &dr.layers {
            dense += [&d.q, &d.k, &d.v, &d.o, &d.k_ctx, &d.v_ctx, &d.gate, &d.up, &d.down].into_iter().map(|t| one(st, t)).sum::<usize>();
        }
        dense += one(st, &dr.fold);
    }
    // a layer's routed experts: each one's gate/up pair and its down matrix
    let exp: Vec<usize> = layers
        .iter()
        .map(|l| {
            l.moe
                .experts
                .iter()
                .map(|[eg, eu, ed]| {
                    let held = matches!((gw_of(eg), gw_of(eu)), (Some((_, a)), Some((_, b))) if st.hyb.pairs.contains_key(&(uid, a.idx, b.idx)));
                    (if held { 0 } else { dev_bytes(eg, 2 * inter, hidden) }) + one(st, ed)
                })
                .sum()
        })
        .collect();
    let need_exp: usize = exp.iter().sum();
    // the card past the weights: the K/V of every application (a sliding slot
    // its window and a call's rows, a full slot the context cap), the row
    // planes and a GiB for cuBLAS and the graphs (or `CMF_HYB_RESERVE_MB`)
    let kvs = cfg.nkv * cfg.hd;
    let kv: usize = cfg.plan().iter().map(|&(li, _)| 2 * ((if layers[li].sliding { cfg.window + rows } else { cfg.max_seq }) * kvs * 2 + 64)).sum();
    let past = match std::env::var("CMF_HYB_RESERVE_MB").ok().and_then(|v| v.parse::<usize>().ok()) {
        Some(mb) => mb << 20,
        None => rows_bytes(cfg, rows, e, k, inter, big_on) + (1 << 30),
    };
    let room = super::super::card_free().saturating_sub(kv + past);
    if dense + need_exp <= room {
        return Ok(None);
    }
    if dense > room {
        return Err(format!(
            "{:.1} GB of dense weights past the card's room of {:.1} GB beside {:.2} GB of caches (CMF_HYB_RESERVE_MB, CMF_MAX_SEQ)",
            dense as f64 / 1e9,
            room as f64 / 1e9,
            kv as f64 / 1e9
        ));
    }
    // the card's room for experts goes to the layers read most a token (the
    // loop first), then by depth; the last layer it reaches keeps a part
    let reads = |li: usize| if (cfg.core_start..cfg.core_end).contains(&li) { cfg.passes } else { 1 };
    let mut order: Vec<usize> = (0..layers.len()).collect();
    order.sort_by_key(|&li| (std::cmp::Reverse(reads(li)), li));
    let mut left = room - dense;
    let mut card = vec![0usize; layers.len()];
    for &li in &order {
        card[li] = exp[li].min(left);
        left -= card[li];
    }
    let on_card: usize = card.iter().sum();
    let host = need_exp - on_card;
    // pinned pages are not reclaimed: past the host's room the plan is declined
    // (the host runs the sequence) instead of ending in the OOM killer
    let host_cap = host + host / 64 + (64 << 20);
    let hroom = host_room();
    if host_cap > hroom / 4 * 3 {
        return Err(format!("{:.1} GB of routed experts past the card, {:.1} GB of host memory to pin them in", host as f64 / 1e9, hroom as f64 / 1e9));
    }
    // every matrix rounds to 256 bytes in an arena
    let nmat = layers.iter().map(|l| 6 + 2 * l.moe.experts.len()).sum::<usize>() + 64;
    let dev_cap = dense + on_card + nmat * 256;
    let a = Buf::new(dev_cap)?;
    ARENA.with(|x| x.set((a.ptr, dev_cap, 0)));
    st.hyb.arenas.push(a);
    let h = HostArena::big(host_cap)?;
    ARENA_HOST.with(|x| x.set((h.dev, host_cap, 0)));
    st.hyb.host_arenas.push(h);
    let spilled: Vec<usize> = (0..layers.len()).filter(|&li| card[li] < exp[li]).collect();
    let all_reads: usize = (0..layers.len()).map(|li| reads(li) * exp[li]).sum();
    let card_reads: usize = (0..layers.len()).map(|li| reads(li) * card[li]).sum();
    tracing::info!(
        "inkling2_loop on CUDA: {:.1} GB of weights on the card beside {:.2} GB of K/V and {:.2} GB kept for the calls, {:.1} GB of routed experts (layers {}) in mapped host memory, read over the bus; {:.0} % of a token's expert reads stay on the card (CMF_HYB_HOST_EXPERTS=0: no overflow)",
        (dense + on_card) as f64 / 1e9,
        kv as f64 / 1e9,
        past as f64 / 1e9,
        host as f64 / 1e9,
        ranges(&spilled),
        100.0 * card_reads as f64 / all_reads.max(1) as f64
    );
    Ok(Some(card))
}

fn build(c: &Ctx, st: &mut State, g: &Globals, layers: &[Layer], cfg: &Cfg) -> Res<Dev> {
    let t0 = std::time::Instant::now();
    // the 6144 expert matrices (1.3 and 2.7 MB) as pieces of shared slabs: the
    // driver rounds each allocation above a megabyte up to a multiple of two,
    // which took 6 GB of an L4 beside 13.6 GB of weights
    let slabs = super::super::SlabScope::enter();
    let (hidden, nh, nkv, hd, dr) = (cfg.dim, cfg.nh, cfg.nkv, cfg.hd, cfg.d_rel);
    let hpk = nh / nkv;
    let hfx = match st.hyb.funcs.get(&(hpk, hd)) {
        Some(f) => f.clone(),
        None => {
            let f = Arc::new(load_funcs(c, hpk, hd)?);
            st.hyb.funcs.insert((hpk, hd), f.clone());
            f
        }
    };
    // `CMF_INKLING_MOE_FOLD=0`: a prompt call's expert GEMM scales its sums
    // after every mma instead of folding the group scale into the f16 weights
    let fold = (std::env::var("CMF_INKLING_MOE_FOLD").as_deref() != Ok("0")) as i32;
    let module = compile(SRC, vec![format!("-DH={hidden}"), format!("-DHD={hd}"), format!("-DNKV={nkv}"), format!("-DNH={nh}"), format!("-DDR={dr}"), "-DKC=4".into(), format!("-DMOE_FOLD={fold}")], c.arch)?;
    let fx = Fx {
        mix: func(module, "ink_mix")?,
        mix2: func(module, "ink_mix2")?,
        rms3: func(module, "ink_rms3")?,
        gd3: func(module, "ink_gate_down3")?,
        go3: func(module, "ink_gate_out3")?,
        merge_g: func(module, "ink_attn_merge_g")?,
        post_mx: func(module, "ink_post_mx")?,
        qrkv2: func(module, "ink_qrkv2")?,
        qrkv: func(module, "ink_qrkv")?,
        fmv3: func(module, "ink_fmv3")?,
        post_mix: func(module, "ink_post_mix")?,
        gate_rr: func(module, "ink_gate_rr")?,
        rms_h: func(module, "ink_rms_h")?,
        ogate_h: func(module, "ink_ogate_h")?,
        gate_d: func(module, "ink_gate_d")?,
        gate_mix2: func(module, "ink_gate_mix2")?,
        rms: func(module, "ink_rms")?,
        gate_down: func(module, "ink_gate_down")?,
        gate_out: func(module, "ink_gate_out")?,
        fmv: func(module, "ink_fmv")?,
        qr: func(module, "ink_qr")?,
        kv: func(module, "ink_kv")?,
        attn: func(module, "ink_attn")?,
        ogate: func(module, "ink_ogate")?,
        post: func(module, "ink_post")?,
        softcap: func(module, "ink_softcap")?,
        attn_split: func(module, "ink_attn_split")?,
        attn_merge: func(module, "ink_attn_merge")?,
        h16: func(module, "ink_h16")?,
        f16: func(module, "ink_f16")?,
        gather16: func(module, "ink_gather16")?,
        moe_mma: func(module, "ink_moe_mma")?,
        moe_mma2: func(module, "ink_moe_mma2")?,
        ring_snap: func(module, "ink_ring_snap")?,
        ring_back: func(module, "ink_ring_back")?,
        ds_mix: func(module, "ink_ds_mix")?,
        ds_ctx: func(module, "ink_ds_ctx")?,
        ds_qk: func(module, "ink_ds_qk")?,
        ds_attn: func(module, "ink_ds_attn")?,
        planes: func(module, "ink_planes")?,
        ds_markov: func(module, "ink_ds_markov")?,
        ds_pick: func(module, "ink_ds_pick")?,
        argmax_rows: func(module, "ink_argmax_rows")?,
        attn_soft: func(module, "ink_attn_soft")?,
        attn_flash: func(module, "ink_attn_flash")?,
        gate_norm: func(module, "ink_gate_norm")?,
        gate_mix: func(module, "ink_gate_mix")?,
        kv_rows: func(module, "ink_kv_rows")?,
        ring_rows: func(module, "ink_ring_rows")?,
        post_rows: func(module, "ink_post_rows")?,
    };
    let f4 = |n: usize| Buf::new(n * 4);
    let h2 = |n: usize| Buf::new(n * 2 + 64);
    let (qs, kvs, rs) = (nh * hd, nkv * hd, nh * dr);
    // the prompt path's rows (f16 weight GEMMs, as the hybrid's)
    let big_on = bmax() > NMAX && prec().0 == Gemm::Half;
    let rows = if big_on { bmax() } else { NMAX };
    let (yq, yg, yr, yk, yv) = (f4(rows * qs)?, f4(rows * qs)?, f4(rows * rs)?, f4(rows * kvs)?, f4(rows * kvs)?);
    let ya = f4(rows * hidden)?;
    let vocab = g.lm_head.rows();
    let logits = f4(NMAX * vocab)?;
    let e = layers.first().map_or(0, |l| l.moe.bias.len());
    let k = cfg.top_k;
    let inter = layers.first().and_then(|l| l.moe.experts.first()).map_or(0, |x| x[0].rows());
    let smax = (NMAX * k).min(e);
    // a card short of the stack: the experts it reads least in mapped host
    // memory (`place_experts`); the arenas close with the drafter's build
    struct ArenaEnd;
    impl Drop for ArenaEnd {
        fn drop(&mut self) {
            ARENA.with(|x| x.set((0, 0, 0)));
            ARENA_HOST.with(|x| x.set((0, 0, 0)));
            ARENA_EXP_DEV.with(|x| x.set(usize::MAX));
        }
    }
    let arena_end = ArenaEnd;
    let budgets = place_experts(st, g, layers, cfg, rows, e, k, inter, big_on)?;
    let mut dl = Vec::with_capacity(layers.len());
    for (li, l) in layers.iter().enumerate() {
        let a = &l.attn;
        let (q, gt, rl, km, vm, om) = (mat(c, st, &a.q)?, mat(c, st, &a.gate)?, mat(c, st, &a.rel)?, mat(c, st, &a.k)?, mat(c, st, &a.v)?, mat(c, st, &a.o)?);
        let qset = mmaset(&[(&q, yq.ptr, 0, qs, qs), (&gt, yg.ptr, 0, qs, qs), (&rl, yr.ptr, 0, rs, rs)])?;
        let qkv = if l.sliding { Some(mmaset(&[(&q, yq.ptr, 0, qs, qs), (&gt, yg.ptr, 0, qs, qs), (&rl, yr.ptr, 0, rs, rs), (&km, yk.ptr, 0, kvs, kvs), (&vm, yv.ptr, 0, kvs, kvs)])?) } else { None };
        let plane = (rows * hidden) as i32;
        let qkv3 = mmaset_core(&[(&q, yq.ptr, 0, qs, qs), (&gt, yg.ptr, 0, qs, qs), (&rl, yr.ptr, 0, rs, rs), (&km, yk.ptr, 0, kvs, kvs), (&vm, yv.ptr, 0, kvs, kvs)], 6, Some(&[0, 0, 0, plane, 2 * plane]), 0.0)?;
        let kset = mmaset(&[(&km, yk.ptr, 0, kvs, kvs)])?;
        let vset = mmaset(&[(&vm, yv.ptr, 0, kvs, kvs)])?;
        let oset = mmaset(&[(&om, ya.ptr, 0, hidden, hidden)])?;
        let dense = [q.clone(), gt.clone(), rl.clone(), km.clone(), vm.clone(), om.clone()];
        let mut mats = vec![q, gt, rl, km, vm, om];
        // the routed experts: Inkling's softcapped SwiGLU in the pair's epilogue
        // (kind bit 0x2000: the gate's cap in `lim`, the up branch's in pad[0])
        let mut gu_t = Vec::with_capacity(e);
        let mut dn_t = Vec::with_capacity(e);
        if let Some(b) = &budgets {
            ARENA_EXP_DEV.with(|x| x.set(b[li]));
        }
        EXPERT_MAT.with(|x| x.set(true));
        let built = (|| -> Res<()> {
            for [eg, eu, ed] in &l.moe.experts {
                let (mg, gwg) = gw_of(eg).ok_or("expert gate codec")?;
                let (_, gwu) = gw_of(eu).ok_or("expert up codec")?;
                let pm = hmat_pair(c, st, &mg, &gwg, &gwu, inter, hidden)?;
                let dmx = mat(c, st, ed)?;
                gu_t.push(HyJob { lim: cfg.gate_cap, pad: [cfg.up_cap.to_bits() as i32, 0, 0], ..job(&pm, 2 * inter, pm.kind as i32 | 0x100 | 0x2000) });
                dn_t.push(job(&dmx, hidden, dmx.kind as i32));
                mats.push(pm);
                mats.push(dmx);
            }
            Ok(())
        })();
        EXPERT_MAT.with(|x| x.set(false));
        built?;
        let one_kd = |t: &[HyJob]| {
            let d = t.first().and_then(|j| kd_of(j.kind & 0xFF))?;
            t.iter().all(|j| kd_of(j.kind & 0xFF) == Some(d)).then_some(d)
        };
        let kd = (one_kd(&gu_t), one_kd(&dn_t));
        let gates = match &l.gates {
            Some(gs) => {
                let mk = |x: &crate::inkling::Gate| -> Res<GateD> {
                    let fg: Vec<f32> = x.forget.iter().chain(x.gain.iter()).copied().collect();
                    Ok(GateD { down: f32b(&x.down)?, forget: f32b(&x.forget)?, gain: f32b(&x.gain)?, fg: f32b(&fg)? })
                };
                Some([mk(&gs[0])?, mk(&gs[1])?, mk(&gs[2])?, mk(&gs[3])?])
            }
            None => None,
        };
        dl.push(LayerD {
            sliding: l.sliding,
            boundary: li % cfg.block == 0,
            aq: match &l.attn_query {
                Some(q) => Some((f32b(q)?, q.len() / hidden)),
                None => None,
            },
            mq: f32b(&l.mlp_query)?,
            norms: [f32b(&l.in_norm[0])?, f32b(&l.in_norm[1])?, f32b(&l.in_norm[2])?],
            post_norm: f32b(&l.post_norm)?,
            qset,
            qkv,
            qkv3,
            kset,
            vset,
            oset,
            sink: f32b(&a.sink)?,
            q_scale: f32b(&a.q_scale)?,
            rel_scale: f32b(&a.rel_scale)?,
            rel_table: f32b(&a.rel_table)?,
            rel_tb: Buf::from_slice(&rel_band(&a.rel_table, dr))?,
            extent: a.rel_table.len() / dr,
            tk: f32b(&a.k_conv.taps)?,
            tv: f32b(&a.v_conv.taps)?,
            dk: match &a.k_conv.proj {
                Some(p) => Some(f32b(p)?),
                None => None,
            },
            dv: match &a.v_conv.proj {
                Some(p) => Some(f32b(p)?),
                None => None,
            },
            tpa: f32b(&l.post_attn_conv.taps)?,
            tpm: f32b(&l.post_mlp_conv.taps)?,
            router: f32b(&l.moe.router)?,
            bias: f32b(&l.moe.bias)?,
            e,
            inter,
            gu_t: Buf::from_slice(&gu_t)?,
            dn_t: Buf::from_slice(&dn_t)?,
            kd,
            bpj_gu: (2 * inter).div_ceil(16) as u32,
            bpj_dn: hidden.div_ceil(16) as u32,
            gates,
            dense,
            _mats: mats,
        });
    }
    let hm = mat(c, st, &g.lm_head)?;
    let head = mmaset(&[(&hm, logits.ptr, 0, vocab, vocab)])?;
    let resident = c.resident.load(Ordering::Relaxed);
    // the caches: a local slot's window, a full slot's context cap
    let cap = cfg.max_seq;
    let mut slots = Vec::with_capacity(cfg.slots());
    for (li, pass) in cfg.plan() {
        let _ = pass;
        // a local slot's ring: its window and a call's rows (the call writes
        // every row's key before any row reads)
        let ring = if layers[li].sliding { cfg.window + rows } else { 0 };
        let rows_kv = if ring > 0 { ring } else { cap };
        let s = SlotD {
            k: h2(rows_kv * kvs)?,
            v: h2(rows_kv * kvs)?,
            ring,
            rings: [f4(3 * kvs)?, f4(3 * kvs)?, f4(3 * hidden)?, f4(3 * hidden)?],
            hist: [f4(NMAX * kvs)?, f4(NMAX * kvs)?, f4(NMAX * hidden)?, f4(NMAX * hidden)?],
            snap: [f4(3 * kvs)?, f4(3 * kvs)?, f4(3 * hidden)?, f4(3 * hidden)?],
        };
        c.kv_bytes.fetch_add((s.k.bytes + s.v.bytes) as u64, Ordering::Relaxed);
        slots.push(s);
    }
    // slots by application order → by slot index
    let mut by_slot: Vec<Option<SlotD>> = (0..cfg.slots()).map(|_| None).collect();
    for ((li, pass), s) in cfg.plan().into_iter().zip(slots) {
        by_slot[cfg.slot(li, pass)] = Some(s);
    }
    let slots: Vec<SlotD> = by_slot.into_iter().map(|s| s.ok_or_else(|| "a slot without its application".to_string())).collect::<Res<_>>()?;
    let job_b = std::mem::size_of::<HyJob>();
    let mut tab = Vec::with_capacity(slots.len() * 4);
    for sl in &slots {
        for j in 0..4 {
            tab.push(RingRef { live: sl.rings[j].ptr, snap: sl.snap[j].ptr, hist: sl.hist[j].ptr, width: if j < 2 { kvs } else { hidden } as i32, pad: 0 });
        }
    }
    let rings_tab = Buf::from_slice(&tab)?;
    let nrings = tab.len();
    let draft = match &g.draft {
        Some(dr) => match build_draft(c, st, g, dr, cfg, rows, &hm, cap) {
            Ok(x) => Some(x),
            Err(e) => {
                tracing::warn!("inkling2_loop on CUDA: the DSpark drafter does not build ({e}); plain decoding");
                None
            }
        },
        None => None,
    };
    drop(arena_end);
    // the prompt path: every dense weight in a codec it expands (q4tp, int8)
    let big = if big_on && dl.iter().all(|l| l.dense.iter().all(|m| matches!(m.kind, 5 | 6 | 15))) && inter % 32 == 0 && e <= 1024 {
        let wmax = dl.iter().flat_map(|l| l.dense.iter().map(|m| m.rows * m.cols)).max().unwrap_or(0);
        let wd_bytes = (wmax * 2).min(wd_cap().max(1 << 20));
        let nk = rows * k;
        let jmax = e + nk.div_ceil(32);
        Some(Big {
            x16: [h2(rows * hidden)?, h2(rows * hidden)?, h2(rows * hidden)?],
            o16: h2(rows * qs)?,
            wd: Buf::new(wd_bytes + 64)?,
            wd_elems: wd_bytes / 2,
            wf16: std::cell::RefCell::new(HashMap::new()),
            wf16_left: std::cell::Cell::new(match std::env::var("CMF_INKLING_WF16_MB").ok().and_then(|v| v.parse::<usize>().ok()) {
                Some(mb) => mb << 20,
                None => super::super::card_free().saturating_sub(4 << 30).min(4 << 30),
            }),
            lg: f4(rows * e)?,
            pidx: f4(nk)?,
            pwt: f4(nk)?,
            pos: f4(nk)?,
            src: f4(nk)?,
            xg: [h2(nk * hidden)?, h2(nk * hidden)?],
            qq: [h2(nk * inter)?, h2(nk * inter)?],
            ys: f4(nk * hidden)?,
            gu_a: Buf::new(jmax * job_b)?,
            dn_a: Buf::new(jmax * job_b)?,
            gxn: f4(rows * 2 * hidden)?,
            gtf: f4(2 * rows * hidden)?,
            gtg: f4(rows * hidden)?,
            q16: h2(rows * qs)?,
            sc: Buf::new(ATT_SCORES)?,
            pr: Buf::new(ATT_SCORES / 2)?,
        })
    } else {
        None
    };
    let xpb = [h2(3 * rows * hidden)?, h2(3 * rows * hidden)?];
    let d = Dev {
        fx,
        hfx,
        rows,
        big,
        big_pos0: std::cell::Cell::new(0),
        rings_tab,
        nrings,
        draft,
        layers: dl,
        slots,
        head,
        msg_q: f32b(&g.message_query)?,
        final_q: f32b(&g.final_query)?,
        final_norm: f32b(&g.norm)?,
        h: [f4(rows * hidden)?, f4(rows * hidden)?],
        blk: f4(rows * MAXB * hidden)?,
        pre_h: f4(rows * hidden)?,
        bank: f4(rows * MAXB * hidden)?,
        bank_out: f4(rows * hidden)?,
        msg: f4(4 * rows * hidden)?,
        in3: f4(3 * rows * hidden)?,
        gin: f4(4 * rows * hidden)?,
        gd: f4(rows * 256)?,
        x: [f4(rows * hidden)?, f4(rows * hidden)?, f4(rows * hidden)?],
        xp: {
            let at = |b: &Buf, j: usize| DPtr { ptr: b.ptr + (j * rows * hidden * 2) as u64 };
            [[at(&xpb[0], 0), at(&xpb[1], 0)], [at(&xpb[0], 1), at(&xpb[1], 1)], [at(&xpb[0], 2), at(&xpb[1], 2)]]
        },
        xpb,
        yq,
        yg,
        yr,
        yk,
        yv,
        sk: f4(rows * nh)?,
        part: f4(NMAX * nh * cap.div_ceil(ATILE) * (hd + 2))?,
        dkb: f4(rows * nkv * 4)?,
        dvb: f4(rows * nkv * 4)?,
        att: f4(rows * qs)?,
        po: [h2(rows * qs)?, h2(rows * qs)?],
        ya,
        r: f4(rows * hidden)?,
        m: f4(rows * hidden)?,
        mg: f4(rows * hidden)?,
        xm: f4(rows * hidden)?,
        pm: [h2(rows * hidden)?, h2(rows * hidden)?],
        logits_e: f4(rows * e)?,
        sg: f4(rows)?,
        wsel: f4(NMAX * smax)?,
        gu_a: Buf::new(smax * job_b)?,
        dn_a: Buf::new(smax * job_b)?,
        qq: [Buf::new(smax * NMAX * hidden * 2)?, Buf::new(smax * NMAX * hidden * 2)?],
        dns: f4(smax * NMAX * hidden)?,
        y: f4(rows * hidden)?,
        fin: f4(rows * hidden)?,
        pf: [h2(rows * hidden)?, h2(rows * hidden)?],
        logits,
        cr: Buf::new(64)?,
        pick: Buf::new(NMAX * 4)?,
        rcnt: Buf::new(64)?,
        smax,
        graphs: HashMap::new(),
        cap,
    };
    tracing::info!(
        "inkling2_loop on CUDA: {} layers resident, {:.1} GB of weights, {:.2} GB of caches for {} positions, prompt calls of {} rows, built in {:.1} s; {}",
        layers.len(),
        resident as f64 / 1e9,
        d.slots.iter().map(|s| (s.k.bytes + s.v.bytes) as f64).sum::<f64>() / 1e9,
        cap,
        if d.big.is_some() { d.rows } else { NMAX },
        t0.elapsed().as_secs_f64(),
        slabs.report()
    );
    Ok(d)
}

impl Dev {
    fn zero_state(&self, c: &Ctx) -> Res<()> {
        unsafe {
            cu::memset_d8_async(self.rcnt.ptr, 0, self.rcnt.bytes, c.stream).map_err(derr)?;
            for s in &self.slots {
                for r in &s.rings {
                    cu::memset_d8_async(r.ptr, 0, r.bytes, c.stream).map_err(derr)?;
                }
            }
        }
        c.sync()
    }
}

/// `CMF_INKLING_FUSE=0`: a decode call's kernels one stage a launch (`ink_mix`,
/// `ink_rms`, `ink_fmv`, the gates' halves, `ink_qr` + `ink_kv`, the merge and
/// `ink_ogate`, router + select, combine + post) instead of the fused ones.
fn fuse_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_FUSE").as_deref() != Ok("0"))
}

/// `CMF_INKLING_GROUP2=0`: a prompt call's experts grouped by the one-warp-an-
/// expert scan (`hy_moe_group`) instead of the parallel count (`hy_moe_group2`).
fn group2_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var("CMF_INKLING_GROUP2").as_deref() != Ok("0"))
}

/// `CMF_INKLING_KT=N` (a measurement): is this the N-th decode call?
/// `CMF_INKLING_KT_ROWS=R` counts the calls of R rows instead (a verify call).
fn kt_call(rows: usize) -> bool {
    static N: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
    static R: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    if rows != *R.get_or_init(|| std::env::var("CMF_INKLING_KT_ROWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1)) {
        return false;
    }
    match N.get_or_init(|| std::env::var("CMF_INKLING_KT").ok().and_then(|v| v.parse().ok())) {
        Some(n) => SEEN.fetch_add(1, Ordering::Relaxed) + 1 == *n,
        None => false,
    }
}

/// Programmatic dependent launch for the arm's kernels on sm_90+ (Hopper,
/// Blackwell): a kernel schedules while its predecessor drains (RTX PRO 6000:
/// decode 122.7 → 127.6 tok/s, the same text). `CMF_INKLING_PDL=0|1` forces it.
fn pdl_on() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| {
        let on = match std::env::var("CMF_INKLING_PDL").as_deref() {
            Ok("0") => false,
            Ok("1") => true,
            _ => super::super::cc_major() >= 9,
        };
        if on {
            super::super::pdl_set(true);
        }
        on
    })
}

/// `true` when this call ran on the card. `ids` from position `pos0`; the
/// logits of the last row (`all`: of every row, `[n][vocab]`) when `want`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn forward(id: u64, g: &Globals, layers: &[Layer], cfg: &Cfg, ids: &[u32], pos0: usize, want: bool, all: bool, logits: &mut Vec<f32>) -> bool {
    let _ = pdl_on();
    forward_with(id, g, layers, cfg, ids, pos0, want, all, logits, None)
}

/// A draft verify: every row of `ids` through the target, each row's greedy
/// pick into `picks` on the card; the logits stay there for `row_logits`.
pub(crate) fn verify(id: u64, g: &Globals, layers: &[Layer], cfg: &Cfg, ids: &[u32], pos0: usize, picks: &mut Vec<u32>) -> bool {
    if ids.len() > NMAX {
        return false;
    }
    let mut none = Vec::new();
    forward_with(id, g, layers, cfg, ids, pos0, true, true, &mut none, Some(picks))
}

/// Row `r`'s logits of the last verify.
pub(crate) fn row_logits(id: u64, r: usize, vocab: usize, out: &mut Vec<f32>) -> bool {
    let Some(c) = super::super::ctx() else { return false };
    let guard = DEVICES.lock().unwrap();
    let Some(d) = guard.as_ref().and_then(|m| m.get(&id)) else { return false };
    if r >= NMAX {
        return false;
    }
    out.resize(vocab, 0.0);
    unsafe { cu::memcpy_dtoh_async(out, d.logits.ptr + (r * vocab * 4) as u64, c.stream).is_ok() && c.sync().is_ok() }
}

#[allow(clippy::too_many_arguments)]
fn forward_with(id: u64, g: &Globals, layers: &[Layer], cfg: &Cfg, ids: &[u32], pos0: usize, want: bool, all: bool, logits: &mut Vec<f32>, pick: Option<&mut Vec<u32>>) -> bool {
    let Some(c) = super::super::ctx() else { return false };
    if std::env::var("CMF_INKLING_CUDA").as_deref() == Ok("0") {
        return false;
    }
    if !admits(g, layers, cfg) {
        static SAID: std::sync::Once = std::sync::Once::new();
        SAID.call_once(|| tracing::warn!("inkling2_loop on CUDA: the file's codecs or geometry are not the arm's (q4tp / q8_2f matrices, 128-wide heads); the host runs it"));
        return false;
    }
    if DECLINED.lock().unwrap().contains(&id) {
        return false;
    }
    if c.current().is_err() {
        return false;
    }
    let mut guard = DEVICES.lock().unwrap();
    let map = guard.get_or_insert_with(HashMap::new);
    if !map.contains_key(&id) {
        // one sequence's state on the card at a time: a new sequence takes the
        // device over (its weights, caches and recorded calls stay)
        let old = map.keys().next().copied();
        match old {
            Some(k) => {
                let d = map.remove(&k).expect("device");
                map.insert(id, d);
            }
            None => {
                let built = {
                    let mut st = c.st.lock().unwrap();
                    build(c, &mut st, g, layers, cfg)
                };
                match built {
                    Ok(d) => {
                        map.insert(id, d);
                    }
                    Err(e) => {
                        tracing::warn!("inkling2_loop on CUDA declined: {e}; the host runs this sequence");
                        DECLINED.lock().unwrap().push(id);
                        return false;
                    }
                }
            }
        }
    }
    let d = map.get_mut(&id).expect("device");
    if pos0 == 0 && d.zero_state(c).is_err() {
        return false;
    }
    if pos0 + ids.len() > d.cap {
        tracing::warn!("inkling2_loop on CUDA: {} positions past the cap of {}", pos0 + ids.len(), d.cap);
        return false;
    }
    // `CMF_INKLING_WINDOW_PROBE=1` (a measurement, not a run): after a prompt,
    // the time of a call of 1..16 rows with every row's logits, as a draft
    // verify would take it; the sequence's state is spoiled
    if pos0 > 0 && std::env::var("CMF_INKLING_WINDOW_PROBE").as_deref() == Ok("1") {
        let vocab = g.lm_head.rows();
        let mut line = Vec::new();
        for n in [1usize, 2, 3, 4, 5, 6, 8, 12, 16] {
            let mut lg = Vec::new();
            let ids_n = vec![ids.first().copied().unwrap_or(0); n];
            let _ = forward_(c, d, g, cfg, &ids_n, pos0, true, true, &mut lg, None);
            let t = std::time::Instant::now();
            for _ in 0..10 {
                let _ = forward_(c, d, g, cfg, &ids_n, pos0, true, true, &mut lg, None);
            }
            line.push(format!("{n}: {:.2} ms", t.elapsed().as_secs_f64() * 100.0));
            let _ = vocab;
        }
        tracing::info!("inkling2_loop CUDA window probe (a call with every row's logits): {}", line.join(", "));
        std::process::exit(0);
    }
    match forward_(c, d, g, cfg, ids, pos0, want, all, logits, pick) {
        Ok(()) => true,
        Err(e) => {
            tracing::error!("inkling2_loop on CUDA: {e}");
            false
        }
    }
}

/// A sequence ends: the device stays for the next one (its rings are cleared
/// when that one starts at position 0).
pub(crate) fn reset(id: u64) {
    DECLINED.lock().unwrap().retain(|&x| x != id);
}

#[allow(clippy::too_many_arguments)]
fn forward_(c: &Ctx, d: &mut Dev, g: &Globals, cfg: &Cfg, ids: &[u32], pos0: usize, want: bool, all: bool, logits: &mut Vec<f32>, mut pick: Option<&mut Vec<u32>>) -> Res<()> {
    let hidden = cfg.dim;
    let vocab = g.lm_head.rows();
    if all {
        logits.clear();
    }
    let mut at = 0usize;
    while at < ids.len() {
        // a prompt's chunk of more than NMAX rows on the prompt path (every
        // row's logits then come from the head 16 rows at a time)
        let big = d.big.is_some() && ids.len() - at > NMAX;
        let n = (ids.len() - at).min(if big { d.rows } else { NMAX });
        let part = &ids[at..at + n];
        let last = at + n == ids.len();
        let lrows = if all { n } else if want && last { 1 } else { 0 };
        // the call's embedded rows, normed on the host
        let mut rows = vec![0f32; n * hidden];
        let mut e = vec![0f32; hidden];
        for (i, &id) in part.iter().enumerate() {
            e.fill(0.0);
            if (id as usize) < g.embed.rows() {
                g.embed.row_f32(&g.model, id as usize, &mut e);
            }
            let ms = e.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hidden as f64;
            let r = (1.0 / (ms + cfg.eps).sqrt()) as f32;
            for (o, (&v, &w)) in rows[i * hidden..(i + 1) * hidden].iter_mut().zip(e.iter().zip(&g.embed_norm)) {
                *o = w * (v * r);
            }
        }
        unsafe {
            cu::memcpy_htod_async(d.h[0].ptr, &rows, c.stream).map_err(derr)?;
            cu::memcpy_htod_async(d.cr.ptr, &[(pos0 + at) as i32, n as i32], c.stream).map_err(derr)?;
        }
        let key = (n, lrows);
        d.big_pos0.set(pos0 + at);
        if big && all {
            unsafe { call(c, d, cfg, n, 0, vocab)? };
            let mut r0 = 0usize;
            while r0 < n {
                let m = (n - r0).min(NMAX);
                unsafe { head_rows(c, d, cfg, r0, m, vocab)? };
                let mut v = vec![0f32; m * vocab];
                unsafe { cu::memcpy_dtoh_async(&mut v, d.logits.ptr, c.stream).map_err(derr)? };
                c.sync()?;
                logits.extend_from_slice(&v);
                r0 += m;
            }
            at += n;
            continue;
        }
        if n <= NMAX && kt_call(n) {
            // `CMF_INKLING_KT=N`: the N-th decode call without its graph, every
            // launch between two events, the time a kernel printed
            super::super::kt_start();
            unsafe { call(c, d, cfg, n, lrows, vocab)? };
            c.sync()?;
            super::super::kt_stop_as("inkling2_loop decode");
        } else if big {
            unsafe { call(c, d, cfg, n, lrows, vocab)? };
        } else if graphs_on() && !prof() {
            if !d.graphs.contains_key(&key) {
                let dd: &Dev = d;
                let exec = unsafe { capture(c, || call(c, dd, cfg, n, lrows, vocab))? };
                d.graphs.insert(key, GraphRec { exec, sig: vec![n as u64, lrows as u64] });
            }
            unsafe { curesult(cs::cuGraphLaunch(d.graphs[&key].exec, c.stream), "graph launch")? };
        } else {
            unsafe { call(c, d, cfg, n, lrows, vocab)? };
        }
        unsafe { ds_dump_taps(c, d, cfg, n, pos0 + at)? };
        if lrows > 0 && all && !big {
            if let Some(p) = pick.as_deref_mut() {
                let mut v = vec![0i32; lrows];
                let v_i = vocab as i32;
                unsafe {
                    c.launch(d.fx.argmax_rows, (lrows as u32, 1), 1024, 0, kargs!(d.logits.ptr, v_i, d.pick.ptr))?;
                    cu::memcpy_dtoh_async(&mut v, d.pick.ptr, c.stream).map_err(derr)?;
                }
                c.sync()?;
                p.extend(v.iter().map(|&x| x as u32));
                at += n;
                continue;
            }
        }
        if lrows > 0 {
            let mut v = vec![0f32; lrows * vocab];
            unsafe { cu::memcpy_dtoh_async(&mut v, d.logits.ptr, c.stream).map_err(derr)? };
            c.sync()?;
            if all {
                logits.extend_from_slice(&v);
            } else {
                *logits = v;
            }
        }
        at += n;
    }
    c.sync()
}

/// The launches of one call of `n` rows (positions from `cr[0]`): the 48
/// applications, the final mixture and, for the last `lrows` rows, the head.
unsafe fn call(c: &Ctx, d: &Dev, cfg: &Cfg, n: usize, lrows: usize, vocab: usize) -> Res<()> {
    if prof() {
        IN_BIG.store(n > NMAX, Ordering::Relaxed);
    }
    let hidden = cfg.dim;
    let hb = n * hidden * 4;
    let ost = (d.rows * hidden) as i32;
    let bst = (MAXB * hidden) as i32;
    let mut cur = 0usize;
    let mut hin = d.h[0].ptr;
    let mut nb = 0usize;
    let mut npre = 0usize;
    for (ai, (li, pass)) in cfg.plan().into_iter().enumerate() {
        let l = &d.layers[li];
        let s = &d.slots[cfg.slot(li, pass)];
        // the drafter's taps: this application's input rows
        if let Some(dr) = &d.draft {
            if let Some(k) = dr.taps.iter().position(|&t| t == ai) {
                unsafe { cu::memcpy_dtod_async(dr.tap.ptr + ((k * d.rows * hidden) * 4) as u64, hin, hb, c.stream).map_err(derr)? };
            }
        }
        if li == cfg.core_start {
            unsafe {
                if pass == 0 {
                    cu::memcpy_dtod_async(d.pre_h.ptr, hin, hb, c.stream).map_err(derr)?;
                    npre = nb;
                } else {
                    // the previous pass's blocks after its first, and its output
                    cu::memcpy_dtod_async(d.bank.ptr, d.blk.ptr, n * MAXB * hidden * 4, c.stream).map_err(derr)?;
                    cu::memcpy_dtod_async(d.bank_out.ptr, hin, hb, c.stream).map_err(derr)?;
                    hin = d.pre_h.ptr;
                }
            }
        }
        let bank_nb = if pass > 0 { cfg.loop_len() / cfg.block - 1 } else { 0 };
        if pass > 0 && li == cfg.core_start {
            nb = npre;
        }
        let hout = d.h[1 - cur].ptr;
        match &d.big {
            Some(b) if n > NMAX => unsafe { app_big(c, d, b, cfg, l, s, li, pass, n, hin, hout, &mut nb, npre, bank_nb)? },
            _ => unsafe { app(c, d, cfg, l, s, li, pass, n, hin, hout, &mut nb, npre, bank_nb)? },
        }
        cur = 1 - cur;
        hin = hout;
    }
    // the final mixture, its norm and the head
    let f = &d.fx;
    let mut tp = std::time::Instant::now();
    unsafe {
        let nb_i = nb as i32;
        c.launch(f.mix, (1, n as u32), 256, 0, kargs!(d.blk.ptr, nb_i, bst, hin, d.final_q.ptr, d.fin.ptr, ost))?;
        if let Some(dr) = &d.draft {
            draft_commit(c, d, dr, cfg, n)?;
        }
        if lrows > 0 {
            head_rows(c, d, cfg, n - lrows, lrows, vocab)?;
        }
    }
    st(c, 10, &mut tp)?;
    if prof() && n > NMAX {
        IN_BIG.store(false, Ordering::Relaxed);
        prof_report_big(n);
    }
    if prof() && n == 1 {
        let k = PROF_CALLS.fetch_add(1, Ordering::Relaxed) + 1;
        if k % 64 == 0 {
            prof_report();
        }
    }
    Ok(())
}

/// The drafter's context of a call's rows: the final normed state as the last
/// tap, the mixes, every layer's context keys and values at the rows'
/// positions, the Markov head's context into its ring.
unsafe fn draft_commit(c: &Ctx, d: &Dev, dr: &DraftD, cfg: &Cfg, n: usize) -> Res<()> {
    let f = &d.fx;
    let hidden = cfg.dim;
    let rows = d.rows;
    let kvs = cfg.nkv * cfg.hd;
    let nt = dr.taps.len() + 1;
    let (nul, hs, eps) = (0u64, hidden as i32, cfg.eps as f32);
    let last = dr.tap.ptr + (((nt - 1) * rows * hidden) * 4) as u64;
    let (nt_i, rows_i, nmix_i, fr_i) = (nt as i32, rows as i32, (dr.layers.len() + 1) as i32, FR as i32);
    unsafe {
        c.launch(f.rms, (n as u32, 1), 256, 0, kargs!(d.fin.ptr, d.final_norm.ptr, eps, last, nul, nul, hs))?;
        c.launch(
            f.ds_mix,
            (n as u32, (dr.layers.len() + 1) as u32),
            256,
            0,
            kargs!(dr.tap.ptr, nt_i, rows_i, dr.alpha.ptr, dr.norms.ptr, dr.eps, nmix_i, dr.mixp[0].ptr, dr.mixp[1].ptr, dr.mixh.ptr, dr.fr.ptr, fr_i, d.cr.ptr),
        )?;
        for (l, dl) in dr.layers.iter().enumerate() {
            let off = ((l * rows * hidden) * 2) as u64;
            if n <= NMAX {
                let pl = Planes { p0: dr.mixp[0].ptr + off, p1: dr.mixp[1].ptr + off, p2: dr.mixp[1].ptr + off, stride: hidden };
                dl.kctx.run(c, &d.hfx, &pl, hidden, n)?;
                dl.vctx.run(c, &d.hfx, &pl, hidden, n)?;
            } else {
                let b = d.big.as_ref().ok_or("a prompt call without the prompt path")?;
                wmul(c, &d.hfx, b, &dl.kctx_m, dr.mixh.ptr + off, dr.ckb.ptr, kvs, n)?;
                wmul(c, &d.hfx, b, &dl.vctx_m, dr.mixh.ptr + off, dr.cvb.ptr, kvs, n)?;
            }
            let (cap_i, ring_i) = (dl.cap as i32, dl.ring as i32);
            c.launch(f.ds_ctx, (n as u32, cfg.nkv as u32), cfg.hd as u32, 0, kargs!(dr.ckb.ptr, dr.cvb.ptr, dl.kc_norm.ptr, dr.eps, dr.theta, dl.ck.ptr, dl.cv.ptr, cap_i, ring_i, d.cr.ptr))?;
        }
    }
    Ok(())
}

/// The drafter on the card (`g.draft`): its matrices in the arm's codecs, its
/// caches for `cap` positions, the target's head for its block.
#[allow(clippy::too_many_arguments)]
fn build_draft(c: &Ctx, st: &mut State, g: &Globals, dr: &crate::inkling::Draft, cfg: &Cfg, rows: usize, hm: &Arc<DevMat>, cap: usize) -> Res<DraftD> {
    let hidden = cfg.dim;
    let (nh, nkv, hd) = (cfg.nh, cfg.nkv, cfg.hd);
    let (qs, kvs) = (nh * hd, nkv * hd);
    let b = dr.block;
    if dr.layers.is_empty() || dr.targets.len() < 2 || b < 2 || b > NMAX + 1 || dr.rank * 3 > 1024 {
        return Err("the drafter's geometry".into());
    }
    let f4 = |n: usize| Buf::new(n * 4);
    let h2 = |n: usize| Buf::new(n * 2 + 64);
    let f32b = |v: &[f32]| Buf::from_slice(v);
    let inter = dr.layers[0].gate.rows();
    let x = f4(b * hidden)?;
    let xp = [h2(b * hidden)?, h2(b * hidden)?];
    let (dq, dk, dv) = (f4(b * qs)?, f4(b * kvs)?, f4(b * kvs)?);
    let att = f4(b * qs)?;
    let ap = [h2(b * qs)?, h2(b * qs)?];
    let gp = [h2(b * inter)?, h2(b * inter)?];
    let (ckb, cvb) = (f4(rows * kvs)?, f4(rows * kvs)?);
    let mut layers = Vec::new();
    let mut all = Vec::new();
    for dl in &dr.layers {
        let (q, k, v, o) = (mat(c, st, &dl.q)?, mat(c, st, &dl.k)?, mat(c, st, &dl.v)?, mat(c, st, &dl.o)?);
        let (kc, vc, dn) = (mat(c, st, &dl.k_ctx)?, mat(c, st, &dl.v_ctx)?, mat(c, st, &dl.down)?);
        let (mg, gwg) = gw_of(&dl.gate).ok_or("drafter gate codec")?;
        let (_, gwu) = gw_of(&dl.up).ok_or("drafter up codec")?;
        let pm = hmat_pair(c, st, &mg, &gwg, &gwu, inter, hidden)?;
        let qkv = mmaset(&[(&q, dq.ptr, 0, qs, qs), (&k, dk.ptr, 0, kvs, kvs), (&v, dv.ptr, 0, kvs, kvs)])?;
        let kctx = mmaset(&[(&kc, ckb.ptr, 0, kvs, kvs)])?;
        let vctx = mmaset(&[(&vc, cvb.ptr, 0, kvs, kvs)])?;
        let oset = mmaset(&[(&o, x.ptr, x.ptr, hidden, hidden)])?;
        let gu = mmaset_pair(&pm, gp[0].ptr, gp[1].ptr, inter)?;
        let down = mmaset(&[(&dn, x.ptr, x.ptr, hidden, hidden)])?;
        let lcap = if dl.local { dr.window + 64 } else { cap + b };
        let ck = Buf::new(lcap * kvs * 2 + 64)?;
        let cv = Buf::new(lcap * kvs * 2 + 64)?;
        c.kv_bytes.fetch_add((ck.bytes + cv.bytes) as u64, Ordering::Relaxed);
        layers.push(DLayerD {
            qkv,
            kctx,
            vctx,
            kctx_m: kc.clone(),
            vctx_m: vc.clone(),
            o: oset,
            gu,
            down,
            in_norm: f32b(&dl.in_norm)?,
            post_norm: f32b(&dl.post_norm)?,
            q_norm: f32b(&dl.q_norm)?,
            k_norm: f32b(&dl.k_norm)?,
            kc_norm: f32b(&dl.k_ctx_norm)?,
            ck,
            cv,
            cap: lcap,
            ring: dl.local,
            _mats: vec![q, k, v, o, kc, vc, dn, pm],
        });
    }
    let nt = dr.targets.len();
    let mut norms = Vec::with_capacity((dr.layers.len() + 1) * hidden);
    for dl in &dr.layers {
        norms.extend_from_slice(&dl.dflare_norm);
    }
    norms.extend_from_slice(&dr.markov_norm);
    let mut masks = Vec::with_capacity((b - 1) * hidden);
    for _ in 1..b {
        masks.extend_from_slice(&dr.mask);
    }
    let vocab = g.lm_head.rows();
    let dlog = f4((b - 1) * vocab)?;
    let head = mmaset(&[(hm, dlog.ptr, 0, vocab, vocab)])?;
    let fold = mat(c, st, &dr.fold)?;
    let latp = [h2(dr.rank)?, h2(dr.rank)?];
    let mut folds = Vec::with_capacity(b - 1);
    for i in 0..b - 1 {
        let y = dlog.ptr + ((i * vocab) * 4) as u64;
        folds.push(mmaset(&[(&fold, y, y, vocab, vocab)])?);
    }
    all.push(fold);
    // the previous token's rows, f16
    let rank = dr.rank;
    let mut w1 = vec![0u16; dr.w1.rows() * rank];
    let mut row = vec![0f32; rank];
    for r in 0..dr.w1.rows() {
        dr.w1.row_f32(r, &mut row);
        for (o, &v) in w1[r * rank..(r + 1) * rank].iter_mut().zip(&row) {
            *o = cortiq_core::quant::f32_to_f16(v);
        }
    }
    Ok(DraftD {
        layers,
        taps: dr.targets[..nt - 1].to_vec(),
        tap: f4(nt * rows * hidden)?,
        alpha: f32b(&dr.alpha)?,
        norms: f32b(&norms)?,
        fnorm: f32b(&dr.norm)?,
        mixp: [h2(dr.layers.len() * rows * hidden)?, h2(dr.layers.len() * rows * hidden)?],
        mixh: h2(dr.layers.len() * rows * hidden)?,
        ckb,
        cvb,
        fr: f4(FR * hidden)?,
        masks: f32b(&masks)?,
        x,
        xp,
        dq,
        dk,
        dv,
        att,
        ap,
        gp,
        hf: f4(b * hidden)?,
        hp: [h2(b * hidden)?, h2(b * hidden)?],
        dcr: Buf::new(64)?,
        head,
        dlog,
        rnn_w: f32b(&dr.rnn_w)?,
        rnn_b: f32b(&dr.rnn_b)?,
        ch: f4((b - 1) * 3 * rank)?,
        cf: f4(3 * rank)?,
        state: f4(rank)?,
        prev: Buf::new(64)?,
        ids: Buf::new(64)?,
        w1: Buf::from_slice(&w1)?,
        folds,
        fold_b: f32b(&dr.fold_b)?,
        latp,
        block: b,
        rank,
        window: dr.window,
        theta: dr.rope_theta as f32,
        eps: dr.eps,
        inter,
        _mats: all,
    })
}

/// One block of the drafter from the anchor at `pos` (the target has run every
/// position before it): up to `k` drafts, on the card.
pub(crate) fn draft_round(id: u64, g: &Globals, cfg: &Cfg, anchor: u32, pos: usize, k: usize) -> Option<Vec<u32>> {
    let c = super::super::ctx()?;
    let guard = DEVICES.lock().unwrap();
    let d = guard.as_ref()?.get(&id)?;
    let dr = d.draft.as_ref()?;
    if pos == 0 || k == 0 || pos + dr.block > d.cap {
        return None;
    }
    let k = k.min(dr.block - 1);
    match unsafe { draft_block(c, d, dr, g, cfg, anchor, pos, k) } {
        Ok(v) => Some(v),
        Err(e) => {
            tracing::warn!("inkling2_loop on CUDA: a draft failed: {e}");
            None
        }
    }
}

#[allow(clippy::too_many_arguments)]
unsafe fn draft_block(c: &Ctx, d: &Dev, dr: &DraftD, g: &Globals, cfg: &Cfg, anchor: u32, pos: usize, k: usize) -> Res<Vec<u32>> {
    let f = &d.fx;
    let hidden = cfg.dim;
    let (nh, nkv, hd) = (cfg.nh, cfg.nkv, cfg.hd);
    let qs = nh * hd;
    let b = dr.block;
    let vocab = g.lm_head.rows();
    let (bu, eps, hs) = (b as u32, dr.eps, hidden as i32);
    // the anchor's normed embedding, as the target's input row
    let mut e = vec![0f32; hidden];
    if (anchor as usize) < g.embed.rows() {
        g.embed.row_f32(&g.model, anchor as usize, &mut e);
    }
    let ms = e.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>() / hidden as f64;
    let r = (1.0 / (ms + cfg.eps).sqrt()) as f32;
    let row0: Vec<f32> = e.iter().zip(&g.embed_norm).map(|(&v, &w)| w * (v * r)).collect();
    unsafe {
        cu::memcpy_htod_async(dr.x.ptr, &row0, c.stream).map_err(derr)?;
        cu::memcpy_dtod_async(dr.x.ptr + (hidden * 4) as u64, dr.masks.ptr, (b - 1) * hidden * 4, c.stream).map_err(derr)?;
        cu::memcpy_htod_async(dr.dcr.ptr, &[pos as i32, b as i32], c.stream).map_err(derr)?;
        cu::memcpy_htod_async(dr.prev.ptr, &[anchor as i32], c.stream).map_err(derr)?;
        cu::memset_d8_async(dr.state.ptr, 0, dr.rank * 4, c.stream).map_err(derr)?;
        let xpl = Planes { p0: dr.xp[0].ptr, p1: dr.xp[1].ptr, p2: dr.xp[1].ptr, stride: hidden };
        let nul = 0u64;
        for dl in &dr.layers {
            c.launch(f.rms, (bu, 1), 256, 0, kargs!(dr.x.ptr, dl.in_norm.ptr, eps, nul, dr.xp[0].ptr, dr.xp[1].ptr, hs))?;
            dl.qkv.run(c, &d.hfx, &xpl, hidden, b)?;
            let (cap_i, ring_i) = (dl.cap as i32, dl.ring as i32);
            c.launch(f.ds_qk, (bu, (nh + nkv) as u32), hd as u32, 0, kargs!(dr.dq.ptr, dr.dk.ptr, dr.dv.ptr, dl.q_norm.ptr, dl.k_norm.ptr, eps, dr.theta, dl.ck.ptr, dl.cv.ptr, cap_i, ring_i, dr.dcr.ptr))?;
            let (win_i, b_i) = (if dl.ring { dr.window as i32 } else { 0 }, b as i32);
            c.launch(f.ds_attn, (nh as u32, bu), 256, 0, kargs!(dr.dq.ptr, dl.ck.ptr, dl.cv.ptr, cap_i, ring_i, win_i, b_i, dr.att.ptr, dr.dcr.ptr))?;
            let tot = (b * qs) as i32;
            c.launch(f.planes, ((b * qs).div_ceil(256) as u32, 1), 256, 0, kargs!(dr.att.ptr, dr.ap[0].ptr, dr.ap[1].ptr, tot))?;
            let apl = Planes { p0: dr.ap[0].ptr, p1: dr.ap[1].ptr, p2: dr.ap[1].ptr, stride: qs };
            dl.o.run(c, &d.hfx, &apl, qs, b)?;
            c.launch(f.rms, (bu, 1), 256, 0, kargs!(dr.x.ptr, dl.post_norm.ptr, eps, nul, dr.xp[0].ptr, dr.xp[1].ptr, hs))?;
            dl.gu.run(c, &d.hfx, &xpl, hidden, b)?;
            let gpl = Planes { p0: dr.gp[0].ptr, p1: dr.gp[1].ptr, p2: dr.gp[1].ptr, stride: dr.inter };
            dl.down.run(c, &d.hfx, &gpl, dr.inter, b)?;
        }
        // h; the rows after the anchor's through the target's head (the drafts' base logits)
        c.launch(f.rms, (bu, 1), 256, 0, kargs!(dr.x.ptr, dr.fnorm.ptr, eps, dr.hf.ptr, dr.hp[0].ptr, dr.hp[1].ptr, hs))?;
        let hpl = Planes { p0: dr.hp[0].ptr + (hidden * 2) as u64, p1: dr.hp[1].ptr + (hidden * 2) as u64, p2: dr.hp[1].ptr + (hidden * 2) as u64, stride: hidden };
        dr.head.run(c, &d.hfx, &hpl, hidden, k)?;
        // the recurrence's input terms: W_h · h_{i+1} for every draft, W_f · f
        // (the Markov context of position pos − 1)
        let rk = dr.rank;
        let ws = 2 * rk + 2 * hidden;
        let w_h = dr.rnn_w.ptr + ((2 * rk) * 4) as u64;
        let w_f = dr.rnn_w.ptr + ((2 * rk + hidden) * 4) as u64;
        c.gemm(true, false, 3 * rk, k, hidden, 1.0, w_h, ws, dr.hf.ptr + (hidden * 4) as u64, hidden, 0.0, dr.ch.ptr, 3 * rk, Gemm::F32)?;
        let fp = dr.fr.ptr + ((((pos - 1) % FR) * hidden) * 4) as u64;
        c.gemm(true, false, 3 * rk, 1, hidden, 1.0, w_f, ws, fp, hidden, 0.0, dr.cf.ptr, 3 * rk, Gemm::F32)?;
        let (ws_i, rk_i, v_i) = (ws as i32, rk as i32, vocab as i32);
        let lpl = Planes { p0: dr.latp[0].ptr, p1: dr.latp[1].ptr, p2: dr.latp[1].ptr, stride: rk };
        for i in 0..k {
            let chi = dr.ch.ptr + ((i * 3 * rk) * 4) as u64;
            c.launch(f.ds_markov, (1, 1), (3 * rk) as u32, 5 * rk * 4, kargs!(chi, dr.cf.ptr, dr.rnn_b.ptr, dr.rnn_w.ptr, ws_i, rk_i, dr.state.ptr, dr.prev.ptr, dr.w1.ptr, dr.latp[0].ptr, dr.latp[1].ptr))?;
            dr.folds[i].run(c, &d.hfx, &lpl, rk, 1)?;
            let lg = dr.dlog.ptr + ((i * vocab) * 4) as u64;
            let i_i = i as i32;
            c.launch(f.ds_pick, (1, 1), 1024, 0, kargs!(lg, dr.fold_b.ptr, v_i, i_i, dr.ids.ptr, dr.prev.ptr))?;
        }
        let mut ids = vec![0i32; k];
        cu::memcpy_dtoh_async(&mut ids, dr.ids.ptr, c.stream).map_err(derr)?;
        c.sync()?;
        let round = DS_ROUND.fetch_add(1, Ordering::Relaxed);
        if let Some(dir) = ds_dump() {
            let want = std::env::var("CMF_INKLING_DS_DUMP_ROUND").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(0);
            if round == want && !DS_DUMPED.swap(true, Ordering::Relaxed) {
                let mut hf = vec![0f32; b * hidden];
                let mut lg = vec![0f32; k * vocab];
                cu::memcpy_dtoh_async(&mut hf, dr.hf.ptr, c.stream).map_err(derr)?;
                cu::memcpy_dtoh_async(&mut lg, dr.dlog.ptr, c.stream).map_err(derr)?;
                c.sync()?;
                let bytes = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
                let _ = std::fs::write(format!("{dir}/h.bin"), bytes(&hf));
                let _ = std::fs::write(format!("{dir}/logits.bin"), bytes(&lg));
                let _ = std::fs::write(format!("{dir}/round.json"), format!("{{\"anchor\": {anchor}, \"pos\": {pos}, \"k\": {k}, \"ids\": {ids:?}}}"));
                tracing::info!("inkling2_loop: the drafter's first round dumped into {dir}");
            }
        }
        Ok(ids.into_iter().map(|v| v as u32).collect())
    }
}

/// `CMF_INKLING_DS_DUMP=dir` (a check, not a run): every call's drafter taps
/// (`taps.bin`, `[tap][rows][hidden]` f32 a call; `taps.idx` a line `pos0 n`
/// a call) until draft round `CMF_INKLING_DS_DUMP_ROUND` (0: the first), then
/// that round's normed block rows
/// (`h.bin`), its drafts' logits before the bias (`logits.bin`) and
/// `round.json`.
fn ds_dump() -> Option<&'static str> {
    static D: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
    D.get_or_init(|| std::env::var("CMF_INKLING_DS_DUMP").ok().filter(|v| !v.is_empty())).as_deref()
}

static DS_DUMPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static DS_ROUND: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

unsafe fn ds_dump_taps(c: &Ctx, d: &Dev, cfg: &Cfg, n: usize, pos0: usize) -> Res<()> {
    let Some(dir) = ds_dump() else { return Ok(()) };
    let Some(dr) = &d.draft else { return Ok(()) };
    if DS_DUMPED.load(Ordering::Relaxed) {
        return Ok(());
    }
    use std::io::Write;
    let hidden = cfg.dim;
    let nt = dr.taps.len() + 1;
    let mut v = vec![0f32; nt * n * hidden];
    unsafe {
        for k in 0..nt {
            cu::memcpy_dtoh_async(&mut v[k * n * hidden..(k + 1) * n * hidden], dr.tap.ptr + ((k * d.rows * hidden) * 4) as u64, c.stream).map_err(derr)?;
        }
    }
    c.sync()?;
    let _ = std::fs::create_dir_all(dir);
    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(format!("{dir}/taps.bin")).map_err(|e| e.to_string())?;
    f.write_all(&v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>()).map_err(|e| e.to_string())?;
    let mut ix = std::fs::OpenOptions::new().create(true).append(true).open(format!("{dir}/taps.idx")).map_err(|e| e.to_string())?;
    writeln!(ix, "{pos0} {n}").map_err(|e| e.to_string())?;
    Ok(())
}

/// The rings of every application saved before a draft verify.
pub(crate) fn ring_snap(id: u64) -> bool {
    let Some(c) = super::super::ctx() else { return false };
    let guard = DEVICES.lock().unwrap();
    let Some(d) = guard.as_ref().and_then(|m| m.get(&id)) else { return false };
    let maxw = (d.slots.first().map_or(0, |s| s.hist[2].bytes / 4 / NMAX)) as u32;
    unsafe { c.launch(d.fx.ring_snap, (maxw.div_ceil(256), d.nrings as u32), 256, 0, kargs!(d.rings_tab.ptr)).is_ok() && c.sync().is_ok() }
}

/// The rings put back as they stand after the verify call's first `r` rows.
pub(crate) fn ring_back(id: u64, r: usize) -> bool {
    let Some(c) = super::super::ctx() else { return false };
    let guard = DEVICES.lock().unwrap();
    let Some(d) = guard.as_ref().and_then(|m| m.get(&id)) else { return false };
    let maxw = (d.slots.first().map_or(0, |s| s.hist[2].bytes / 4 / NMAX)) as u32;
    let r_i = r as i32;
    unsafe { c.launch(d.fx.ring_back, (maxw.div_ceil(256), d.nrings as u32), 256, 0, kargs!(d.rings_tab.ptr, r_i)).is_ok() && c.sync().is_ok() }
}

/// The head over rows `r0 .. r0 + m` of the final mixture (`m` ≤ `NMAX`):
/// the norm, the logits into `logits`, the softcap.
unsafe fn head_rows(c: &Ctx, d: &Dev, cfg: &Cfg, r0: usize, m: usize, vocab: usize) -> Res<()> {
    let f = &d.fx;
    let hidden = cfg.dim;
    let fin = d.fin.ptr + (r0 * hidden * 4) as u64;
    let (nul, hs) = (0u64, hidden as i32);
    unsafe {
        c.launch(f.rms, (m as u32, 1), 256, 0, kargs!(fin, d.final_norm.ptr, cfg.eps as f32, nul, d.pf[0].ptr, d.pf[1].ptr, hs))?;
        let pl = Planes { p0: d.pf[0].ptr, p1: d.pf[1].ptr, p2: d.pf[1].ptr, stride: hidden };
        d.head.run(c, &d.hfx, &pl, hidden, m)?;
        let (v_i, cap) = (vocab as i32, cfg.logit_cap);
        if cap > 0.0 {
            c.launch(f.softcap, (vocab.div_ceil(256) as u32, m as u32), 256, 0, kargs!(d.logits.ptr, v_i, cap))?;
        }
    }
    Ok(())
}

/// One layer application of the call's rows: `hin` the running sums in,
/// `hout` out; `nb` the block states the rows hold (a boundary layer adds one).
#[allow(clippy::too_many_arguments)]
unsafe fn app(c: &Ctx, d: &Dev, cfg: &Cfg, l: &LayerD, s: &SlotD, li: usize, pass: usize, n: usize, hin: u64, hout: u64, nb: &mut usize, npre: usize, bank_nb: usize) -> Res<()> {
    let f = &d.fx;
    let hidden = cfg.dim;
    let rows = d.rows;
    let ost = (rows * hidden) as i32;
    let bst = (MAXB * hidden) as i32;
    let (ni, nu) = (n as i32, n as u32);
    let eps = cfg.eps as f32;
    let hs = hidden as i32;
    let fl = |b: &Buf, i: usize| b.ptr + (i * rows * hidden * 4) as u64;
    let mut tp = std::time::Instant::now();
    unsafe {
        // 1. the attention inputs (a decode call: the mix and, when no gate
        // follows, query 0's norm in one launch)
        let gates = if pass > 0 { l.gates.as_ref() } else { None };
        let one = l.sliding && gates.is_none();
        let fuse = fuse_on();
        let mut normed = false;
        let mut inp = [hin, hin, hin];
        if let Some((aq, nq)) = &l.aq {
            let nb_i = *nb as i32;
            if fuse {
                let (nw, xo, p0, p1) = if one { (l.norms[0].ptr, d.x[0].ptr, d.xp[0][0].ptr, d.xp[0][1].ptr) } else { (0u64, 0u64, 0u64, 0u64) };
                c.launch(f.mix2, (*nq as u32, nu), mix_tpb(hidden), 0, kargs!(d.blk.ptr, nb_i, bst, hin, aq.ptr, d.in3.ptr, ost, nw, eps, xo, p0, p1, hs))?;
                normed = one;
            } else {
                c.launch(f.mix, (*nq as u32, nu), 256, 0, kargs!(d.blk.ptr, nb_i, bst, hin, aq.ptr, d.in3.ptr, ost))?;
            }
            inp = if *nq == 3 { [fl(&d.in3, 0), fl(&d.in3, 1), fl(&d.in3, 2)] } else { [fl(&d.in3, 0); 3] };
        }
        st(c, 0, &mut tp)?;
        // 2. the messages of a later pass, gated into q, k, v
        if let Some(gs) = gates {
            let i = li - cfg.core_start;
            let q = d.msg_q.ptr + (i * 4 * hidden * 4) as u64;
            let bnb = bank_nb as i32;
            let bank = d.bank.ptr + ((npre + 1) * hidden * 4) as u64;
            if fuse {
                let nul = 0u64;
                c.launch(f.mix2, (4, nu), mix_tpb(hidden), 0, kargs!(bank, bnb, bst, d.bank_out.ptr, q, d.msg.ptr, ost, nul, eps, nul, nul, nul, hs))?;
            } else {
                c.launch(f.mix, (4, nu), 256, 0, kargs!(bank, bnb, bst, d.bank_out.ptr, q, d.msg.ptr, ost))?;
            }
            let r = gs[0].down.bytes / (2 * hidden * 4);
            if fuse && gs[..3].iter().all(|g| g.down.bytes / (2 * hidden * 4) == r) {
                // the three gates' halves a launch each
                let r_i = r as i32;
                let (m0, m1, m2) = (fl(&d.msg, 0), fl(&d.msg, 1), fl(&d.msg, 2));
                let (o0, o1, o2) = (fl(&d.gin, 0), fl(&d.gin, 1), fl(&d.gin, 2));
                c.launch_3d(f.gd3, (r as u32, nu, 3), 256, 0, kargs!(inp[0], inp[1], inp[2], m0, m1, m2, gs[0].down.ptr, gs[1].down.ptr, gs[2].down.ptr, r_i, eps, d.gd.ptr))?;
                c.launch_3d(
                    f.go3,
                    (hidden.div_ceil(8) as u32, nu, 3),
                    256,
                    0,
                    kargs!(inp[0], inp[1], inp[2], m0, m1, m2, d.gd.ptr, gs[0].forget.ptr, gs[1].forget.ptr, gs[2].forget.ptr, gs[0].gain.ptr, gs[1].gain.ptr, gs[2].gain.ptr, r_i, o0, o1, o2),
                )?;
                inp = [o0, o1, o2];
            } else {
                for j in 0..3 {
                    gate(c, f, &gs[j], inp[j], fl(&d.msg, j), d.gd.ptr, fl(&d.gin, j), n, hidden, eps)?;
                    inp[j] = fl(&d.gin, j);
                }
            }
        }
        st(c, 1, &mut tp)?;
        // 3. the input norms (a local layer's three are one weight; without
        // messages its inputs are one row)
        let cnt = if one { 1 } else { 3 };
        if fuse {
            if !normed {
                let th = (hidden / 4).div_ceil(32) * 32;
                let (x, w, p) = (&d.x, &l.norms, &d.xp);
                c.launch(
                    f.rms3,
                    (nu, cnt as u32),
                    th as u32,
                    0,
                    kargs!(inp[0], w[0].ptr, x[0].ptr, p[0][0].ptr, p[0][1].ptr, inp[1], w[1].ptr, x[1].ptr, p[1][0].ptr, p[1][1].ptr, inp[2], w[2].ptr, x[2].ptr, p[2][0].ptr, p[2][1].ptr, eps, hs),
                )?;
            }
        } else {
            for j in 0..cnt {
                c.launch(f.rms, (nu, 1), 256, 0, kargs!(inp[j], l.norms[j].ptr, eps, d.x[j].ptr, d.xp[j][0].ptr, d.xp[j][1].ptr, hs))?;
            }
        }
        let (xk, xv) = if one { (0, 0) } else { (1, 2) };
        let pl = |j: usize| Planes { p0: d.xp[j][0].ptr, p1: d.xp[j][1].ptr, p2: d.xp[j][1].ptr, stride: hidden };
        st(c, 2, &mut tp)?;
        // 4. the projections
        match (&l.qkv, one) {
            (Some(all), true) => all.run(c, &d.hfx, &pl(0), hidden, n)?,
            // k's and v's input planes follow q's (`xpb`)
            _ if fuse => l.qkv3.run(c, &d.hfx, &pl(0), hidden, n)?,
            _ => {
                l.qset.run(c, &d.hfx, &pl(0), hidden, n)?;
                l.kset.run(c, &d.hfx, &pl(xk), hidden, n)?;
                l.vset.run(c, &d.hfx, &pl(xv), hidden, n)?;
            }
        }
        let nh = cfg.nh;
        let (nh_i, kp_i) = (nh as i32, (cfg.nkv * 4) as i32);
        let (mut dk, mut dv) = (0u64, 0u64);
        let q2 = fuse && qrkv2_on();
        if fuse && !q2 {
            // the sinks and the dynamic convolution weights in one launch
            let (wk, wv, kr) = match (&l.dk, &l.dv) {
                (Some(wk), Some(wv)) => {
                    dk = d.dkb.ptr;
                    dv = d.dvb.ptr;
                    (wk.ptr, wv.ptr, kp_i)
                }
                _ => (0u64, 0u64, 0i32),
            };
            let tot = nh + 2 * kr as usize;
            c.launch(f.fmv3, (tot as u32, nu), 192, 0, kargs!(l.sink.ptr, nh_i, d.x[0].ptr, d.sk.ptr, wk, kr, d.x[xk].ptr, d.dkb.ptr, wv, kr, d.x[xv].ptr, d.dvb.ptr))?;
        } else if !fuse {
            c.launch(f.fmv, (nh.div_ceil(8) as u32, nu), 256, 0, kargs!(l.sink.ptr, nh_i, d.x[0].ptr, d.sk.ptr))?;
            if let (Some(wk), Some(wv)) = (&l.dk, &l.dv) {
                c.launch(f.fmv, ((cfg.nkv * 4).div_ceil(8) as u32, nu), 256, 0, kargs!(wk.ptr, kp_i, d.x[xk].ptr, d.dkb.ptr))?;
                c.launch(f.fmv, ((cfg.nkv * 4).div_ceil(8) as u32, nu), 256, 0, kargs!(wv.ptr, kp_i, d.x[xv].ptr, d.dvb.ptr))?;
                dk = d.dkb.ptr;
                dv = d.dvb.ptr;
            }
        }
        st(c, 3, &mut tp)?;
        // 5. queries and relative states; keys and values into the cache
        let full = !l.sliding as i32;
        let (alpha, floor) = (cfg.log_alpha as f32, cfg.log_floor as f32);
        let ring = s.ring as i32;
        if fuse && !q2 {
            c.launch(
                f.qrkv,
                ((nh * n + 2 * cfg.nkv) as u32, 1),
                cfg.hd as u32,
                0,
                kargs!(
                    d.yq.ptr, d.yr.ptr, l.q_scale.ptr, l.rel_scale.ptr, cfg.rel_clip, full, alpha, floor, d.yk.ptr, d.yv.ptr, dk, dv, l.tk.ptr, l.tv.ptr, s.rings[0].ptr, s.rings[1].ptr, s.k.ptr,
                    s.v.ptr, ring, ni, cfg.qk_clip, eps, d.cr.ptr, s.hist[0].ptr, s.hist[1].ptr
                ),
            )?;
        } else if fuse {
            // queries, keys, values, the sinks and the per-token taps in one launch
            let (wdk, wdv) = match (&l.dk, &l.dv) {
                (Some(wk), Some(wv)) => (wk.ptr, wv.ptr),
                _ => (0u64, 0u64),
            };
            c.launch(
                f.qrkv2,
                ((nh * n + 2 * cfg.nkv) as u32, 1),
                cfg.hd as u32,
                0,
                kargs!(
                    d.yq.ptr, d.yr.ptr, l.q_scale.ptr, l.rel_scale.ptr, cfg.rel_clip, full, alpha, floor, d.yk.ptr, d.yv.ptr, l.tk.ptr, l.tv.ptr, s.rings[0].ptr, s.rings[1].ptr, s.k.ptr, s.v.ptr,
                    ring, ni, cfg.qk_clip, eps, d.cr.ptr, s.hist[0].ptr, s.hist[1].ptr, l.sink.ptr, d.x[0].ptr, d.sk.ptr, wdk, d.x[xk].ptr, wdv, d.x[xv].ptr
                ),
            )?;
        } else {
            c.launch(f.qr, (nh as u32, nu), cfg.hd as u32, 0, kargs!(d.yq.ptr, d.yr.ptr, l.q_scale.ptr, l.rel_scale.ptr, cfg.qk_clip, cfg.rel_clip, full, alpha, floor, d.cr.ptr))?;
            c.launch(
                f.kv,
                (cfg.nkv as u32, 2),
                cfg.hd as u32,
                0,
                kargs!(d.yk.ptr, d.yv.ptr, dk, dv, l.tk.ptr, l.tv.ptr, s.rings[0].ptr, s.rings[1].ptr, s.k.ptr, s.v.ptr, ring, ni, cfg.qk_clip, eps, d.cr.ptr, s.hist[0].ptr, s.hist[1].ptr),
            )?;
        }
        st(c, 4, &mut tp)?;
        // 6. the attention, its gate, the O projection
        let (ext, scale) = (l.extent as i32, 1.0f32 / (cfg.hd as f32).sqrt());
        let win = if s.ring > 0 { cfg.window as i32 } else { 0 };
        if split_on() {
            // the tiles of the longest span the slot holds: a recorded call
            // replays at any position
            let tiles = if s.ring > 0 { cfg.window } else { d.cap }.div_ceil(ATILE);
            let t_i = tiles as i32;
            c.launch_3d(
                f.attn_split,
                (nh as u32, nu, tiles as u32),
                256,
                0,
                kargs!(d.yq.ptr, d.yr.ptr, l.rel_table.ptr, ext, s.k.ptr, s.v.ptr, ring, win, scale, d.part.ptr, t_i, d.cr.ptr),
            )?;
            if fuse {
                // the output gate in the merge's epilogue
                let qs_i = (nh * cfg.hd) as i32;
                c.launch(f.merge_g, (nh as u32, nu), cfg.hd as u32, 0, kargs!(d.part.ptr, t_i, d.sk.ptr, win, d.att.ptr, d.cr.ptr, d.yg.ptr, d.po[0].ptr, d.po[1].ptr, qs_i))?;
            } else {
                c.launch(f.attn_merge, (nh as u32, nu), cfg.hd as u32, 0, kargs!(d.part.ptr, t_i, d.sk.ptr, win, d.att.ptr, d.cr.ptr))?;
            }
        } else {
            c.launch(f.attn, (nh as u32, nu), 256, 0, kargs!(d.yq.ptr, d.yr.ptr, d.sk.ptr, l.rel_table.ptr, ext, s.k.ptr, s.v.ptr, ring, win, scale, d.att.ptr, d.cr.ptr))?;
        }
        st(c, 5, &mut tp)?;
        let qs = nh * cfg.hd;
        let qs_i = qs as i32;
        if !(fuse && split_on()) {
            c.launch(f.ogate, (qs.div_ceil(256) as u32, nu), 256, 0, kargs!(d.att.ptr, d.yg.ptr, d.po[0].ptr, d.po[1].ptr, qs_i))?;
        }
        let po = Planes { p0: d.po[0].ptr, p1: d.po[1].ptr, p2: d.po[1].ptr, stride: qs };
        l.oset.run(c, &d.hfx, &po, qs, n)?;
        st(c, 6, &mut tp)?;
        // 7. the output convolution; a boundary closes the running sum into a block
        let bslot = if l.boundary { *nb as i32 } else { -1 };
        let hb = hidden.div_ceil(256) as u32;
        // a decode row: the post and the MoE input's mix (and norm) in one block
        let pm = fuse && n == 1 && postmix_on();
        if !pm {
            c.launch(f.post, (hb, 1), 256, 0, kargs!(d.ya.ptr, l.tpa.ptr, s.rings[2].ptr, hin, d.blk.ptr, bslot, bst, d.r.ptr, ni, s.hist[2].ptr))?;
        }
        if l.boundary {
            *nb += 1;
        }
        st(c, 7, &mut tp)?;
        // 8. the MoE input
        let nb_i = *nb as i32;
        if pm {
            let (nw, xo, p0, p1) = if gates.is_none() { (l.post_norm.ptr, d.xm.ptr, d.pm[0].ptr, d.pm[1].ptr) } else { (0u64, 0u64, 0u64, 0u64) };
            c.launch(f.post_mix, (1, 1), mix_tpb(hidden), 0, kargs!(d.ya.ptr, l.tpa.ptr, s.rings[2].ptr, hin, d.blk.ptr, bslot, bst, d.r.ptr, s.hist[2].ptr, nb_i, l.mq.ptr, d.m.ptr, ost, nw, eps, xo, p0, p1, hs))?;
        }
        if fuse && gates.is_none() {
            // the MoE input's mix and its norm in one launch
            if !pm {
                c.launch(f.mix2, (1, nu), mix_tpb(hidden), 0, kargs!(d.blk.ptr, nb_i, bst, d.r.ptr, l.mq.ptr, d.m.ptr, ost, l.post_norm.ptr, eps, d.xm.ptr, d.pm[0].ptr, d.pm[1].ptr, hs))?;
            }
        } else {
            if pm {
            } else if fuse {
                let nul = 0u64;
                c.launch(f.mix2, (1, nu), mix_tpb(hidden), 0, kargs!(d.blk.ptr, nb_i, bst, d.r.ptr, l.mq.ptr, d.m.ptr, ost, nul, eps, nul, nul, nul, hs))?;
            } else {
                c.launch(f.mix, (1, nu), 256, 0, kargs!(d.blk.ptr, nb_i, bst, d.r.ptr, l.mq.ptr, d.m.ptr, ost))?;
            }
            let mut mi = d.m.ptr;
            if let Some(gs) = gates {
                if fuse {
                    let r = gs[3].down.bytes / (2 * hidden * 4);
                    let r_i = r as i32;
                    let (m3, g3) = (fl(&d.msg, 3), &gs[3]);
                    c.launch_3d(f.gd3, (r as u32, nu, 1), 256, 0, kargs!(mi, mi, mi, m3, m3, m3, g3.down.ptr, g3.down.ptr, g3.down.ptr, r_i, eps, d.gd.ptr))?;
                    c.launch_3d(
                        f.go3,
                        (hidden.div_ceil(8) as u32, nu, 1),
                        256,
                        0,
                        kargs!(mi, mi, mi, m3, m3, m3, d.gd.ptr, g3.forget.ptr, g3.forget.ptr, g3.forget.ptr, g3.gain.ptr, g3.gain.ptr, g3.gain.ptr, r_i, d.mg.ptr, d.mg.ptr, d.mg.ptr),
                    )?;
                } else {
                    gate(c, f, &gs[3], mi, fl(&d.msg, 3), d.gd.ptr, d.mg.ptr, n, hidden, eps)?;
                }
                mi = d.mg.ptr;
            }
            if fuse {
                let th = (hidden / 4).div_ceil(32) * 32;
                let (x, p, w) = (d.xm.ptr, &d.pm, l.post_norm.ptr);
                c.launch(f.rms3, (nu, 1), th as u32, 0, kargs!(mi, w, x, p[0].ptr, p[1].ptr, mi, w, x, p[0].ptr, p[1].ptr, mi, w, x, p[0].ptr, p[1].ptr, eps, hs))?;
            } else {
                c.launch(f.rms, (nu, 1), 256, 0, kargs!(mi, l.post_norm.ptr, eps, d.xm.ptr, d.pm[0].ptr, d.pm[1].ptr, hs))?;
            }
        }
        st(c, 8, &mut tp)?;
        // 9. the routed experts (fused: their weighted sum left to the post)
        let si = moe(c, d, cfg, l, n, &mut tp, fuse)?;
        st(c, 9, &mut tp)?;
        // 10. the output convolution onto the running sum
        let (nul, m1) = (0u64, -1i32);
        if fuse {
            c.launch(f.post_mx, (hb, 1), 256, 0, kargs!(d.dns.ptr, d.wsel.ptr, si, l.tpm.ptr, s.rings[3].ptr, d.r.ptr, hout, ni, s.hist[3].ptr))?;
        } else {
            c.launch(f.post, (hb, 1), 256, 0, kargs!(d.y.ptr, l.tpm.ptr, s.rings[3].ptr, d.r.ptr, nul, m1, bst, hout, ni, s.hist[3].ptr))?;
        }
        st(c, 7, &mut tp)?;
    }
    Ok(())
}

/// One layer application of a prompt call (more than `NMAX` rows): `app`'s
/// stages with the weights as cuBLAS GEMMs (`wmul`), the convolutions a row a
/// block (their rings moved on after the call) and the routed experts grouped
/// by expert (`moe_big`).
#[allow(clippy::too_many_arguments)]
unsafe fn app_big(c: &Ctx, d: &Dev, b: &Big, cfg: &Cfg, l: &LayerD, s: &SlotD, li: usize, pass: usize, n: usize, hin: u64, hout: u64, nb: &mut usize, npre: usize, bank_nb: usize) -> Res<()> {
    let f = &d.fx;
    let fx = &d.hfx;
    let hidden = cfg.dim;
    let rows = d.rows;
    let ost = (rows * hidden) as i32;
    let bst = (MAXB * hidden) as i32;
    let (ni, nu) = (n as i32, n as u32);
    let eps = cfg.eps as f32;
    let hs = hidden as i32;
    let (nh, nkv, hd) = (cfg.nh, cfg.nkv, cfg.hd);
    let (qs, kvs, rs) = (nh * hd, nkv * hd, nh * cfg.d_rel);
    let fl = |bb: &Buf, i: usize| bb.ptr + (i * rows * hidden * 4) as u64;
    let h16 = |p0: u64, p1: u64, out: u64, width: usize| -> Res<()> {
        let tot = n * width;
        let tot_i = tot as i32;
        unsafe { c.launch(f.h16, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(p0, p1, out, tot_i)) }
    };
    let ring = |y: u64, r: &Buf, width: usize| -> Res<()> {
        let w_i = width as i32;
        unsafe { c.launch(f.ring_rows, (width.div_ceil(256) as u32, 1), 256, 0, kargs!(y, r.ptr, w_i, ni)) }
    };
    let mut tp = std::time::Instant::now();
    unsafe {
        // 1. the attention inputs
        let mut inp = [hin, hin, hin];
        if let Some((aq, nq)) = &l.aq {
            let nb_i = *nb as i32;
            if fuse_on() {
                let nul = 0u64;
                c.launch(f.mix2, (*nq as u32, nu), mix_tpb(hidden), 0, kargs!(d.blk.ptr, nb_i, bst, hin, aq.ptr, d.in3.ptr, ost, nul, eps, nul, nul, nul, hs))?;
            } else {
                c.launch(f.mix, (*nq as u32, nu), 256, 0, kargs!(d.blk.ptr, nb_i, bst, hin, aq.ptr, d.in3.ptr, ost))?;
            }
            inp = if *nq == 3 { [fl(&d.in3, 0), fl(&d.in3, 1), fl(&d.in3, 2)] } else { [fl(&d.in3, 0); 3] };
        }
        st(c, 0, &mut tp)?;
        // 2. the messages of a later pass, gated into q, k, v
        let gates = if pass > 0 { l.gates.as_ref() } else { None };
        if let Some(gs) = gates {
            let i = li - cfg.core_start;
            let q = d.msg_q.ptr + (i * 4 * hidden * 4) as u64;
            let bnb = bank_nb as i32;
            let bank = d.bank.ptr + ((npre + 1) * hidden * 4) as u64;
            if fuse_on() {
                let nul = 0u64;
                c.launch(f.mix2, (4, nu), mix_tpb(hidden), 0, kargs!(bank, bnb, bst, d.bank_out.ptr, q, d.msg.ptr, ost, nul, eps, nul, nul, nul, hs))?;
            } else {
                c.launch(f.mix, (4, nu), 256, 0, kargs!(bank, bnb, bst, d.bank_out.ptr, q, d.msg.ptr, ost))?;
            }
            for j in 0..3 {
                gate_big(c, f, b, &gs[j], inp[j], fl(&d.msg, j), d.gd.ptr, fl(&d.gin, j), n, hidden, eps)?;
                inp[j] = fl(&d.gin, j);
            }
        }
        st(c, 1, &mut tp)?;
        // 3. the input norms and their f16 rows
        let one = l.sliding && gates.is_none();
        let th = ((hidden / 4).div_ceil(32) * 32) as u32;
        for j in 0..(if one { 1 } else { 3 }) {
            if hidden % 4 == 0 && th <= 1024 {
                // the f16 rows straight from the norm
                c.launch(f.rms_h, (nu, 1), th, 0, kargs!(inp[j], l.norms[j].ptr, eps, d.x[j].ptr, b.x16[j].ptr))?;
            } else {
                c.launch(f.rms, (nu, 1), 256, 0, kargs!(inp[j], l.norms[j].ptr, eps, d.x[j].ptr, d.xp[j][0].ptr, d.xp[j][1].ptr, hs))?;
                h16(d.xp[j][0].ptr, d.xp[j][1].ptr, b.x16[j].ptr, hidden)?;
            }
        }
        let (xk, xv) = if one { (0, 0) } else { (1, 2) };
        st(c, 2, &mut tp)?;
        // 4. the projections
        let [wq, wg, wr, wk, wv, wo] = &l.dense;
        wmul(c, fx, b, wq, b.x16[0].ptr, d.yq.ptr, qs, n)?;
        wmul(c, fx, b, wg, b.x16[0].ptr, d.yg.ptr, qs, n)?;
        wmul(c, fx, b, wr, b.x16[0].ptr, d.yr.ptr, rs, n)?;
        wmul(c, fx, b, wk, b.x16[xk].ptr, d.yk.ptr, kvs, n)?;
        wmul(c, fx, b, wv, b.x16[xv].ptr, d.yv.ptr, kvs, n)?;
        let (nh_i, kp_i) = (nh as i32, (nkv * 4) as i32);
        c.launch(f.fmv, (nh.div_ceil(8) as u32, nu), 256, 0, kargs!(l.sink.ptr, nh_i, d.x[0].ptr, d.sk.ptr))?;
        let (mut dk, mut dv) = (0u64, 0u64);
        if let (Some(wdk), Some(wdv)) = (&l.dk, &l.dv) {
            c.launch(f.fmv, ((nkv * 4).div_ceil(8) as u32, nu), 256, 0, kargs!(wdk.ptr, kp_i, d.x[xk].ptr, d.dkb.ptr))?;
            c.launch(f.fmv, ((nkv * 4).div_ceil(8) as u32, nu), 256, 0, kargs!(wdv.ptr, kp_i, d.x[xv].ptr, d.dvb.ptr))?;
            dk = d.dkb.ptr;
            dv = d.dvb.ptr;
        }
        st(c, 3, &mut tp)?;
        // 5. queries and relative states; keys and values into the cache, a row a block
        let full = !l.sliding as i32;
        let (alpha, floor) = (cfg.log_alpha as f32, cfg.log_floor as f32);
        c.launch(f.qr, (nh as u32, nu), hd as u32, 0, kargs!(d.yq.ptr, d.yr.ptr, l.q_scale.ptr, l.rel_scale.ptr, cfg.qk_clip, cfg.rel_clip, full, alpha, floor, d.cr.ptr))?;
        let ring_i = s.ring as i32;
        c.launch(
            f.kv_rows,
            ((2 * nkv) as u32, nu),
            hd as u32,
            0,
            kargs!(d.yk.ptr, d.yv.ptr, dk, dv, l.tk.ptr, l.tv.ptr, s.rings[0].ptr, s.rings[1].ptr, s.k.ptr, s.v.ptr, ring_i, cfg.qk_clip, eps, d.cr.ptr),
        )?;
        ring(d.yk.ptr, &s.rings[0], kvs)?;
        ring(d.yv.ptr, &s.rings[1], kvs)?;
        st(c, 4, &mut tp)?;
        // 6. the attention, its gate, the O projection
        let (ext, scale) = (l.extent as i32, 1.0f32 / (hd as f32).sqrt());
        let win = if s.ring > 0 { cfg.window as i32 } else { 0 };
        if attn_gemm_on() && flash_on() && hd == 128 && cfg.d_rel == 16 && nh % cfg.nkv == 0 {
            // the queries as f16 rows, then the flash kernel (no scores stored)
            let (tot_i, n_i, ring_i) = ((n * nh * hd) as i32, n as i32, s.ring as i32);
            c.launch(f.f16, ((n * nh * hd).div_ceil(256) as u32, 1), 256, 0, kargs!(d.yq.ptr, b.q16.ptr, tot_i))?;
            c.launch(f.attn_flash, (n.div_ceil(64) as u32, nh as u32), 128, 0, kargs!(b.q16.ptr, d.yr.ptr, d.sk.ptr, l.rel_tb.ptr, ext, s.k.ptr, s.v.ptr, ring_i, win, scale, n_i, d.cr.ptr, d.att.ptr))?;
        } else if attn_gemm_on() {
            attn_gemm(c, d, b, cfg, l, s, n, ext, win, scale)?;
        } else {
            c.launch(f.attn, (nh as u32, nu), 256, 0, kargs!(d.yq.ptr, d.yr.ptr, d.sk.ptr, l.rel_table.ptr, ext, s.k.ptr, s.v.ptr, ring_i, win, scale, d.att.ptr, d.cr.ptr))?;
        }
        st(c, 5, &mut tp)?;
        c.launch(f.ogate_h, (qs.div_ceil(256) as u32, nu), 256, 0, kargs!(d.att.ptr, d.yg.ptr, b.o16.ptr))?;
        wmul(c, fx, b, wo, b.o16.ptr, d.ya.ptr, hidden, n)?;
        st(c, 6, &mut tp)?;
        // 7. the output convolution; a boundary closes the running sum into a block
        let bslot = if l.boundary { *nb as i32 } else { -1 };
        let hb = hidden.div_ceil(256) as u32;
        c.launch(f.post_rows, (hb, nu), 256, 0, kargs!(d.ya.ptr, l.tpa.ptr, s.rings[2].ptr, hin, d.blk.ptr, bslot, bst, d.r.ptr))?;
        ring(d.ya.ptr, &s.rings[2], hidden)?;
        if l.boundary {
            *nb += 1;
        }
        st(c, 7, &mut tp)?;
        // 8. the MoE input
        let nb_i = *nb as i32;
        if fuse_on() {
            let nul = 0u64;
            c.launch(f.mix2, (1, nu), mix_tpb(hidden), 0, kargs!(d.blk.ptr, nb_i, bst, d.r.ptr, l.mq.ptr, d.m.ptr, ost, nul, eps, nul, nul, nul, hs))?;
        } else {
            c.launch(f.mix, (1, nu), 256, 0, kargs!(d.blk.ptr, nb_i, bst, d.r.ptr, l.mq.ptr, d.m.ptr, ost))?;
        }
        let mut mi = d.m.ptr;
        if let Some(gs) = gates {
            gate_big(c, f, b, &gs[3], mi, fl(&d.msg, 3), d.gd.ptr, d.mg.ptr, n, hidden, eps)?;
            mi = d.mg.ptr;
        }
        let nul = 0u64;
        c.launch(f.rms, (nu, 1), 256, 0, kargs!(mi, l.post_norm.ptr, eps, d.xm.ptr, nul, nul, hs))?;
        st(c, 8, &mut tp)?;
        // 9. the routed experts into y
        moe_big(c, d, b, cfg, l, n, &mut tp)?;
        st(c, 13, &mut tp)?;
        // 10. the output convolution onto the running sum
        let m1 = -1i32;
        c.launch(f.post_rows, (hb, nu), 256, 0, kargs!(d.y.ptr, l.tpm.ptr, s.rings[3].ptr, d.r.ptr, nul, m1, bst, hout))?;
        ring(d.y.ptr, &s.rings[3], hidden)?;
        st(c, 7, &mut tp)?;
    }
    Ok(())
}

/// A prompt call's attention through cuBLAS: the queries as f16 rows, per KV
/// group S = Q·Kᵀ over the slots the call reads (a local layer's whole ring,
/// a full layer's positions to the call's last), `ink_attn_soft` (scale,
/// relative bias, window, ring positions, sink, softmax), O = P·V into `att`;
/// rows in chunks whose scores fit `ATT_SCORES`.
#[allow(clippy::too_many_arguments)]
unsafe fn attn_gemm(c: &Ctx, d: &Dev, b: &Big, cfg: &Cfg, l: &LayerD, s: &SlotD, n: usize, ext: i32, win: i32, scale: f32) -> Res<()> {
    let f = &d.fx;
    let (nh, nkv, hd) = (cfg.nh, cfg.nkv, cfg.hd);
    let hpk = nh / nkv;
    let (qs, kvs) = (nh * hd, nkv * hd);
    let nk = if s.ring > 0 { s.ring } else { d.big_pos0.get() + n };
    let chunk = (ATT_SCORES / (nh * nk * 4)).clamp(1, n);
    let (tot_i, nk_i, ring_i, n_i) = ((n * qs) as i32, nk as i32, s.ring as i32, n as i32);
    unsafe {
        c.launch(f.f16, ((n * qs).div_ceil(256) as u32, 1), 256, 0, kargs!(d.yq.ptr, b.q16.ptr, tot_i))?;
        let mut r0 = 0usize;
        while r0 < n {
            let rows = chunk.min(n - r0);
            for g in 0..nkv {
                let kp = s.k.ptr + (g * hd * 2) as u64;
                let qp = b.q16.ptr + ((r0 * qs + g * hpk * hd) * 2) as u64;
                let sp = b.sc.ptr + ((g * hpk * rows * nk) * 4) as u64;
                gemm_batched_h(c, true, nk, rows, hd, 1.0, kp, kvs, 0, qp, qs, hd, sp, nk, rows * nk, hpk)?;
            }
            let (rows_i, r0_i) = (rows as i32, r0 as i32);
            c.launch(
                f.attn_soft,
                (rows as u32, nh as u32),
                256,
                0,
                kargs!(b.sc.ptr, b.pr.ptr, d.yr.ptr, d.sk.ptr, l.rel_table.ptr, ext, nk_i, ring_i, win, scale, rows_i, r0_i, n_i, d.cr.ptr),
            )?;
            for g in 0..nkv {
                let vp = s.v.ptr + (g * hd * 2) as u64;
                let pp = b.pr.ptr + ((g * hpk * rows * nk) * 2) as u64;
                let op = d.att.ptr + ((r0 * qs + g * hpk * hd) * 4) as u64;
                gemm_batched_h(c, false, hd, rows, nk, 1.0, vp, kvs, 0, pp, nk, rows * nk, op, qs, hd, hpk)?;
            }
            r0 += rows;
        }
    }
    Ok(())
}

/// `y [n][ldy] = W x` for a prompt call's rows (`x` f16 `[n][cols]`): the
/// weight expanded to f16 (whole when it fits the band, else a band of rows at
/// a time) and cuBLAS on the tensor cores, as the hybrid prompt path's `mul`.
#[allow(clippy::too_many_arguments)]
unsafe fn wmul(c: &Ctx, fx: &HFuncs, b: &Big, m: &DevMat, x: u64, y: u64, ldy: usize, n: usize) -> Res<()> {
    let (rows_i, cols_i) = (m.rows as i32, m.cols as i32);
    let wd = b.wd.ptr;
    unsafe {
        if m.kind == 6 {
            // the f16 copy kept from an earlier call, or made now while the budget lasts
            if let Some(w16) = b.wf16.borrow().get(&m.w.ptr) {
                return c.gemm(true, false, m.rows, n, m.cols, 1.0, w16.ptr, m.cols, x, m.cols, 0.0, y, ldy, Gemm::Half);
            }
            let bytes = m.rows * m.cols * 2;
            if bytes <= b.wf16_left.get() {
                if let Ok(w16) = Buf::direct(bytes + 64) {
                    let threads = (m.rows.div_ceil(16) * (m.cols / 32) * 32) as u64;
                    c.launch(fx.expand_p, (threads.div_ceil(256) as u32, 1), 256, 0, kargs!(m.w.ptr, m.aux0(), m.aux1(), w16.ptr, rows_i, cols_i))?;
                    let p = w16.ptr;
                    b.wf16_left.set(b.wf16_left.get() - bytes);
                    b.wf16.borrow_mut().insert(m.w.ptr, w16);
                    return c.gemm(true, false, m.rows, n, m.cols, 1.0, p, m.cols, x, m.cols, 0.0, y, ldy, Gemm::Half);
                }
            }
        }
        if m.kind == 6 && m.rows * m.cols <= b.wd_elems {
            let threads = (m.rows.div_ceil(16) * (m.cols / 32) * 32) as u64;
            c.launch(fx.expand_p, (threads.div_ceil(256) as u32, 1), 256, 0, kargs!(m.w.ptr, m.aux0(), m.aux1(), wd, rows_i, cols_i))?;
            return c.gemm(true, false, m.rows, n, m.cols, 1.0, wd, m.cols, x, m.cols, 0.0, y, ldy, Gemm::Half);
        }
        let tiles = m.rows.div_ceil(16);
        let band = (b.wd_elems / m.cols / 16).max(1);
        let mut t0 = 0usize;
        while t0 < tiles {
            let nt = band.min(tiles - t0);
            let r0 = t0 * 16;
            let nr = (nt * 16).min(m.rows - r0);
            let threads = (nt * (m.cols / 32) * 32) as u64;
            let (t0_i, nt_i) = (t0 as i32, nt as i32);
            if m.kind == 5 || m.kind == 15 {
                let dual_i = (m.kind == 15) as i32;
                c.launch(fx.expand_i8, (threads.div_ceil(256) as u32, 1), 256, 0, kargs!(m.w.ptr, m.aux1(), m.aux0(), wd, rows_i, cols_i, t0_i, nt_i, dual_i))?;
            } else {
                c.launch(fx.expand_pr, (threads.div_ceil(256) as u32, 1), 256, 0, kargs!(m.w.ptr, m.aux0(), m.aux1(), wd, rows_i, cols_i, t0_i, nt_i))?;
            }
            c.gemm(true, false, nr, n, m.cols, 1.0, wd, m.cols, x, m.cols, 0.0, y + (r0 * 4) as u64, ldy, Gemm::Half)?;
            t0 += nt;
        }
    }
    Ok(())
}

/// A prompt call's routed experts, grouped (the hybrid prompt path's
/// `moe_grouped`): the router as an f32 GEMM, every row's picks
/// (`hy_moe_topk`, the arithmetic of the decode select), the (row, pick)
/// entries sorted by expert and laid out as planes, one tensor-core launch over
/// every expert's gate/up pair (Inkling's activation in the epilogue) and one
/// over its down, the weighted mixture into `y`.
unsafe fn moe_big(c: &Ctx, d: &Dev, b: &Big, cfg: &Cfg, l: &LayerD, n: usize, tp: &mut std::time::Instant) -> Res<()> {
    let fx = &d.hfx;
    let (hidden, e, k, inter) = (cfg.dim, l.e, cfg.top_k, l.inter);
    let nk = n * k;
    let mma = moe_mma_on();
    let rmax = if mma { 64 } else { moe_rmax() };
    let jmax = e + nk.div_ceil(rmax);
    let (gi, tb) = if rmax == 64 { (1usize, 1u32) } else { (0, 2) };
    let (bpg, bpd) = (l.bpj_gu.div_ceil(tb), l.bpj_dn.div_ceil(tb));
    let flags = 1 | 2 | 4 | 32;
    let (n_i, e_i, k_i, nk_i, rmax_i, jmax_i, inter_i, hid_i) = (n as i32, e as i32, k as i32, nk as i32, rmax as i32, jmax as i32, inter as i32, hidden as i32);
    let (bg_i, bd_i) = (bpg as i32, bpd as i32);
    let (nul, zero) = (0u64, 0i32);
    unsafe {
        c.gemm(true, false, e, n, hidden, 1.0, l.router.ptr, hidden, d.xm.ptr, hidden, 0.0, b.lg.ptr, e, Gemm::F32)?;
        c.launch(fx.moe_topk, (n.div_ceil(8) as u32, 1), 256, 0, kargs!(b.lg.ptr, l.bias.ptr, n_i, e_i, k_i, flags, cfg.route_scale, b.pidx.ptr, b.pwt.ptr))?;
        c.launch(
            if e <= 256 && group2_on() { fx.moe_group2 } else { fx.moe_group },
            (1, 1),
            1024,
            0,
            kargs!(b.pidx.ptr, nk_i, k_i, e_i, rmax_i, jmax_i, l.gu_t.ptr, l.dn_t.ptr, b.gu_a.ptr, b.dn_a.ptr, b.pos.ptr, b.src.ptr, b.qq[0].ptr, b.qq[1].ptr, hid_i, inter_i, b.ys.ptr, bg_i, bd_i),
        )?;
        let tot = (nk * hidden) as u64;
        if mma {
            // the rows in their places as f16; gate/up (the activation in the
            // epilogue) into f16 rows, then down into ys
            let (tot_i, f) = (tot as i32, &d.fx);
            let (one, zero_i, nul) = (1i32, 0i32, 0u64);
            let mm = if mma2_on() { f.moe_mma2 } else { f.moe_mma };
            // ink_moe_mma2 reads a job's rows through the places' rows (src):
            // the call's rows as f16 once instead of every pick's copy
            let map = mma2_on() && rowmap_on();
            let rm = if map { b.src.ptr } else { nul };
            if map {
                let tn = (n * hidden) as i32;
                c.launch(f.f16, ((n * hidden).div_ceil(256) as u32, 1), 256, 0, kargs!(d.xm.ptr, b.xg[0].ptr, tn))?;
            } else {
                c.launch(f.gather16, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(d.xm.ptr, b.src.ptr, tot_i, b.xg[0].ptr))?;
            }
            st(c, 11, tp)?;
            let gx = ((2 * inter).div_ceil(16)).div_ceil(MMA_TILES) as u32;
            c.launch(mm, (gx, jmax as u32), 128, 0, kargs!(b.gu_a.ptr, b.xg[0].ptr, hid_i, one, b.qq[0].ptr, inter_i, nul, zero_i, rm))?;
            st(c, 12, tp)?;
            let dx = (hidden.div_ceil(16)).div_ceil(MMA_TILES) as u32;
            c.launch(mm, (dx, jmax as u32), 128, 0, kargs!(b.dn_a.ptr, b.qq[0].ptr, inter_i, zero_i, nul, zero_i, b.ys.ptr, hid_i, nul))?;
            cu::memset_d8_async(d.y.ptr, 0, n * hidden * 4, c.stream).map_err(derr)?;
            c.launch(fx.moe_gcombine, (hidden.div_ceil(256) as u32, n as u32), 256, 0, kargs!(d.y.ptr, b.ys.ptr, b.pos.ptr, b.pwt.ptr, nul, nul, zero, n_i, k_i, hid_i))?;
            return Ok(());
        }
        c.launch(fx.moe_gather, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(d.xm.ptr, b.src.ptr, nk_i, hid_i, b.xg[0].ptr, b.xg[1].ptr, b.xg[1].ptr))?;
        st(c, 11, tp)?;
        let fg = fx.mmp_g[gi];
        c.launch(fg, (jmax as u32 * bpg, 1), 32 * 8, 0, kargs!(b.gu_a.ptr, jmax_i, b.xg[0].ptr, b.xg[1].ptr, b.xg[1].ptr, hid_i, rmax_i, hid_i))?;
        st(c, 12, tp)?;
        c.launch(fg, (jmax as u32 * bpd, 1), 32 * 8, 0, kargs!(b.dn_a.ptr, jmax_i, b.qq[0].ptr, b.qq[1].ptr, b.qq[1].ptr, inter_i, rmax_i, inter_i))?;
        cu::memset_d8_async(d.y.ptr, 0, n * hidden * 4, c.stream).map_err(derr)?;
        c.launch(fx.moe_gcombine, (hidden.div_ceil(256) as u32, n as u32), 256, 0, kargs!(d.y.ptr, b.ys.ptr, b.pos.ptr, b.pwt.ptr, nul, nul, zero, n_i, k_i, hid_i))?;
    }
    Ok(())
}

/// A prompt call's message gate (`gate`'s arithmetic): the normed halves of
/// every row, `d = xn · downᵀ`, `F·d` and `G·d` as f32 GEMMs, then the mix.
#[allow(clippy::too_many_arguments)]
unsafe fn gate_big(c: &Ctx, f: &Fx, b: &Big, g: &GateD, x: u64, m: u64, dbuf: u64, out: u64, n: usize, hidden: usize, eps: f32) -> Res<()> {
    let r = g.down.bytes / (2 * hidden * 4);
    let tot = n * hidden;
    let tot_i = tot as i32;
    if gate2_on() {
        // no normed copy: the rows' inverse RMS, x's and m's products with the
        // down rows' halves, d = P·rr_x + Q·rr_m; F and G in one GEMM
        let (p, q, rr) = (b.gxn.ptr, b.gxn.ptr + (n * r * 4) as u64, b.gxn.ptr + (2 * n * r * 4) as u64);
        let (r_i, nr_i) = (r as i32, (n * r) as i32);
        let th = ((hidden / 4).div_ceil(32) * 32).min(1024) as u32;
        unsafe {
            c.launch(f.gate_rr, (n as u32, 1), th, 0, kargs!(x, m, eps, rr))?;
            c.gemm(true, false, r, n, hidden, 1.0, g.down.ptr, 2 * hidden, x, hidden, 0.0, p, r, Gemm::F32)?;
            c.gemm(true, false, r, n, hidden, 1.0, g.down.ptr + (hidden * 4) as u64, 2 * hidden, m, hidden, 0.0, q, r, Gemm::F32)?;
            c.launch(f.gate_d, ((n * r).div_ceil(256) as u32, 1), 256, 0, kargs!(p, q, rr, r_i, nr_i, dbuf))?;
            c.gemm(true, false, 2 * hidden, n, r, 1.0, g.fg.ptr, r, dbuf, r, 0.0, b.gtf.ptr, 2 * hidden, Gemm::F32)?;
            return c.launch(f.gate_mix2, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(x, m, b.gtf.ptr, out, tot_i));
        }
    }
    unsafe {
        c.launch(f.gate_norm, (n as u32, 1), 256, 0, kargs!(x, m, eps, b.gxn.ptr))?;
        c.gemm(true, false, r, n, 2 * hidden, 1.0, g.down.ptr, 2 * hidden, b.gxn.ptr, 2 * hidden, 0.0, dbuf, r, Gemm::F32)?;
        c.gemm(true, false, hidden, n, r, 1.0, g.forget.ptr, r, dbuf, r, 0.0, b.gtf.ptr, hidden, Gemm::F32)?;
        c.gemm(true, false, hidden, n, r, 1.0, g.gain.ptr, r, dbuf, r, 0.0, b.gtg.ptr, hidden, Gemm::F32)?;
        c.launch(f.gate_mix, (tot.div_ceil(256) as u32, 1), 256, 0, kargs!(x, m, b.gtf.ptr, b.gtg.ptr, out, tot_i))
    }
}

/// A message gate: `out = (1 − tanh F·d)·x + tanh G·d·m`, `d` the rank-R
/// projection of `[x/rms x, m/rms m]`.
#[allow(clippy::too_many_arguments)]
unsafe fn gate(c: &Ctx, f: &Fx, g: &GateD, x: u64, m: u64, dbuf: u64, out: u64, n: usize, hidden: usize, eps: f32) -> Res<()> {
    let r = g.down.bytes / (2 * hidden * 4);
    let r_i = r as i32;
    unsafe {
        c.launch(f.gate_down, (r as u32, n as u32), 256, 0, kargs!(x, m, g.down.ptr, r_i, eps, dbuf))?;
        c.launch(f.gate_out, (hidden.div_ceil(8) as u32, n as u32), 256, 0, kargs!(x, m, dbuf, g.forget.ptr, g.gain.ptr, r_i, out))
    }
}

/// The routed experts of the call's rows (the hybrid arm's `moe_routed` over
/// this arm's buffers): the router, the picks laid out as slots, every slot's
/// gate/up pair (Inkling's activation in its epilogue) and down, the mixture
/// into `y`.
unsafe fn moe(c: &Ctx, d: &Dev, cfg: &Cfg, l: &LayerD, n: usize, tp: &mut std::time::Instant, fuse: bool) -> Res<i32> {
    let fx = &d.hfx;
    let hidden = cfg.dim;
    let e = l.e;
    let k = cfg.top_k;
    let s_n = (n * k).min(e).min(d.smax);
    let (ni, ei, hi, ki, si) = (n as i32, e as i32, hidden as i32, k as i32, s_n as i32);
    // renormalized σ scores, a selection bias, the floor 1e-20
    let flags = 1 | 2 | 4 | 32;
    let ps_i = hidden as i32;
    let inter_i = l.inter as i32;
    // `CMF_INKLING_EXP_TB=2` (a measurement): a decode row's experts two tiles a block
    let tb = if (n > 1 && std::env::var("CMF_HYB_MOE_TB").as_deref() != Ok("1")) || std::env::var("CMF_INKLING_EXP_TB").as_deref() == Ok("2") { 2u32 } else { 1u32 };
    let (bpg, bpd) = (l.bpj_gu.div_ceil(tb), l.bpj_dn.div_ceil(tb));
    let (bg, bd) = (bpg as i32, bpd as i32);
    let nul = 0u64;
    unsafe {
        if fuse && n == 1 && e <= 256 && k <= 32 && s_n == k && hidden % 4 == 0 {
            // a decode row: the router and the selection in one launch
            c.launch(
                fx.moe_route1,
                (e as u32, 1),
                128,
                0,
                kargs!(
                    d.xm.ptr, l.router.ptr, d.logits_e.ptr, ei, hi, l.bias.ptr, ki, flags, cfg.route_scale, l.gu_t.ptr, l.dn_t.ptr, d.gu_a.ptr, d.dn_a.ptr, d.wsel.ptr, si, d.qq[0].ptr,
                    d.qq[1].ptr, ps_i, d.dns.ptr, bg, bd, d.rcnt.ptr
                ),
            )?;
        } else {
            if fuse && e <= 256 && hidden % 4 == 0 {
                // a verify call's rows: the decode route's logits
                c.launch(fx.moe_router4, (e as u32, n as u32), 128, 0, kargs!(d.xm.ptr, l.router.ptr, d.logits_e.ptr, ei, hi))?;
            } else {
                c.launch(fx.moe_router, ((e + 1).div_ceil(8) as u32, n as u32), 256, 0, kargs!(d.xm.ptr, l.router.ptr, nul, d.logits_e.ptr, d.sg.ptr, ni, ei, hi))?;
            }
            c.launch(
                fx.moe_select,
                (1, 1),
                if n == 1 && select512_on() { 512 } else { (32 * n.max(1)) as u32 },
                0,
                kargs!(
                    d.logits_e.ptr, l.bias.ptr, ni, ei, ki, flags, cfg.route_scale, l.gu_t.ptr, l.dn_t.ptr, d.gu_a.ptr, d.dn_a.ptr, d.wsel.ptr, si,
                    d.qq[0].ptr, d.qq[1].ptr, ps_i, d.dns.ptr, hi, bg, bd
                ),
            )?;
        }
        st(c, 11, tp)?;
        let t = (tb - 1) as usize;
        // the experts' K split: 16 warps a tile (`CMF_HYB_KS=8`: 8)
        let k16 = super::decode_ks().is_none_or(|k| k == 16);
        let ksw = if k16 { 16u32 } else { 8 };
        let pick = |kd: Option<usize>| match kd {
            Some(dd) => fx.mmpk[nt_of(n)][t][k16 as usize][dd],
            None => fx.mmp[nt_of(n)][t][k16 as usize],
        };
        let xs_i = hidden as i32;
        // a decode row's experts as a resident grid (q4tp / int8): no partial last wave
        let res = |kd: Option<usize>| match kd {
            Some(dd) if n == 1 && t == 0 && dd < 2 && persist_on() && fx.mmpkg_res[dd] > 0 => Some((fx.mmpkg[dd], fx.mmpkg_res[dd])),
            _ => None,
        };
        let (nbg, nbd) = (s_n as u32 * bpg, s_n as u32 * bpd);
        match res(l.kd.0) {
            Some((fg, rb)) => {
                let nb_i = nbg as i32;
                c.launch(fg, (nbg.min(rb), 1), 32 * 16, 0, kargs!(d.gu_a.ptr, si, d.pm[0].ptr, d.pm[1].ptr, d.pm[1].ptr, xs_i, ni, hi, nb_i))?
            }
            None => c.launch(pick(l.kd.0), (nbg, 1), 32 * ksw, 0, kargs!(d.gu_a.ptr, si, d.pm[0].ptr, d.pm[1].ptr, d.pm[1].ptr, xs_i, ni, hi))?,
        }
        st(c, 12, tp)?;
        match res(l.kd.1) {
            Some((fd, rb)) => {
                let nb_i = nbd as i32;
                c.launch(fd, (nbd.min(rb), 1), 32 * 16, 0, kargs!(d.dn_a.ptr, si, d.qq[0].ptr, d.qq[1].ptr, d.qq[1].ptr, ps_i, ni, inter_i, nb_i))?
            }
            None => c.launch(pick(l.kd.1), (nbd, 1), 32 * ksw, 0, kargs!(d.dn_a.ptr, si, d.qq[0].ptr, d.qq[1].ptr, d.qq[1].ptr, ps_i, ni, inter_i))?,
        }
        st(c, 13, tp)?;
        if !fuse {
            cu::memset_d8_async(d.y.ptr, 0, n * hidden * 4, c.stream).map_err(derr)?;
            let zero = 0i32;
            c.launch(fx.moe_combine, (hidden.div_ceil(256) as u32, n as u32), 256, 0, kargs!(d.y.ptr, d.dns.ptr, d.wsel.ptr, nul, d.sg.ptr, zero, ni, hi, si))?;
        }
    }
    Ok(si)
}