inky-engine 3.0.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
//! KV8 tensor-core prefill attention (`k_attn_tc_fixed_blk`, `k_attn_tc_fixed_b` under `KV8`).
//!
//! Three layers of evidence, from the cheapest to the widest:
//! 1. The KV8 row format on the CPU: where the per-row scale lives, with a reversed witness.
//! 2. A model of the kernels' tile grid (which cache row each lane reads for which query row, which partial slot
//!    it lands in), enumerated at a capacity small enough to try every span, with planted off-by-one witnesses.
//! 3. The kernels themselves on a GPU, with no model file: an exact census of every key every row sees, the
//!    simdgroup KV8 kernels and a CPU reference on random data, and a microbenchmark. These run wherever Metal 4
//!    and MetalPerformancePrimitives run (an M3 Ultra executes them on its ALUs), and nightly on the M5.

use super::*;
use crate::blocks::{f16_bits_to_f32, f32_to_f16_bits, kv8_vscale_cpu, BLOCK};

// ---------------------------------------------------------------------------------------------------------------
// 1. The KV8 row format (`kv_scale`, `kv_code`, `kv_quant`, `kv_vscale` in `kernels.metal`).
//
//    One cache row is HD = 128 signed bytes q[0..128) and stands for the vector q[d] * s(c).
//    The scale s(c) = (8 + (c & 7)) * 2^((c >> 3) - 20) has an 8-bit code c that takes no space of its own:
//
//        byte:       0     1     2     3     4     5     6     7     8 ... 127
//        low bit:  c>>7  c>>6  c>>5  c>>4  c>>3  c>>2  c>>1   c     (free)
//
//    Bytes 0..7 are rounded to the even or the odd integers so that their lowest bits spell c, bit 7 first.
// ---------------------------------------------------------------------------------------------------------------

fn kv8_scale(c: u32) -> f32 {
    (8 + (c & 7)) as f32 * f32::from_bits(((c >> 3) + 107) << 23)
}

/// `kv_code`: the smallest step that represents a vector whose largest magnitude is `mx` in 126 steps.
fn kv8_code(mx: f32) -> u32 {
    if mx.is_nan() || mx <= 0.0 {
        return 0;
    }
    let t = mx / 126.0;
    let mut ex = (t.log2().floor() as i32).clamp(-17, 14);
    let mut m = ((t * 2f32.powi(-ex) * 8.0).ceil() as i32).clamp(8, 16);
    if m == 16 {
        m = 8;
        ex += 1;
    }
    let mut c = (((ex + 17) << 3) | (m - 8)).min(255) as u32;
    if kv8_scale(c) * 126.0 < mx && c < 255 {
        c += 1;
    }
    c
}

/// `kv_quant` over one vector: the stored bytes of `x`.
pub(super) fn kv8_quant_row(x: &[f32]) -> [i8; HD] {
    let mx = x.iter().fold(0.0f32, |m, v| m.max(v.abs()));
    let c = kv8_code(mx);
    let s = kv8_scale(c);
    let mut row = [0i8; HD];
    for (i, (&v, out)) in x.iter().zip(row.iter_mut()).enumerate() {
        let y = v / s;
        let q = if i < 8 {
            let b = ((c >> (7 - i)) & 1) as f32;
            2.0 * ((y - b) * 0.5).round_ties_even() + b
        } else {
            y.round_ties_even()
        };
        *out = q.clamp(-127.0, 127.0) as i8;
    }
    row
}

/// A row whose code is `c` and whose bytes are `value(d)`, bytes 0..7 moved to the parity the code asks for.
fn kv8_row_with_code(c: u32, value: impl Fn(usize) -> i8) -> [i8; HD] {
    let mut row = [0i8; HD];
    for (d, out) in row.iter_mut().enumerate() {
        let v = value(d);
        *out = if d < 8 { (v & !1) | ((c >> (7 - d)) & 1) as i8 } else { v };
    }
    row
}

fn as_bytes(row: &[i8]) -> &[u8] {
    // i8 and u8 have one layout
    unsafe { std::slice::from_raw_parts(row.as_ptr().cast::<u8>(), row.len()) }
}

#[test]
fn kv8_scale_code_rides_in_the_low_bits_of_the_first_eight_bytes() {
    for c in 0..256u32 {
        let s = kv8_scale(c);
        assert_eq!(f64::from(s), f64::from(8 + (c & 7)) * 2f64.powi((c >> 3) as i32 - 20), "scale of code {c}");
        // any bytes with these low bits decode to the code's scale
        let row = kv8_row_with_code(c, |d| (d as i32 * 37 - 90).clamp(-127, 127) as i8);
        assert_eq!(kv8_vscale_cpu(as_bytes(&row)).to_bits(), s.to_bits(), "code {c}");
        for (i, &b) in row[..8].iter().enumerate() {
            assert_eq!((b as u8 & 1) as u32, (c >> (7 - i)) & 1, "code {c}: bit {} is the low bit of byte {i}", 7 - i);
        }
        // bytes 8.. carry no scale: flipping all their low bits changes nothing
        let mut tail = row;
        tail[8..].iter_mut().for_each(|b| *b ^= 1);
        assert_eq!(kv8_vscale_cpu(as_bytes(&tail)).to_bits(), s.to_bits(), "code {c}: bytes 8.. are free");
    }
    // Reversed witness: the same code written bit i in byte i (the order reversed) reads back as another scale.
    let c = 0b0101_1001u32;
    let mut reversed = [0i8; HD];
    for (i, b) in reversed[..8].iter_mut().enumerate() {
        *b = ((c >> i) & 1) as i8;
    }
    assert_eq!(kv8_vscale_cpu(as_bytes(&reversed)).to_bits(), kv8_scale(c.reverse_bits() >> 24).to_bits());
    assert_ne!(kv8_vscale_cpu(as_bytes(&reversed)).to_bits(), kv8_scale(c).to_bits());

    // The quantiser keeps the format's promises: the stored scale is the smallest that holds the vector in 126
    // steps, nothing clips, and every value is within half a step (a whole step in the 8 bytes that carry the code).
    let mut rng = Rng::new(0x51ca1e);
    for trial in 0..2000 {
        let amp = 2f32.powi((trial % 14) as i32 - 9);
        let x: Vec<f32> = (0..HD).map(|_| rng.unit() * amp).collect();
        let mx = x.iter().fold(0.0f32, |m, v| m.max(v.abs()));
        let row = kv8_quant_row(&x);
        let s = kv8_vscale_cpu(as_bytes(&row));
        let c = kv8_code(mx);
        assert_eq!(s.to_bits(), kv8_scale(c).to_bits(), "trial {trial}");
        assert!(s * 126.0 >= mx, "trial {trial}: the largest value must not clip");
        assert!(c == 0 || kv8_scale(c - 1) * 126.0 < mx, "trial {trial}: code {c} is not the smallest");
        for (d, (&v, &q)) in x.iter().zip(&row).enumerate() {
            let err = (f64::from(q) * f64::from(s) - f64::from(v)).abs();
            let steps = if d < 8 { 1.0 } else { 0.5 };
            assert!(err <= steps * f64::from(s) * (1.0 + 1e-6), "trial {trial} d {d}: {v} stored as {q} * {s}");
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------
// 2. The tile grid of `k_attn_tc_fixed_blk` / `k_attn_tc_fixed_b`, as a model.
//
//    Positions run left to right. The cache is cut three ways at once, all anchored at position 0:
//
//        block  (64 rows, one pool slot)     |0 ............ 63|64 ......... 127|128 ...
//        tile   (32 keys, one tensor op)     |0 .... 31|32 . 63|64 . 95|96 . 127|128 ...
//        split  (64 keys on window passes,   |0 ............ 63|64 ......... 127|128 ...     (window)
//                256 on full passes)         |0 ......................................... 255|256 ...  (full)
//
//    A tile is half a block and a split is a whole number of blocks, so a tile never crosses a block or a split.
//    Layer 3 finds key `kp` at row `kp % 64` of block `kp / 64` through the lane's block table (a window lane holds
//    its last 18 blocks; older entries are cleared). Layer 2 finds it at row `kp - idx0` of one array: `idx0` is 0
//    in a lane's full cache and `p0 - (EXT + KGUARD)` in the window scratch.
//
//    A threadgroup is (split column, KV head, 16 query rows); the GPU grid (`tc_attn_dispatch_grid`) is (row block
//    `x`, KV head `y`, split column `z`) for FP16 and KV8, rows fastest so the row blocks of one K/V split run
//    together, and (split column `x`, KV head `y`, row block `z`) for KV4. Its
//    absolute split is the first row's first split plus its split column; each of its rows files that split under
//    its own local index (absolute split minus the row's first split), so the 16 rows of one threadgroup may write
//    local slots that differ by one. Within a tile, lane `j` of each simdgroup holds key `kc + j`: column `j` of
//    the tile's K tensor, and under KV8 the lane that reads the two scales in the low bits of that key's K row and
//    V row.
//
//    The model below is the kernels' arithmetic with the sizes as parameters. `Plant` breaks it in ways a slip
//    would, and the checker has to catch each one.
// ---------------------------------------------------------------------------------------------------------------

#[derive(Clone, Copy, Debug)]
struct TcGeom {
    /// cache rows per block (`KV_BLK`)
    block: usize,
    /// keys per tile (`TC_ATT_AK`)
    ak: usize,
    /// keys per split (`PreparedAttnArgs::kps`)
    kps: usize,
    /// sliding window (`PreparedAttnArgs::window`), 0 on a full-attention pass
    window: usize,
    /// reach of the relative-bias table (`EXT`)
    ext: usize,
    /// query rows per threadgroup (`PreparedAttnArgs::tg_rows`)
    tg_rows: usize,
}

impl TcGeom {
    const ENGINE_WINDOW: TcGeom = TcGeom { block: BLOCK, ak: 32, kps: 64, window: EXT, ext: EXT, tg_rows: TC_ATT_TG_ROWS };
    const ENGINE_FULL: TcGeom = TcGeom { block: BLOCK, ak: 32, kps: 256, window: 0, ext: EXT, tg_rows: TC_ATT_TG_ROWS };
    /// 4-row blocks, 2-key tiles, a 3-block window, 3 rows per threadgroup
    const SMALL_WINDOW: TcGeom = TcGeom { block: 4, ak: 2, kps: 4, window: 12, ext: 12, tg_rows: 3 };
    /// the same blocks and tiles, 4-block splits
    const SMALL_FULL: TcGeom = TcGeom { block: 4, ak: 2, kps: 16, window: 0, ext: 12, tg_rows: 3 };

    fn swa(&self) -> bool {
        self.window != 0
    }
    /// `fixed_attn_nsplit` at this geometry: partial slots per row
    fn nsplit(&self, span_end: usize) -> usize {
        if self.swa() && span_end > self.ext {
            (self.ext - 1).div_ceil(self.kps) + 1
        } else if span_end == 0 {
            1
        } else {
            fixed_split_count(0, span_end, self.kps)
        }
    }
    /// `prefill_attn_grid` at this geometry: split columns of the grid
    fn grid_x(&self, span_end: usize, plant: Plant) -> usize {
        let nsplit = self.nsplit(span_end);
        if self.swa() && span_end > self.ext && plant != Plant::NoRolloverColumn {
            nsplit + 1
        } else {
            nsplit
        }
    }
    fn p_lo(&self, pos: usize) -> usize {
        if self.swa() && pos + 1 > self.window {
            pos + 1 - self.window
        } else {
            0
        }
    }
}

/// A slip planted in the model.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Plant {
    None,
    /// dispatch as many split columns as a row has splits, without the one the sliding window adds
    NoRolloverColumn,
    /// take a tile's row inside its block from the split's width instead of the block's (`kc % kps`)
    TileRowInSplitUnits,
    /// read the lane's scale from the row after its key
    ScaleFromTheNextRow,
    /// call a tile interior when its nearest key is still one position inside the relative-bias table
    InteriorOneKeyEarly,
}

/// One key as one query row sees it in one threadgroup.
struct KeyRead {
    row: usize,
    local_sp: usize,
    kp: usize,
    /// (block, row in block) the tile's tensor reads this lane's key from
    key_at: (usize, usize),
    /// (block, row in block) the lane reads its scale from
    scale_at: (usize, usize),
    bias: bool,
}

struct TgTrace {
    /// (first key, keys, interior) of every tile the threadgroup multiplies
    tiles: Vec<(usize, usize, bool)>,
    reads: Vec<KeyRead>,
    /// (row, local split) of every partial the threadgroup writes
    slots: Vec<(usize, usize)>,
    k_min: usize,
}

/// The unpruned branch of the kernels for threadgroup `(tg_x, tg_z)` of a batch of `nrows` rows starting at `pos0`.
fn tc_threadgroup(g: &TcGeom, pos0: usize, nrows: usize, tg_x: usize, tg_z: usize, plant: Plant) -> Option<TgTrace> {
    let row0 = tg_z * g.tg_rows;
    if row0 >= nrows {
        return None;
    }
    let nr = g.tg_rows.min(nrows - row0);
    let abs_sp = g.p_lo(pos0 + row0) / g.kps + tg_x;
    let split_start = abs_sp * g.kps;
    let split_lim = split_start + g.kps;
    let (mut live, mut p_lo_r, mut p_hi_r, mut local_sp_r) = (vec![false; nr], vec![0; nr], vec![0; nr], vec![0; nr]);
    let (mut k_min_tg, mut p_max_tg) = (usize::MAX, 0usize);
    for r in 0..nr {
        let p_hi = pos0 + row0 + r + 1;
        let plo = g.p_lo(pos0 + row0 + r);
        let sp_base = plo / g.kps;
        live[r] = abs_sp >= sp_base && split_start < p_hi;
        p_lo_r[r] = plo;
        p_hi_r[r] = p_hi.min(split_lim);
        local_sp_r[r] = abs_sp.wrapping_sub(sp_base);
        if live[r] {
            k_min_tg = k_min_tg.min(plo);
            p_max_tg = p_max_tg.max(p_hi_r[r]);
        }
    }
    if p_max_tg == 0 {
        return None;
    }
    // `tc_interior_bounds`
    let all_live = live.iter().all(|&l| l);
    let (int_lo, int_hi) = if all_live {
        (p_lo_r.iter().copied().max().unwrap(), p_hi_r.iter().copied().min().unwrap())
    } else {
        (usize::MAX, 0)
    };
    let mut t = TgTrace { tiles: Vec::new(), reads: Vec::new(), slots: Vec::new(), k_min: k_min_tg };
    let mut kc = split_start;
    while kc < p_max_tg {
        if kc + g.ak <= k_min_tg {
            kc += g.ak;
            continue;
        }
        let nk = g.ak.min(p_max_tg - kc);
        let tile_at = (kc / g.block, if plant == Plant::TileRowInSplitUnits { kc % g.kps } else { kc % g.block });
        let nearest = (pos0 + row0) as i64 - (kc + nk - 1) as i64;
        let any_bias = nearest + i64::from(plant == Plant::InteriorOneKeyEarly) < g.ext as i64;
        let interior = !any_bias && nk == g.ak && kc >= int_lo && kc + g.ak <= int_hi;
        t.tiles.push((kc, nk, interior));
        for lane in 0..g.ak {
            let kp = kc + lane;
            let key_at = (tile_at.0, tile_at.1 + lane);
            let scale_at = (tile_at.0, tile_at.1 + lane + usize::from(plant == Plant::ScaleFromTheNextRow));
            for r in 0..nr {
                let pos = pos0 + row0 + r;
                let valid = interior || (live[r] && lane < nk && kp >= p_lo_r[r] && kp < p_hi_r[r]);
                if valid {
                    let bias = !interior && any_bias && pos.wrapping_sub(kp) < g.ext;
                    t.reads.push(KeyRead { row: row0 + r, local_sp: local_sp_r[r], kp, key_at, scale_at, bias });
                }
            }
        }
        kc += g.ak;
    }
    for r in 0..nr {
        if live[r] {
            t.slots.push((row0 + r, local_sp_r[r]));
        }
    }
    Some(t)
}

#[derive(Default, Debug)]
struct TcCensus {
    tiles: usize,
    interior_tiles: usize,
    partial_tiles: usize,
    reads: usize,
    /// threadgroups whose rows filed one absolute split under two local indices
    straddling_threadgroups: usize,
}

/// Run the whole grid of one batch through the model and check what the kernels promise.
fn tc_check(g: &TcGeom, pos0: usize, nrows: usize, plant: Plant) -> Result<TcCensus, String> {
    let end = pos0 + nrows;
    let nsplit = g.nsplit(end);
    // seen[row][kp - p_lo]: how often the row read key kp
    let mut seen: Vec<Vec<u8>> = (0..nrows).map(|row| vec![0; pos0 + row + 1 - g.p_lo(pos0 + row)]).collect();
    let mut written = vec![vec![0usize; nsplit]; nrows];
    let mut census = TcCensus::default();
    let fail = |what: &str, detail: String| Err(format!("{what}: {detail} (pos0 {pos0}, {nrows} rows, {g:?}, {plant:?})"));
    for tg_z in 0..nrows.div_ceil(g.tg_rows) {
        for tg_x in 0..g.grid_x(end, plant) {
            let Some(tg) = tc_threadgroup(g, pos0, nrows, tg_x, tg_z, plant) else { continue };
            for &(kc, nk, interior) in &tg.tiles {
                census.tiles += 1;
                census.interior_tiles += usize::from(interior);
                census.partial_tiles += usize::from(nk < g.ak);
                if kc % g.ak != 0 || kc % g.block + nk > g.block {
                    return fail("a tile crosses a block", format!("keys {kc}..{}", kc + nk));
                }
                if kc + nk > end {
                    return fail("a tile reads past the last written row", format!("keys {kc}..{}", kc + nk));
                }
                if kc / g.block < tg.k_min / g.block {
                    return fail("a tile reads a block older than every live key", format!("tile {kc}, first live key {}", tg.k_min));
                }
                // Layer 2 window scratch: row 0 is position `pos0 - (ext + KGUARD)`, and KGUARD is one block
                if g.swa() && (kc as i64) < pos0 as i64 - (g.ext + g.block) as i64 {
                    return fail("a tile starts before the window scratch", format!("tile {kc}"));
                }
            }
            for rd in &tg.reads {
                let pos = pos0 + rd.row;
                let p_lo = g.p_lo(pos);
                if rd.kp < p_lo || rd.kp > pos {
                    return fail("a row sees a key outside its window", format!("row {} (position {pos}) key {}", rd.row, rd.kp));
                }
                let home = (rd.kp / g.block, rd.kp % g.block);
                if rd.key_at != home {
                    return fail("a key is read from another row", format!("key {} from {:?}", rd.kp, rd.key_at));
                }
                if rd.scale_at != home {
                    return fail("a scale is read from another row", format!("key {} from {:?}", rd.kp, rd.scale_at));
                }
                if rd.local_sp != rd.kp / g.kps - p_lo / g.kps || rd.local_sp >= nsplit {
                    return fail("a key lands in the wrong partial slot", format!("row {} key {} slot {}", rd.row, rd.kp, rd.local_sp));
                }
                if rd.bias != (pos - rd.kp < g.ext) {
                    return fail("the relative bias is applied to the wrong keys", format!("row {} key {}", rd.row, rd.kp));
                }
                seen[rd.row][rd.kp - p_lo] += 1;
                census.reads += 1;
            }
            let mut locals: Vec<usize> = tg.slots.iter().map(|&(_, sp)| sp).collect();
            locals.dedup();
            census.straddling_threadgroups += usize::from(locals.len() > 1);
            for &(row, sp) in &tg.slots {
                if sp >= nsplit {
                    return fail("a partial is written past the row's slots", format!("row {row} slot {sp} of {nsplit}"));
                }
                written[row][sp] += 1;
            }
        }
    }
    for row in 0..nrows {
        let pos = pos0 + row;
        let p_lo = g.p_lo(pos);
        if let Some(i) = seen[row].iter().position(|&n| n != 1) {
            return fail("a visible key is not read exactly once", format!("row {row} (position {pos}) key {}: {} times", p_lo + i, seen[row][i]));
        }
        let count = fixed_split_count(p_lo, pos + 1, g.kps);
        for (sp, &n) in written[row].iter().enumerate() {
            if n != usize::from(sp < count) {
                return fail("a partial slot is not written exactly once", format!("row {row} slot {sp} of {count}: {n} times"));
            }
        }
    }
    Ok(census)
}

#[test]
fn kv8_tc_tile_grid_reads_every_visible_key_once_from_its_own_row_at_small_capacity() {
    for g in [TcGeom::SMALL_WINDOW, TcGeom::SMALL_FULL] {
        let (mut total, mut caught) = (TcCensus::default(), [0usize; 4]);
        let plants = [Plant::NoRolloverColumn, Plant::TileRowInSplitUnits, Plant::ScaleFromTheNextRow, Plant::InteriorOneKeyEarly];
        // every span of up to 3 threadgroups and a row, starting anywhere in the first 4 windows and 2 blocks
        for pos0 in 0..4 * 12 + 2 * g.block {
            for nrows in 1..=3 * g.tg_rows + 1 {
                let c = tc_check(&g, pos0, nrows, Plant::None).unwrap_or_else(|e| panic!("{e}"));
                total.tiles += c.tiles;
                total.interior_tiles += c.interior_tiles;
                total.partial_tiles += c.partial_tiles;
                total.reads += c.reads;
                total.straddling_threadgroups += c.straddling_threadgroups;
                for (n, &plant) in caught.iter_mut().zip(&plants) {
                    *n += usize::from(tc_check(&g, pos0, nrows, plant).is_err());
                }
            }
        }
        // the enumeration reached the cases the layout is about
        assert!(total.partial_tiles > 0 && total.reads > 0, "{g:?}: {total:?}");
        if g.swa() {
            // rows of one threadgroup whose windows start in different splits: the reason for the extra column
            assert!(total.straddling_threadgroups > 0, "{g:?}: {total:?}");
            assert_eq!(total.interior_tiles, 0, "a window reaches no further than the relative-bias table");
            assert!(caught[0] > 0, "{g:?}: the grid without the rollover column must lose keys somewhere");
        } else {
            assert!(total.interior_tiles > 0, "{g:?}: {total:?}");
            assert_eq!(caught[0], 0, "a full pass has no rollover column to lose");
            // one key early is a tile whose last key sits at distance ext - 1 from the threadgroup's first row
            assert!(caught[3] > 0, "{g:?}: an interior tile one key inside the bias table must be caught");
            // a split is 4 blocks here: the second block of a split is the first place `kc % kps` leaves the block
            assert!(caught[1] > 0, "{g:?}: a tile row taken in split units must be caught");
        }
        assert!(caught[2] > 0, "{g:?}: a scale read from the next row must be caught");
    }
    // The witness at the block boundary, spelled out: 4-row blocks, window 12. Rows at positions 14..=16 share a
    // threadgroup. Position 14 sees keys 3..=14 (splits 0..=3); position 16 sees keys 5..=16 (splits 1..=4). The
    // threadgroup's columns count from the first row's first split, so split 4, the block that position 16 opens,
    // is column 4: the fifth, one more than the 4 slots any single row needs.
    let g = TcGeom::SMALL_WINDOW;
    assert_eq!((g.nsplit(17), g.grid_x(17, Plant::None)), (4, 5));
    assert!(tc_check(&g, 14, 3, Plant::None).is_ok());
    let lost = tc_check(&g, 14, 3, Plant::NoRolloverColumn).unwrap_err();
    assert!(lost.contains("row 2 (position 16) key 16"), "{lost}");
    // One position earlier nothing straddles a block and 4 columns are enough: the planted slip is silent there.
    assert!(tc_check(&g, 13, 3, Plant::NoRolloverColumn).is_ok());
}

#[test]
fn kv8_tc_tile_grid_holds_at_the_engine_geometry() {
    // The model's sizes are the engine's.
    for end in [1, 63, 64, 65, EXT - 1, EXT, EXT + 1, 4096, 100_000] {
        for (g, swa) in [(TcGeom::ENGINE_WINDOW, true), (TcGeom::ENGINE_FULL, false)] {
            assert_eq!(g.kps, decode_split_kps(swa, 0));
            let nsplit = fixed_attn_nsplit(swa, end);
            assert_eq!(g.nsplit(end), nsplit, "swa {swa} end {end}");
            assert_eq!((g.tg_rows, g.grid_x(end, Plant::None)), prefill_attn_grid(true, swa, end, 0, nsplit));
        }
    }
    // 16 rows of one threadgroup touch 18 window blocks, the slots a window lane's ring has: 16 and the two a
    // sliding window straddles.
    assert_eq!(TcGeom::ENGINE_WINDOW.grid_x(EXT + 1, Plant::None), crate::blocks::MIN_ROLLOVER_WINDOW_SLOTS);
    // The batches the GPU tests run are batches the model accepts, interior tiles among them.
    let mut interior = 0;
    for case in CASES.iter().chain([&DEEP]).filter(|c| c.budget == 0) {
        let g = if case.swa { TcGeom::ENGINE_WINDOW } else { TcGeom::ENGINE_FULL };
        let census = tc_check(&g, case.pos0, case.nrows, Plant::None).unwrap_or_else(|e| panic!("{}: {e}", case.name));
        assert!(!case.swa || census.interior_tiles == 0, "{}", case.name);
        interior += census.interior_tiles;
    }
    assert!(interior > 100, "the full-attention cases must reach interior tiles: {interior}");
    // The planted slips are caught at the engine's sizes too.
    assert!(tc_check(&TcGeom::ENGINE_WINDOW, 2040, 17, Plant::NoRolloverColumn).is_err());
    assert!(tc_check(&TcGeom::ENGINE_FULL, 250, 17, Plant::TileRowInSplitUnits).is_err());
    assert!(tc_check(&TcGeom::ENGINE_FULL, 250, 17, Plant::ScaleFromTheNextRow).is_err());
    assert!(tc_check(&TcGeom::ENGINE_FULL, 3006, 70, Plant::InteriorOneKeyEarly).is_err());
}

/// What one threadgroup of the model computes: its tiles, and for each partial slot it writes, the keys (and
/// whether each takes the relative bias) that slot sums. A function of the threadgroup's split column and row
/// block alone.
/// (row, local split) of a partial slot and the (key, takes the bias) it sums
type SlotKeys = ((usize, usize), Vec<(usize, bool)>);
type TgWork = (Vec<(usize, usize, bool)>, Vec<SlotKeys>);

/// Every threadgroup of one batch on one KV head, in the order the GPU is handed them (a grid is numbered `x`
/// fastest, then `y`, then `z`), decoded the way the kernels decode `threadgroup_position_in_grid`: row-major
/// (FP16, KV8) `x` is the row block and `z` the split column; split-major (KV4, or `TC_ATT_GRID_SPLIT_X`) the
/// other way round. Returns (split column, row block, its work).
fn tc_dispatch(g: &TcGeom, pos0: usize, nrows: usize, grid: (usize, usize, usize), split_major: bool) -> Vec<(usize, usize, Option<TgWork>)> {
    let mut out = Vec::new();
    for z in 0..grid.2 {
        for y in 0..grid.1 {
            for x in 0..grid.0 {
                if y != 0 {
                    continue;
                }
                let (sx, rb) = if split_major { (x, z) } else { (z, x) };
                let work = tc_threadgroup(g, pos0, nrows, sx, rb, Plant::None).map(|t| {
                    let mut slots: Vec<SlotKeys> = t.slots.iter().map(|&s| (s, Vec::new())).collect();
                    for rd in &t.reads {
                        let at = slots.iter().position(|(s, _)| *s == (rd.row, rd.local_sp)).expect("a read of a row the threadgroup files");
                        slots[at].1.push((rd.kp, rd.bias));
                    }
                    (t.tiles, slots)
                });
                out.push((sx, rb, work));
            }
        }
    }
    out
}

#[test]
fn tc_grid_per_format_runs_the_same_threadgroups_row_major_for_fp16_kv8_and_split_major_for_kv4() {
    use std::collections::BTreeMap;
    let (mut grouped_by_old_grid, mut shared_splits) = (0, 0);
    for (g, spans) in [
        (TcGeom::ENGINE_FULL, [(0, 17), (250, 48), (3006, 70), (5000, 48), (20_000, 33)]),
        (TcGeom::ENGINE_WINDOW, [(0, 17), (2040, 17), (2040, 48), (5000, 70), (20_000, 33)]),
        (TcGeom::SMALL_FULL, [(0, 7), (14, 9), (30, 10), (41, 3), (47, 10)]),
        (TcGeom::SMALL_WINDOW, [(0, 7), (14, 9), (30, 10), (41, 3), (47, 10)]),
    ] {
        for (pos0, nrows) in spans {
            let what = format!("{g:?} pos0 {pos0} rows {nrows}");
            let (grid_x, rbs) = (g.grid_x(pos0 + nrows, Plant::None), nrows.div_ceil(g.tg_rows));
            // the old grid, and the engine's grid per format with the kernels' decode per format
            let old = tc_dispatch(&g, pos0, nrows, (grid_x, NKV, rbs), true);
            let new = tc_dispatch(&g, pos0, nrows, tc_attn_dispatch_grid(false, grid_x, nrows, g.tg_rows), false);
            let kv4 = tc_dispatch(&g, pos0, nrows, tc_attn_dispatch_grid(true, grid_x, nrows, g.tg_rows), true);
            // KV4 keeps the old grid: the same threadgroups in the same order, doing the same work
            assert!(kv4 == old, "{what}: KV4 must run the split-major grid unchanged");
            // the same threadgroups, each once: only the order differs
            let by_tg = |d: &[(usize, usize, Option<TgWork>)]| {
                let mut m = BTreeMap::new();
                for (sx, rb, w) in d {
                    assert!(m.insert((*sx, *rb), w.clone()).is_none(), "{what}: threadgroup ({sx}, {rb}) dispatched twice");
                }
                m
            };
            let (old_tgs, new_tgs) = (by_tg(&old), by_tg(&new));
            assert_eq!(old_tgs.keys().collect::<Vec<_>>(), new_tgs.keys().collect::<Vec<_>>(), "{what}");
            // each partial slot is written by exactly one threadgroup, from the same keys, under either grid, so
            // `k_attn_fixed_combine` (which folds slots in slot order) reads identical inputs
            let by_slot = |m: &BTreeMap<(usize, usize), Option<TgWork>>| {
                let mut s = BTreeMap::new();
                for (tg, w) in m {
                    for (slot, keys) in w.iter().flat_map(|w| &w.1) {
                        assert!(s.insert(*slot, (*tg, w.as_ref().unwrap().0.clone(), keys.clone())).is_none(), "{what}: slot {slot:?} written twice");
                    }
                }
                s
            };
            assert!(by_slot(&old_tgs) == by_slot(&new_tgs), "{what}: a slot's work differs between the grids");
            // on the row-major grid the row blocks of one split column are consecutive threadgroups
            for (i, &(sx, rb, _)) in new.iter().enumerate() {
                assert_eq!((sx, rb), (i / rbs, i % rbs), "{what}");
            }
            let columns = grid_x;
            shared_splits += usize::from(rbs > 1 && columns > 1);
            grouped_by_old_grid += usize::from(rbs > 1 && columns > 1 && old.iter().enumerate().all(|(i, &(sx, rb, _))| (sx, rb) == (i / rbs, i % rbs)));
        }
    }
    assert!(shared_splits > 10, "the spans must reach batches whose row blocks share split columns: {shared_splits}");
    assert_eq!(grouped_by_old_grid, 0, "the split-major grid must not already group the row blocks of a split");
}

// ---------------------------------------------------------------------------------------------------------------
// 3. The kernels on a GPU.
// ---------------------------------------------------------------------------------------------------------------

struct Rng(u64);

impl Rng {
    fn new(seed: u64) -> Self {
        Rng(seed ^ 0x9E37_79B9_7F4A_7C15)
    }
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    }
    /// uniform in [-1, 1)
    fn unit(&mut self) -> f32 {
        ((self.next() >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
    }
}

/// One prefill attention batch: `nrows` query rows at positions `pos0..`, on a window or a full pass.
#[derive(Clone, Copy, Debug)]
struct Case {
    name: &'static str,
    swa: bool,
    pos0: usize,
    nrows: usize,
    /// `--full-attn-budget` (0: every key)
    budget: usize,
}

impl Case {
    const fn window(name: &'static str, pos0: usize, nrows: usize) -> Case {
        Case { name, swa: true, pos0, nrows, budget: 0 }
    }
    const fn full(name: &'static str, pos0: usize, nrows: usize) -> Case {
        Case { name, swa: false, pos0, nrows, budget: 0 }
    }
    fn end(&self) -> usize {
        self.pos0 + self.nrows
    }
    fn kps(&self) -> usize {
        decode_split_kps(self.swa, 0)
    }
    fn nsplit(&self) -> usize {
        fixed_attn_nsplit(self.swa, self.end())
    }
    /// The specification the kernels implement, with no tiles in it: the splits of the row at `pos`, in the
    /// order of their partial slots, each with the keys the row sees in it (`k_attn_fixed_b`'s definition).
    fn row_splits(&self, pos: usize) -> Vec<Vec<usize>> {
        let (kps, p_hi) = (self.kps(), pos + 1);
        if !self.swa && self.budget > 0 && p_hi > self.budget {
            // far-key pruning: the first 64 keys, a gap, then the most recent `budget - 64`
            let recent_start = p_hi - (self.budget - 64);
            let (rlo, sp_hi) = (recent_start / kps, pos / kps);
            let count = if rlo == 0 { sp_hi + 1 } else { 1 + (sp_hi - rlo + 1) };
            return (0..count)
                .map(|sp| {
                    let abs_sp = if rlo == 0 || sp == 0 { sp } else { rlo + sp - 1 };
                    let start = abs_sp * kps;
                    let lo = if abs_sp > 0 { recent_start } else { 0 };
                    let hi = if abs_sp == 0 && rlo > 0 { p_hi.min(64) } else { p_hi.min(start + kps) };
                    let gap_end = if abs_sp == 0 && rlo == 0 { recent_start } else { 0 };
                    (start.max(lo)..hi).filter(|&kp| gap_end == 0 || kp < 64 || kp >= gap_end).collect()
                })
                .collect();
        }
        let p_lo = if self.swa && p_hi > EXT { p_hi - EXT } else { 0 };
        (p_lo / kps..=pos / kps).map(|abs_sp| ((abs_sp * kps).max(p_lo)..p_hi.min((abs_sp + 1) * kps)).collect()).collect()
    }
    /// The oldest key any row of the batch sees after position 64 (window lanes release the blocks before it).
    fn first_live_key(&self) -> usize {
        if self.swa {
            (self.pos0 + 1).saturating_sub(EXT)
        } else {
            0
        }
    }
}

/// The shapes the layout is about.
const CASES: [Case; 15] = [
    Case::full("full: one row, one key", 0, 1),
    Case::full("full: the first rows, rows that do not see the tile's later keys", 0, 40),
    Case::full("full: across the first split and block boundary, 16 rows and 1", 250, 17),
    Case::full("full: one row at the end of a block", 1023, 1),
    Case::full("full: one row at the start of a block", 1024, 1),
    Case::full("full: a tile ending on the last key the relative bias reaches", 3006, 70),
    Case::full("full: a tile starting on the first key past the relative bias", 3007, 33),
    Case { name: "full, far keys pruned to 2048", swa: false, pos0: 3000, nrows: 5, budget: 2048 },
    Case { name: "full, far keys pruned to 2048, the gap inside split 0", swa: false, pos0: 2100, nrows: 3, budget: 2048 },
    Case::window("window: the first rows", 0, 33),
    Case::window("window: the window starts to slide", 1000, 48),
    Case::window("window: 18 live blocks, rows on both sides of a block boundary", 2040, 17),
    Case::window("window: window starts on both sides of a block boundary", 1207, 32),
    Case::window("window: one row at the end of a block", 4095, 1),
    Case::window("window: one row at the start of a block", 4096, 1),
];

/// A deeper full pass than the list has: 20 splits, most of their tiles interior.
const DEEP: Case = Case::full("full: 5,000 keys deep, most tiles interior", 5000, 40);

/// A lane's K and V rows: `[plane][head][position][HD]` signed bytes.
struct Cache {
    n: usize,
    kv: Vec<i8>,
}

impl Cache {
    fn new(n: usize) -> Cache {
        Cache { n, kv: vec![0; 2 * NKV * n * HD] }
    }
    fn row(&self, plane: usize, g: usize, pos: usize) -> &[i8] {
        let at = ((plane * NKV + g) * self.n + pos) * HD;
        &self.kv[at..at + HD]
    }
    fn set(&mut self, plane: usize, g: usize, pos: usize, row: &[i8; HD]) {
        let at = ((plane * NKV + g) * self.n + pos) * HD;
        self.kv[at..at + HD].copy_from_slice(row);
    }
    /// Random vectors through the quantiser, their magnitudes spread over three octaves so that neighbouring rows
    /// carry different scales.
    fn random(n: usize, rng: &mut Rng) -> Cache {
        let mut c = Cache::new(n);
        let mut x = [0.0f32; HD];
        for plane in 0..2 {
            for g in 0..NKV {
                for pos in 0..n {
                    let amp = (0.25 + 0.75 * rng.unit().abs()) * 2f32.powi((rng.next() % 3) as i32);
                    x.iter_mut().for_each(|v| *v = rng.unit() * amp);
                    c.set(plane, g, pos, &kv8_quant_row(&x));
                }
            }
        }
        c
    }
}

// ---- where the rows live on the GPU

/// passes per pool slot in these tests, and the one the kernels are pointed at (`PreparedAttnArgs::k_base`)
const TEST_PASSES: usize = 2;
const TEST_PASS: u32 = 1;
const PASS_BYTES: usize = 2 * NKV * BLOCK * HD;
const SLOT_BYTES: usize = TEST_PASSES * PASS_BYTES;

/// Layer 3: 64-row blocks in pool slots, found through the lane's block table.
struct Paged {
    slabs: [Buf; 2],
    bt: Buf,
}

impl Paged {
    /// A window lane keeps its last `MIN_ROLLOVER_WINDOW_SLOTS` (18) blocks in a ring of as many slots: block `b`
    /// sits in slot `b % 18`, and the table entry of an older block is cleared. A full lane keeps every block,
    /// here scattered over two slabs in descending slots, so that no two neighbouring blocks are neighbours in
    /// memory. Every byte no live row owns is 0x7f: the largest value under the largest scale.
    fn new(gpu: &Gpu, cache: &Cache, case: &Case) -> Paged {
        let n_blks = cache.n.div_ceil(BLOCK);
        let ring = crate::blocks::MIN_ROLLOVER_WINDOW_SLOTS;
        let first_live = if case.swa { case.first_live_key() / BLOCK } else { 0 };
        assert!(!case.swa || n_blks - first_live <= ring, "{}: a window lane holds {ring} blocks", case.name);
        let slots_per_slab = if case.swa { ring } else { n_blks.div_ceil(2) };
        let slabs = [gpu.buffer(slots_per_slab * SLOT_BYTES), gpu.buffer(slots_per_slab * SLOT_BYTES)];
        let bt = gpu.buffer(n_blks * 8);
        unsafe {
            for slab in &slabs {
                std::ptr::write_bytes(slab.contents().as_ptr().cast::<u8>(), 0x7f, slots_per_slab * SLOT_BYTES);
            }
            let table = std::slice::from_raw_parts_mut(bt.contents().as_ptr().cast::<u64>(), n_blks);
            for (b, entry) in table.iter_mut().enumerate() {
                if b < first_live {
                    *entry = crate::blocks::CLEARED_GPU_TABLE_ENTRY;
                    continue;
                }
                let (slab, slot) = if case.swa { (0, b % ring) } else { (b % 2, slots_per_slab - 1 - b / 2) };
                *entry = ((slab as u64) << crate::blocks::KV_SLAB_SHIFT) | (slot * SLOT_BYTES) as u64;
                let base = slabs[slab].contents().as_ptr().cast::<u8>().add(slot * SLOT_BYTES + TEST_PASS as usize * PASS_BYTES);
                for plane in 0..2 {
                    for g in 0..NKV {
                        for ib in 0..BLOCK.min(cache.n - b * BLOCK) {
                            let src = cache.row(plane, g, b * BLOCK + ib);
                            let dst = base.add(((plane * NKV + g) * BLOCK + ib) * HD);
                            std::ptr::copy_nonoverlapping(src.as_ptr().cast::<u8>(), dst, HD);
                        }
                    }
                }
            }
        }
        Paged { slabs, bt }
    }
    fn bind(&self, e: &Enc) {
        e.buf(&self.slabs[0], 0, 3);
        e.buf(&self.bt, 0, 8);
        e.buf(&self.slabs[1], 0, 10);
        e.buf(&self.slabs[1], 0, 11);
        e.buf(&self.slabs[1], 0, 12);
    }
    fn bytes(&self) -> Vec<u8> {
        self.slabs.iter().flat_map(buffer_bytes).collect()
    }
}

/// Layer 2: one array per plane and head. Row `i` of a head is position `idx0 + i`.
struct Flat {
    buf: Buf,
    k_base: u32,
    v_base: u32,
    cap: u32,
    idx0: i32,
}

impl Flat {
    /// A full pass reads the lane's own cache (`idx0 = 0`); a window pass reads the scratch the engine copies the
    /// window into, whose row 0 is position `p0 - (EXT + KGUARD)` and whose capacity is `EXT + t + 2 * KGUARD`.
    /// Rows the batch has no position for stay 0x7f, as in `Paged`.
    fn new(gpu: &Gpu, cache: &Cache, case: &Case) -> Flat {
        let (idx0, cap) = if case.swa {
            (case.pos0 as i64 - (EXT + KGUARD) as i64, EXT + case.nrows + 2 * KGUARD)
        } else {
            (0, cache.n + 3)
        };
        // the bases are element offsets into the bound buffer: start the K plane away from 0
        let k_base = 4 * HD;
        let v_base = k_base + NKV * cap * HD;
        let len = v_base + NKV * cap * HD;
        let buf = gpu.buffer(len);
        unsafe {
            let p = buf.contents().as_ptr().cast::<u8>();
            std::ptr::write_bytes(p, 0x7f, len);
            for (plane, base) in [k_base, v_base].into_iter().enumerate() {
                for g in 0..NKV {
                    for pos in case.first_live_key()..cache.n {
                        let i = (pos as i64 - idx0) as usize;
                        assert!(i < cap);
                        std::ptr::copy_nonoverlapping(cache.row(plane, g, pos).as_ptr().cast::<u8>(), p.add(base + (g * cap + i) * HD), HD);
                    }
                }
            }
        }
        Flat { buf, k_base: k_base as u32, v_base: v_base as u32, cap: cap as u32, idx0: idx0 as i32 }
    }
}

fn buffer_bytes(b: &Buf) -> Vec<u8> {
    unsafe { std::slice::from_raw_parts(b.contents().as_ptr().cast::<u8>(), b.length()).to_vec() }
}

// ---- the queries and the partials

/// bytes into PB of the relative-bias table: `EXT` rows, and one more that no kernel may read
const RELB_AT: usize = 4096;
/// partial slots no kernel wrote keep this NaN
const UNWRITTEN: u32 = 0x7fc0_dead;

/// The query side of a batch: half queries, relative features and sinks, `[row][head][..]`.
struct Queries {
    q: Vec<u16>,
    r: Vec<f32>,
    sink: Vec<f32>,
}

impl Queries {
    fn random(nrows: usize, rng: &mut Rng) -> Queries {
        Queries {
            q: (0..nrows * NH * HD).map(|_| f32_to_f16_bits(rng.unit() * 0.25)).collect(),
            r: (0..nrows * NH * NREL).map(|_| rng.unit() * 0.5).collect(),
            sink: (0..nrows * NH).map(|_| rng.unit() * 0.7).collect(),
        }
    }
}

fn relbias_buffer(gpu: &Gpu, relb: &[f32]) -> Buf {
    assert_eq!(relb.len(), (EXT + 1) * NREL);
    let pb = gpu.buffer(RELB_AT + relb.len() * 4);
    unsafe { std::ptr::copy_nonoverlapping(relb.as_ptr(), pb.contents().as_ptr().cast::<u8>().add(RELB_AT).cast::<f32>(), relb.len()) };
    pb
}

/// The activation arena of one batch: the queries, then `parts` regions of split partials.
struct Arena {
    buf: Buf,
    r_off: usize,
    sink_off: usize,
    part0: usize,
    part_words: usize,
    nsplit: usize,
}

impl Arena {
    fn new(gpu: &Gpu, case: &Case, qs: &Queries, parts: usize) -> Arena {
        let nsplit = case.nsplit();
        let q_words = (case.nrows * NH * HD).div_ceil(2);
        let (r_off, sink_off) = (q_words, q_words + qs.r.len());
        let part0 = (sink_off + qs.sink.len()).next_multiple_of(64);
        let part_words = case.nrows * NH * nsplit * (HD + 2);
        let buf = gpu.buffer((part0 + parts * part_words) * 4);
        unsafe {
            let a = buf.contents().as_ptr().cast::<f32>();
            std::ptr::copy_nonoverlapping(qs.q.as_ptr(), a.cast::<u16>(), qs.q.len());
            std::ptr::copy_nonoverlapping(qs.r.as_ptr(), a.add(r_off), qs.r.len());
            std::ptr::copy_nonoverlapping(qs.sink.as_ptr(), a.add(sink_off), qs.sink.len());
            std::slice::from_raw_parts_mut(a.add(part0).cast::<u32>(), parts * part_words).fill(UNWRITTEN);
        }
        Arena { buf, r_off, sink_off, part0, part_words, nsplit }
    }
    fn part(&self, i: usize) -> &[f32] {
        unsafe { std::slice::from_raw_parts(self.buf.contents().as_ptr().cast::<f32>().add(self.part0 + i * self.part_words), self.part_words) }
    }
    fn args(&self, case: &Case, part: usize) -> PreparedAttnArgs {
        PreparedAttnArgs {
            pos0: case.pos0 as u32,
            window: if case.swa { EXT as u32 } else { 0 },
            cap: 0,
            idx0: 0,
            k_base: TEST_PASS,
            v_base: 0,
            q_off: 0,
            r_off: self.r_off as u32,
            sink_off: self.sink_off as u32,
            gate_off: 0,
            out_off: 0,
            relbias_w: RELB_AT as u32,
            part_off: (self.part0 + part * self.part_words) as u32,
            kps: case.kps() as u32,
            nsplit: self.nsplit as u32,
            half_io: 1,
            ring: 0,
            full_budget: case.budget as u32,
            kv4_slot: 0,
            tg_rows: 1,
            nrows: case.nrows as u32,
            pad: [0; 3],
        }
    }
}

enum Store<'a> {
    Paged(&'a Paged),
    Flat(&'a Flat),
}

/// Dispatch one prefill attention batch the way `Engine::encode_spans` does, on the tensor-core kernel (`tc`) or the
/// simdgroup kernel, into partial region `part`. Returns the GPU seconds of the command buffer.
fn attend(gpu: &Gpu, pb: &Buf, arena: &Arena, part: usize, case: &Case, store: &Store, tc: bool) -> f64 {
    attend_on_grid(gpu, pb, arena, part, case, store, tc, false)
}

/// `attend`, with the tensor-core kernels optionally on the old split-major grid (`x` split column, `z` row block),
/// for kernels built with `TC_ATT_GRID_SPLIT_X`.
#[allow(clippy::too_many_arguments)]
fn attend_on_grid(gpu: &Gpu, pb: &Buf, arena: &Arena, part: usize, case: &Case, store: &Store, tc: bool, split_major: bool) -> f64 {
    let (tg_rows, grid_x) = prefill_attn_grid(tc, case.swa, case.end(), case.budget as u32, arena.nsplit);
    let tc_grid = |nrows: usize| {
        if split_major {
            (grid_x, NKV, nrows.div_ceil(tg_rows))
        } else {
            tc_attn_dispatch_grid(false, grid_x, nrows, tg_rows)
        }
    };
    let mut args = arena.args(case, part);
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(pb, 0, 1);
    e.buf(&arena.buf, 0, 2);
    let (kernel, grid, threads) = match store {
        Store::Paged(paged) => {
            paged.bind(&e);
            args.tg_rows = tg_rows as u32;
            let name = if tc { "k_attn_tc_fixed_blk" } else { "k_attn_fixed_b_blk" };
            (name, if tc { tc_grid(case.nrows) } else { (grid_x, NKV, case.nrows.div_ceil(tg_rows)) }, if tc { 96 } else { 128 })
        }
        Store::Flat(flat) => {
            e.buf(&flat.buf, 0, 3);
            (args.cap, args.idx0, args.k_base, args.v_base) = (flat.cap, flat.idx0, flat.k_base, flat.v_base);
            // the Layer 2 simdgroup kernel takes one row per threadgroup
            args.tg_rows = if tc { tg_rows as u32 } else { 1 };
            if tc {
                ("k_attn_tc_fixed_b", tc_grid(case.nrows), 96)
            } else {
                ("k_attn_fixed_b", (grid_x, NKV, case.nrows), 128)
            }
        }
    };
    e.bytes(&args, 5);
    e.pso(&gpu.pso(kernel));
    e.dispatch(grid, threads);
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    Engine::assert_cmd_ok(&cb, kernel);
    cb.GPUEndTime() - cb.GPUStartTime()
}

/// One row's partial slot `sp` of head `h`: `[max logit, sum of weights, HD weighted sums]`.
fn slot<'a>(part: &'a [f32], nsplit: usize, row: usize, h: usize, sp: usize) -> &'a [f32] {
    let at = ((row * NH + h) * nsplit + sp) * (HD + 2);
    &part[at..at + HD + 2]
}

/// Every slot a row has a split for is written whole, and every other slot is untouched.
fn assert_slots_written(what: &str, case: &Case, part: &[f32], nsplit: usize) {
    for row in 0..case.nrows {
        let count = case.row_splits(case.pos0 + row).len();
        assert!(count <= nsplit, "{what}: {}: row {row} has {count} splits for {nsplit} slots", case.name);
        for h in 0..NH {
            for sp in 0..nsplit {
                let unwritten = slot(part, nsplit, row, h, sp).iter().filter(|x| x.to_bits() == UNWRITTEN).count();
                let want = if sp < count { 0 } else { HD + 2 };
                assert_eq!(unwritten, want, "{what}: {}: row {row} head {h} slot {sp} of {count}", case.name);
            }
        }
    }
}

/// `k_attn_fixed_combine` in double precision: the attention output of every row and head before the gate.
fn combine(case: &Case, part: &[f32], nsplit: usize) -> Vec<f64> {
    let mut out = vec![0.0f64; case.nrows * NH * HD];
    for row in 0..case.nrows {
        let count = case.row_splits(case.pos0 + row).len();
        for h in 0..NH {
            let m = (0..count).fold(0.0f64, |m, sp| m.max(f64::from(slot(part, nsplit, row, h, sp)[0])));
            let mut l = (-m).exp();
            let o = &mut out[(row * NH + h) * HD..][..HD];
            for sp in 0..count {
                let p = slot(part, nsplit, row, h, sp);
                let w = (f64::from(p[0]) - m).exp();
                l += w * f64::from(p[1]);
                o.iter_mut().zip(&p[2..]).for_each(|(o, &x)| *o += w * f64::from(x));
            }
            o.iter_mut().for_each(|o| *o /= l);
        }
    }
    out
}

/// The attention output from the cache bytes in double precision, with no tiles and no splits: for every row and
/// head, the softmax over the sink (logit 0) and the keys the row sees of `q . (K_int * ks) + r . B[distance] - sink`,
/// applied to `V_int * vs`.
fn reference(case: &Case, cache: &Cache, qs: &Queries, relb: &[f32]) -> Vec<f64> {
    let mut out = vec![0.0f64; case.nrows * NH * HD];
    let mut scores = Vec::new();
    for row in 0..case.nrows {
        let pos = case.pos0 + row;
        let keys: Vec<usize> = case.row_splits(pos).into_iter().flatten().collect();
        for h in 0..NH {
            let g = h / 3;
            let q: Vec<f64> = qs.q[(row * NH + h) * HD..][..HD].iter().map(|&b| f64::from(f16_bits_to_f32(b))).collect();
            let r = &qs.r[(row * NH + h) * NREL..][..NREL];
            let sink = f64::from(qs.sink[row * NH + h]);
            scores.clear();
            for &kp in &keys {
                let k = cache.row(0, g, kp);
                let ks = f64::from(kv8_vscale_cpu(as_bytes(k)));
                let mut s = q.iter().zip(k).map(|(q, &k)| q * f64::from(k)).sum::<f64>() * ks;
                if pos - kp < EXT {
                    s += r.iter().zip(&relb[(pos - kp) * NREL..]).map(|(&r, &b)| f64::from(r) * f64::from(b)).sum::<f64>();
                }
                scores.push(s - sink);
            }
            let m = scores.iter().fold(0.0f64, |m, &s| m.max(s));
            let mut l = (-m).exp();
            let o = &mut out[(row * NH + h) * HD..][..HD];
            for (&kp, &s) in keys.iter().zip(&scores) {
                let v = cache.row(1, g, kp);
                let w = (s - m).exp();
                l += w;
                let wv = w * f64::from(kv8_vscale_cpu(as_bytes(v)));
                o.iter_mut().zip(v).for_each(|(o, &v)| *o += wv * f64::from(v));
            }
            o.iter_mut().for_each(|o| *o /= l);
        }
    }
    out
}

/// (largest absolute difference, largest difference of a row and head relative to the largest magnitude of its
/// reference vector)
fn difference(a: &[f64], b: &[f64]) -> (f64, f64) {
    let (mut abs, mut rel) = (0.0f64, 0.0f64);
    for (a, b) in a.chunks(HD).zip(b.chunks(HD)) {
        let d = a.iter().zip(b).fold(0.0f64, |m, (a, b)| m.max((a - b).abs()));
        let scale = b.iter().fold(0.0f64, |m, b| m.max(b.abs()));
        assert!(d.is_finite() && scale.is_finite(), "non-finite attention output");
        abs = abs.max(d);
        rel = rel.max(d / scale.max(1e-3));
    }
    (abs, rel)
}

/// The KV8 kernels, compiled from the shader sources after `edit` (nothing, or a planted slip).
fn kv8_gpu_edited(defines: &str, kernels: &[&str], edit: &dyn Fn(&str) -> String) -> Gpu {
    let src = format!("#define KV8 1\n{defines}{}\n{}", include_str!("../kernels.metal"), edit(include_str!("../prefill.metal")));
    Gpu::new(&src, kernels)
}

fn kv8_gpu(defines: &str, kernels: &[&str]) -> Gpu {
    kv8_gpu_edited(defines, kernels, &str::to_string)
}

const ATTN_KERNELS: [&str; 4] = ["k_attn_tc_fixed_blk", "k_attn_tc_fixed_b", "k_attn_fixed_b_blk", "k_attn_fixed_b"];

/// The two builds every check runs: the kernels as the engine compiles them, and the same with the tensor-core
/// kernels' interior fast path compiled out.
struct Kernels {
    gpu: Gpu,
    plain: Gpu,
}

impl Kernels {
    fn new(edit: &dyn Fn(&str) -> String) -> Kernels {
        Kernels { gpu: kv8_gpu_edited("", &ATTN_KERNELS, edit), plain: kv8_gpu_edited("#define TC_KV8_NO_INTERIOR 1\n", &ATTN_KERNELS, edit) }
    }
}

/// partial regions of one case: (tensor cores, tensor cores without the interior fast path, simdgroups) x (Layer 3, Layer 2)
const TC_L3: usize = 0;
const TC_L2: usize = 1;
const PLAIN_L3: usize = 2;
const PLAIN_L2: usize = 3;
const SIMD_L3: usize = 4;
const SIMD_L2: usize = 5;
const PARTS: [&str; 6] = [
    "tensor cores, Layer 3",
    "tensor cores, Layer 2",
    "tensor cores without the interior path, Layer 3",
    "tensor cores without the interior path, Layer 2",
    "simdgroups, Layer 3",
    "simdgroups, Layer 2",
];

/// Run all six kernels of a case over the same cache and queries. Every kernel must write the slots the rows have
/// and no other, and leave every cache byte as it found it.
fn attend_all(k: &Kernels, pb: &Buf, case: &Case, cache: &Cache, qs: &Queries) -> Arena {
    let (paged, flat) = (Paged::new(&k.gpu, cache, case), Flat::new(&k.gpu, cache, case));
    let (paged_before, flat_before) = (paged.bytes(), buffer_bytes(&flat.buf));
    let arena = Arena::new(&k.gpu, case, qs, PARTS.len());
    for (part, name) in PARTS.iter().enumerate() {
        let store = if part % 2 == 0 { Store::Paged(&paged) } else { Store::Flat(&flat) };
        let on = if part == PLAIN_L3 || part == PLAIN_L2 { &k.plain } else { &k.gpu };
        attend(on, pb, &arena, part, case, &store, part < SIMD_L3);
        assert_slots_written(name, case, arena.part(part), arena.nsplit);
        assert!(paged.bytes() == paged_before && buffer_bytes(&flat.buf) == flat_before, "{name}: {}: attention wrote the cache", case.name);
    }
    arena
}

/// Values that differ in bits between two partial regions, over the slots the rows have.
fn differing_values(case: &Case, a: &[f32], b: &[f32], nsplit: usize) -> usize {
    let mut n = 0;
    for row in 0..case.nrows {
        for sp in 0..case.row_splits(case.pos0 + row).len() {
            for h in 0..NH {
                let (x, y) = (slot(a, nsplit, row, h, sp), slot(b, nsplit, row, h, sp));
                n += x.iter().zip(y).filter(|(x, y)| x.to_bits() != y.to_bits()).count();
            }
        }
    }
    n
}

// ---- the key census: every key every row sees, counted exactly, at any depth
//
// The cache and the queries are built so that each kernel's arithmetic is exact whatever order it sums in, and so
// that a key's row, its head, its V scale and its distance each leave a mark:
// - K: the row of key `kp` of head `g` is all zero when `(kp + g) % 5 != 2` (score 0), otherwise it scores
//   -2,080,768 through one byte and a scale of 1.
// - Relative bias: the table is -4096 at every third distance below `EXT` (and in the row past the table, which
//   nothing may read), so a row kills every third key within reach, its own position among them.
// - V: one-hot, a 1 in dimension `8 + (kp + 7 g) % 113`, with a scale of 1/2, 1 or 2 by `(kp + g) % 3`.
//
// A score is then minus the sum of its penalties, exactly, and a split's partial is the max score, the number of
// keys that reach it, and in each dimension the sum of the V scales of those among them that point there: small
// dyadic numbers that say which keys took part. One key more or less, a key from the wrong row, block or head, a V
// scale from a neighbour, or the bias at the wrong distance each move one of them by at least 1/2.

fn census_cache(n: usize) -> Cache {
    let mut c = Cache::new(n);
    for g in 0..NKV {
        for kp in 0..n {
            if (kp + g) % 5 == 2 {
                c.set(0, g, kp, &kv8_row_with_code(136, |d| if d == 9 { -127 } else { 0 }));
            }
            let class = 8 + (kp + 7 * g) % 113;
            c.set(1, g, kp, &kv8_row_with_code(128 + 8 * ((kp + g) % 3) as u32, |d| i8::from(d == class)));
        }
    }
    c
}

const CENSUS_Q9: f32 = 16384.0;
const CENSUS_K_PENALTY: f64 = -127.0 * 16384.0;
const CENSUS_BIAS_PENALTY: f64 = -4096.0;

fn census_queries(nrows: usize) -> (Queries, Vec<f32>) {
    let mut qs = Queries { q: vec![0; nrows * NH * HD], r: vec![0.0; nrows * NH * NREL], sink: vec![0.0; nrows * NH] };
    qs.q.iter_mut().skip(9).step_by(HD).for_each(|q| *q = f32_to_f16_bits(CENSUS_Q9));
    qs.r.iter_mut().step_by(NREL).for_each(|r| *r = 1.0);
    let mut relb = vec![0.0f32; (EXT + 1) * NREL];
    for dist in (0..EXT).step_by(3).chain([EXT]) {
        relb[dist * NREL] = CENSUS_BIAS_PENALTY as f32;
    }
    (qs, relb)
}

/// What the split holding `keys` of the row at `pos` must be for KV head `g`: (max score, keys at the max, sums
/// per dimension).
fn census_expect(pos: usize, g: usize, keys: &[usize]) -> (f64, f64, [f64; HD]) {
    let score = |kp: usize| {
        let k = if (kp + g) % 5 == 2 { CENSUS_K_PENALTY } else { 0.0 };
        let b = if pos - kp < EXT && (pos - kp) % 3 == 0 { CENSUS_BIAS_PENALTY } else { 0.0 };
        k + b
    };
    let m = keys.iter().map(|&kp| score(kp)).fold(f64::NEG_INFINITY, f64::max);
    let (mut n, mut sums) = (0.0, [0.0f64; HD]);
    for &kp in keys.iter().filter(|&&kp| score(kp) == m) {
        let code = 128 + 8 * ((kp + g) % 3) as u32;
        let vs = f64::from(kv8_scale(code));
        n += 1.0;
        sums[8 + (kp + 7 * g) % 113] += vs;
        // bytes 0..7 of the V row carry its code: a 1 wherever the code has a bit
        for (d, sum) in sums[..8].iter_mut().enumerate() {
            *sum += vs * f64::from((code >> (7 - d)) & 1);
        }
    }
    (m, n, sums)
}

/// The key census of one case on all six kernels: the partials checked, or the first that is wrong.
fn key_census(k: &Kernels, case: &Case) -> Result<usize, String> {
    let cache = census_cache(case.end());
    let (qs, relb) = census_queries(case.nrows);
    let pb = relbias_buffer(&k.gpu, &relb);
    let arena = attend_all(k, &pb, case, &cache, &qs);
    let mut checked = 0;
    for (part, name) in PARTS.iter().enumerate() {
        let p = arena.part(part);
        for row in 0..case.nrows {
            let pos = case.pos0 + row;
            for (sp, keys) in case.row_splits(pos).iter().enumerate() {
                for h in 0..NH {
                    let (m, n, sums) = census_expect(pos, h / 3, keys);
                    let got = slot(p, arena.nsplit, row, h, sp);
                    let at = format!("{name}: {}: row {row} (position {pos}) head {h} split {sp}", case.name);
                    if f64::from(got[0]) != m {
                        return Err(format!("{at}: max score {}, expected {m}", got[0]));
                    }
                    // the simdgroup kernels count in ones; the tensor-core kernels in e^8, scaled back
                    if (f64::from(got[1]) - n).abs() > 1e-4 * n {
                        return Err(format!("{at}: {} keys at the max, expected {n}", got[1]));
                    }
                    for (d, (&x, &want)) in got[2..].iter().zip(&sums).enumerate() {
                        if (f64::from(x) - want).abs() > 1e-4 * want.max(1.0) {
                            return Err(format!("{at}: dimension {d} sums {x}, expected {want}"));
                        }
                    }
                    checked += 1;
                }
            }
        }
    }
    Ok(checked)
}

// ---- the score census: the K side, exactly
//
// Key `kp` of head `g` scores `a * ks` and nothing else: `a` is a byte from 1 to 96 that depends on the key and the
// head, `ks` the row's scale, 1/2, 1 or 2. Every score is a multiple of 1/2 below 200, so the max of a split is exact
// in any order, and it names one key: its byte and its scale, from its own row.

fn score_census_byte(kp: usize, g: usize) -> i8 {
    (1 + (kp.wrapping_mul(2_654_435_761) >> 7).wrapping_add(g * 29) % 96) as i8
}

fn score_census_code(kp: usize, g: usize) -> u32 {
    128 + 8 * ((kp + 2 * g) % 3) as u32
}

/// The score census of one case on all six kernels: the partials checked, or the first whose max is wrong.
fn score_census(k: &Kernels, case: &Case) -> Result<usize, String> {
    let mut cache = census_cache(case.end());
    for g in 0..NKV {
        for kp in 0..case.end() {
            let byte = score_census_byte(kp, g);
            cache.set(0, g, kp, &kv8_row_with_code(score_census_code(kp, g), |d| if d == 9 { byte } else { 0 }));
        }
    }
    let mut qs = Queries { q: vec![0; case.nrows * NH * HD], r: vec![0.0; case.nrows * NH * NREL], sink: vec![0.0; case.nrows * NH] };
    qs.q.iter_mut().skip(9).step_by(HD).for_each(|q| *q = f32_to_f16_bits(1.0));
    let pb = relbias_buffer(&k.gpu, &vec![0.0; (EXT + 1) * NREL]);
    let arena = attend_all(k, &pb, case, &cache, &qs);
    let mut checked = 0;
    for (part, name) in PARTS.iter().enumerate() {
        let p = arena.part(part);
        for row in 0..case.nrows {
            let pos = case.pos0 + row;
            for (sp, keys) in case.row_splits(pos).iter().enumerate() {
                for h in 0..NH {
                    let g = h / 3;
                    let score = |kp: usize| f64::from(score_census_byte(kp, g)) * f64::from(kv8_scale(score_census_code(kp, g)));
                    let m = keys.iter().map(|&kp| score(kp)).fold(f64::NEG_INFINITY, f64::max);
                    let got = slot(p, arena.nsplit, row, h, sp)[0];
                    if f64::from(got) != m {
                        return Err(format!("{name}: {}: row {row} (position {pos}) head {h} split {sp}: max score {got}, expected {m}", case.name));
                    }
                    checked += 1;
                }
            }
        }
    }
    Ok(checked)
}

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_prefill_attention_sees_exactly_the_keys_of_every_row() {
    let k = Kernels::new(&str::to_string);
    for case in CASES.iter().chain([&DEEP]) {
        let keys = key_census(&k, case).unwrap_or_else(|e| panic!("{e}"));
        let scores = score_census(&k, case).unwrap_or_else(|e| panic!("{e}"));
        eprintln!("[kv8-tc census] {}: {keys} partials and {scores} max scores exact on 6 kernels", case.name);
    }
}

// ---- random data: the simdgroup kernels and a CPU reference

/// Largest difference of an attention output (a softmax-weighted mean of V rows, of magnitude about 1) allowed
/// between two float32 evaluations, or between one and the double-precision reference. On an M3 Ultra the
/// tensor-core kernels sit 4e-6 from the reference and the simdgroup kernels 2e-6. A wrong scale, bit or row is a
/// difference of percents; a single key is the census's to catch.
const MAX_ABS: f64 = 5e-5;
const MAX_REL: f64 = 5e-5;

/// (absolute, relative) differences of one case
struct Agreement {
    tc: (f64, f64),
    simd: (f64, f64),
    pair: (f64, f64),
    /// values that differ in bits between Layer 2 and Layer 3 on the tensor cores
    layers_differ: usize,
}

fn worse(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {
    (a.0.max(b.0), a.1.max(b.1))
}

/// One case on random data: the tensor-core kernels against the CPU reference and against the simdgroup kernels,
/// within `MAX_ABS` and `MAX_REL`, and bit for bit against themselves without the interior fast path.
fn random_agreement(k: &Kernels, pb: &Buf, relb: &[f32], case: &Case, rng: &mut Rng) -> Result<Agreement, String> {
    let cache = Cache::random(case.end(), rng);
    let qs = Queries::random(case.nrows, rng);
    let arena = attend_all(k, pb, case, &cache, &qs);
    let want = reference(case, &cache, &qs, relb);
    let out: Vec<Vec<f64>> = (0..PARTS.len()).map(|part| combine(case, arena.part(part), arena.nsplit)).collect();
    // The interior fast path is the general path's arithmetic: not one bit differs.
    for (fast, general) in [(TC_L3, PLAIN_L3), (TC_L2, PLAIN_L2)] {
        let n = differing_values(case, arena.part(fast), arena.part(general), arena.nsplit);
        if n != 0 {
            return Err(format!("{}: {} differs from the general path in {n} values", case.name, PARTS[fast]));
        }
    }
    let a = Agreement {
        tc: worse(difference(&out[TC_L3], &want), difference(&out[TC_L2], &want)),
        simd: worse(difference(&out[SIMD_L3], &want), difference(&out[SIMD_L2], &want)),
        pair: worse(difference(&out[TC_L3], &out[SIMD_L3]), difference(&out[TC_L2], &out[SIMD_L2])),
        // Layer 2 against Layer 3 on the tensor cores: the same tiles through another address. Reported, not
        // required: nothing in the default mode rests on it.
        layers_differ: differing_values(case, arena.part(TC_L3), arena.part(TC_L2), arena.nsplit),
    };
    // the tensor-core kernels get no more room than the simdgroup kernels
    for (what, (abs, rel)) in [("tensor cores vs reference", a.tc), ("simdgroups vs reference", a.simd), ("tensor cores vs simdgroups", a.pair)] {
        if abs.is_nan() || rel.is_nan() || abs > MAX_ABS || rel > MAX_REL {
            return Err(format!("{}: {what}: {abs:.3e} abs, {rel:.3e} rel exceeds {MAX_ABS:.0e} / {MAX_REL:.0e}", case.name));
        }
    }
    Ok(a)
}

/// The relative-bias table of the random-data checks: random, and NaN in the row past the table.
fn random_relbias(rng: &mut Rng) -> Vec<f32> {
    (0..(EXT + 1) * NREL).map(|i| if i < EXT * NREL { rng.unit() * 0.25 } else { f32::NAN }).collect()
}

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_prefill_attention_matches_the_simdgroup_kernels_and_a_cpu_reference() {
    let k = Kernels::new(&str::to_string);
    let mut rng = Rng::new(0x6b76_3874_63);
    let relb = random_relbias(&mut rng);
    let pb = relbias_buffer(&k.gpu, &relb);
    let (mut tc, mut simd, mut pair, mut layers_differ) = ((0.0, 0.0), (0.0, 0.0), (0.0, 0.0), 0);
    for case in CASES.iter().chain([&DEEP]) {
        let a = random_agreement(&k, &pb, &relb, case, &mut rng).unwrap_or_else(|e| panic!("{e}"));
        eprintln!(
            "[kv8-tc] {:<70} vs reference: tc {:.2e}/{:.2e} simd {:.2e}/{:.2e} (abs/rel); tc vs simd {:.2e}/{:.2e}; L2 vs L3 differ in {} values",
            case.name, a.tc.0, a.tc.1, a.simd.0, a.simd.1, a.pair.0, a.pair.1, a.layers_differ
        );
        (tc, simd, pair, layers_differ) = (worse(tc, a.tc), worse(simd, a.simd), worse(pair, a.pair), layers_differ + a.layers_differ);
    }
    eprintln!(
        "[kv8-tc] worst vs reference: tensor cores {:.2e} abs {:.2e} rel, simdgroups {:.2e} abs {:.2e} rel; tensor cores vs simdgroups {:.2e} abs {:.2e} rel; Layer 2 vs Layer 3 on the tensor cores: {}",
        tc.0,
        tc.1,
        simd.0,
        simd.1,
        pair.0,
        pair.1,
        if layers_differ == 0 { "bit-identical".to_string() } else { format!("{layers_differ} values differ") }
    );
}

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_prefill_attention_is_bit_identical_to_the_split_major_grid_and_separate_score_tile() {
    // The tensor-core kernels as the engine builds them against the layout they replaced: the split-major grid
    // (`TC_ATT_GRID_SPLIT_X`) and a score tile apart from the weight tile (`TC_ATT_SEPARATE_SP`), each alone and
    // both together (the kernels before the change). Every partial slot must match bit for bit, on both layers.
    // Then FP16 and KV4 on their own grids (below).
    let tc = ["k_attn_tc_fixed_blk", "k_attn_tc_fixed_b"];
    let now = kv8_gpu("", &tc);
    let builds: [(&str, Gpu, bool); 3] = [
        ("split-major grid, separate S tile", kv8_gpu("#define TC_ATT_GRID_SPLIT_X 1\n#define TC_ATT_SEPARATE_SP 1\n", &tc), true),
        ("split-major grid", kv8_gpu("#define TC_ATT_GRID_SPLIT_X 1\n", &tc), true),
        ("separate S tile", kv8_gpu("#define TC_ATT_SEPARATE_SP 1\n", &tc), false),
    ];
    let mut rng = Rng::new(0x6772_6964);
    let relb = random_relbias(&mut rng);
    let pb = relbias_buffer(&now, &relb);
    let mut compared = 0usize;
    for case in CASES.iter().chain([&DEEP]) {
        let cache = Cache::random(case.end(), &mut rng);
        let qs = Queries::random(case.nrows, &mut rng);
        let (paged, flat) = (Paged::new(&now, &cache, case), Flat::new(&now, &cache, case));
        let arena = Arena::new(&now, case, &qs, 2 * (builds.len() + 1));
        for layer in 0..2 {
            let store = if layer == 0 { Store::Paged(&paged) } else { Store::Flat(&flat) };
            attend(&now, &pb, &arena, layer, case, &store, true);
            assert_slots_written("now", case, arena.part(layer), arena.nsplit);
            for (b, (name, gpu, split_major)) in builds.iter().enumerate() {
                let part = 2 * (b + 1) + layer;
                attend_on_grid(gpu, &pb, &arena, part, case, &store, true, *split_major);
                assert_slots_written(name, case, arena.part(part), arena.nsplit);
                let n = differing_values(case, arena.part(layer), arena.part(part), arena.nsplit);
                assert_eq!(n, 0, "{}: Layer {}: {n} values differ from the build with {name}", case.name, 3 - layer);
                compared += case.nrows;
            }
        }
    }
    eprintln!("[kv8-tc grid] {compared} rows x builds x layers bit-identical over {} cases", CASES.len() + 1);

    // FP16 and KV4 through `k_attn_tc_fixed_b`, each on the grid the engine dispatches for it
    // (`tc_attn_dispatch_grid`: row-major for FP16, split-major for KV4), against the build with both old-layout
    // switches on the split-major grid. A control dispatches each engine build on the other format's grid: the
    // kernels decode the grid per format, so that must not match.
    let base = format!("{}\n{}", include_str!("../kernels.metal"), include_str!("../prefill.metal"));
    let old = "#define TC_ATT_GRID_SPLIT_X 1\n#define TC_ATT_SEPARATE_SP 1\n";
    for kv4 in [false, true] {
        let fmt = if kv4 { "#define KV4 1\n#define KV4_DC_OFF 256u\n" } else { "" };
        let mname = if kv4 { "kv4" } else { "fp16" };
        let now = Gpu::new(&format!("{fmt}{base}"), &["k_attn_tc_fixed_b"]);
        let was = Gpu::new(&format!("{fmt}{old}{base}"), &["k_attn_tc_fixed_b"]);
        for (pos0, nrows) in [(250usize, 17usize), (3006, 70), (5000, 40)] {
            let end = pos0 + nrows;
            let cap = end.div_ceil(BLOCK) * BLOCK;
            let nsplit = fixed_attn_nsplit(false, end);
            let row_b = if kv4 { crate::blocks::KV4_ROW_BYTES as usize } else { 2 * HD };
            let mut kv = vec![0u8; 2 * NKV * cap * row_b];
            for row in kv.chunks_mut(row_b) {
                if kv4 {
                    row[..64].iter_mut().for_each(|b| *b = rng.next() as u8);
                    row[64..].copy_from_slice(&f32_to_f16_bits(0.02 + 0.06 * rng.unit().abs()).to_le_bytes());
                } else {
                    row.chunks_mut(2).for_each(|h| h.copy_from_slice(&f32_to_f16_bits(rng.unit()).to_le_bytes()));
                }
            }
            let q_words = nrows * NH * HD / 2;
            let (r_words, sink_words, part_words) = (nrows * NH * NREL, nrows * NH, nrows * NH * nsplit * (HD + 2));
            let mut act = vec![UNWRITTEN; q_words + r_words + sink_words + part_words];
            for w in &mut act[..q_words] {
                *w = u32::from(f32_to_f16_bits(rng.unit())) | (u32::from(f32_to_f16_bits(rng.unit())) << 16);
            }
            act[q_words..q_words + r_words].iter_mut().for_each(|w| *w = (rng.unit() * 0.25).to_bits());
            act[q_words + r_words..q_words + r_words + sink_words].iter_mut().for_each(|w| *w = rng.unit().to_bits());
            let relb = random_relbias(&mut rng);
            let run = |g: &Gpu, grid: (usize, usize, usize)| -> Vec<u32> {
                let (kv_b, pb_b) = (g.buffer_with(&kv), relbias_buffer(g, &relb));
                let act_b = g.buffer_with(unsafe { std::slice::from_raw_parts(act.as_ptr().cast::<u8>(), act.len() * 4) });
                let args = PreparedAttnArgs {
                    pos0: pos0 as u32,
                    window: 0,
                    cap: cap as u32,
                    idx0: 0,
                    k_base: 0,
                    v_base: if kv4 { (NKV * cap) as u32 } else { (NKV * cap * HD) as u32 },
                    q_off: 0,
                    r_off: q_words as u32,
                    sink_off: (q_words + r_words) as u32,
                    gate_off: 0,
                    out_off: 0,
                    relbias_w: 0,
                    part_off: (q_words + r_words + sink_words) as u32,
                    kps: decode_split_kps(false, 0) as u32,
                    nsplit: nsplit as u32,
                    half_io: 1,
                    ring: 0,
                    full_budget: 0,
                    kv4_slot: 0,
                    tg_rows: TC_ATT_TG_ROWS as u32,
                    nrows: nrows as u32,
                    pad: [0; 3],
                };
                let cb = g.cmd();
                let e = Enc::new(&cb);
                e.buf(&pb_b, 0, 1);
                e.buf(&act_b, 0, 2);
                e.buf(&kv_b, 0, 3);
                e.bytes(&args, 5);
                e.pso(&g.pso("k_attn_tc_fixed_b"));
                e.dispatch(grid, 96);
                e.end();
                cb.commit();
                cb.waitUntilCompleted();
                Engine::assert_cmd_ok(&cb, mname);
                let out = unsafe { std::slice::from_raw_parts(act_b.contents().as_ptr().cast::<u32>(), act.len()) };
                out[q_words + r_words + sink_words..].to_vec()
            };
            let split_major = (nsplit, NKV, nrows.div_ceil(TC_ATT_TG_ROWS));
            let row_major = (nrows.div_ceil(TC_ATT_TG_ROWS), NKV, nsplit);
            let engine_grid = tc_attn_dispatch_grid(kv4, nsplit, nrows, TC_ATT_TG_ROWS);
            assert_eq!(engine_grid, if kv4 { split_major } else { row_major }, "{mname}: the engine's grid");
            let want = run(&was, split_major);
            assert!(want.iter().filter(|&&w| w != UNWRITTEN).count() > part_words / 2, "{mname} {pos0}+{nrows}: too few slots written");
            let got = run(&now, engine_grid);
            let n = got.iter().zip(&want).filter(|(a, b)| a != b).count();
            assert_eq!(n, 0, "{mname} {pos0}+{nrows}: {n} partial words differ from the old layout on the split-major grid");
            if split_major != row_major {
                let other = run(&now, if kv4 { row_major } else { split_major });
                assert!(other != want, "{mname} {pos0}+{nrows}: the other format's grid must not match (the control)");
            }
            eprintln!("[tc grid] {mname} {pos0}+{nrows}: {part_words} partial words bit-identical to the old layout");
        }
    }
}

// ---- FP16 and KV4 caches for `k_attn_tc_fixed_blk`, model-free

/// A paged FP16 or KV4 (`kv4`) cache of `n` positions of random rows, every block in one slab: (slab, block table).
fn other_format_slab(gpu: &Gpu, n: usize, kv4: bool, rng: &mut Rng) -> (Buf, Buf) {
    let row_bytes = if kv4 { crate::blocks::KV4_ROW_BYTES as usize } else { 2 * HD };
    let n_blks = n.div_ceil(BLOCK);
    let pass_bytes = 2 * NKV * BLOCK * row_bytes;
    let (slab, bt) = (gpu.buffer(n_blks * pass_bytes), gpu.buffer(n_blks * 8));
    unsafe {
        let table = std::slice::from_raw_parts_mut(bt.contents().as_ptr().cast::<u64>(), n_blks);
        table.iter_mut().enumerate().for_each(|(b, e)| *e = (b * pass_bytes) as u64);
        let bytes = std::slice::from_raw_parts_mut(slab.contents().as_ptr().cast::<u8>(), n_blks * pass_bytes);
        for row in bytes.chunks_mut(row_bytes) {
            if kv4 {
                row[..64].iter_mut().for_each(|b| *b = rng.next() as u8);
                row[64..].copy_from_slice(&f32_to_f16_bits(0.05 + rng.unit().abs() * 0.8).to_le_bytes());
            } else {
                row.chunks_mut(2).for_each(|h| h.copy_from_slice(&f32_to_f16_bits(rng.unit() * 0.9).to_le_bytes()));
            }
        }
    }
    (slab, bt)
}

/// One `k_attn_tc_fixed_blk` batch over an `other_format_slab` cache into partial region `part`, on the grid the
/// engine dispatches for the format. Returns the GPU seconds of the command buffer.
fn attend_other_format(gpu: &Gpu, pb: &Buf, arena: &Arena, part: usize, case: &Case, kv4: bool, slab: &(Buf, Buf)) -> f64 {
    let (tg_rows, grid_x) = prefill_attn_grid(true, case.swa, case.end(), case.budget as u32, arena.nsplit);
    let args = PreparedAttnArgs { k_base: 0, tg_rows: tg_rows as u32, ..arena.args(case, part) };
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(pb, 0, 1);
    e.buf(&arena.buf, 0, 2);
    e.buf(&slab.0, 0, 3);
    e.bytes(&args, 5);
    e.buf(&slab.1, 0, 8);
    for i in [10, 11, 12] {
        e.buf(&slab.0, 0, i);
    }
    e.pso(&gpu.pso("k_attn_tc_fixed_blk"));
    e.dispatch(tc_attn_dispatch_grid(kv4, grid_x, case.nrows, tg_rows), 96);
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    Engine::assert_cmd_ok(&cb, "k_attn_tc_fixed_blk");
    cb.GPUEndTime() - cb.GPUStartTime()
}

// ---- planted slips: the checks above have to object to each

/// `text` with its one occurrence of `find` replaced. A slip that no longer applies is a failure, not a pass.
fn replace_once(text: &str, find: &str, with: &str) -> String {
    assert_eq!(text.matches(find).count(), 1, "the planted slip must apply exactly once: {find:?}");
    text.replacen(find, with, 1)
}

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_gpu_checks_catch_planted_kernel_slips() {
    type Check = fn(&Kernels, &Case) -> Result<usize, String>;
    fn random_check(k: &Kernels, case: &Case) -> Result<usize, String> {
        let mut rng = Rng::new(0x5119);
        let relb = random_relbias(&mut rng);
        random_agreement(k, &relbias_buffer(&k.gpu, &relb), &relb, case, &mut rng).map(|_| 0)
    }
    let full = CASES[5];
    let window = CASES[11];
    assert!(!full.swa && full.pos0 == 3006 && window.swa && window.pos0 == 2040);
    // (the slip, the text of `tc_kv8_scores` it changes, the change, the check and the case that must object)
    let slips: [(&str, &str, &str, Check, Case); 8] = [
        (
            "the V scale of a key read from its neighbour's row",
            "kv_vscale(vptr + uint(lane) * HD)",
            "kv_vscale(vptr + uint(lane ^ 1) * HD)",
            key_census,
            window,
        ),
        (
            "the K scale of a key read from its neighbour's row",
            "kv_vscale(kptr + uint(lane) * HD)",
            "kv_vscale(kptr + uint(lane ^ 1) * HD)",
            score_census,
            window,
        ),
        (
            "the K scale left out of interior tiles",
            "const float raw_qk = ss_sg[r * TC_ATT_AK + lane] * ks;",
            "const float raw_qk = ss_sg[r * TC_ATT_AK + lane];",
            score_census,
            DEEP,
        ),
        (
            "the K scale left out everywhere",
            "ss_sg[r * TC_ATT_AK + lane] * ks;\n            if (any_bias",
            "ss_sg[r * TC_ATT_AK + lane];\n            if (any_bias",
            random_check,
            window,
        ),
        (
            "a tile taken as interior inside the relative-bias table",
            "if (sel_rows == ~0u && !any_bias && nk == TC_ATT_AK &&",
            "if (sel_rows == ~0u && nk == TC_ATT_AK &&",
            key_census,
            full,
        ),
        (
            "a row that sees the key after its own position",
            "in_tile && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])",
            "in_tile && (kp >= p_lo_r[r]) && (kp <= p_hi_r[r])",
            key_census,
            full,
        ),
        (
            "a window one key too long",
            "in_tile && (kp >= p_lo_r[r]) && (kp < p_hi_r[r])",
            "in_tile && (kp + 1u >= p_lo_r[r]) && (kp < p_hi_r[r])",
            key_census,
            window,
        ),
        (
            "the relative bias read one row past its table",
            "* ks;\n            if (any_bias && (pos - kp) < EXT) {",
            "* ks;\n            if (any_bias && (pos - kp) <= EXT) {",
            key_census,
            full,
        ),
    ];
    // the kernels as they are pass every check on these cases
    let k = Kernels::new(&str::to_string);
    for case in [full, window, DEEP] {
        for check in [key_census as Check, score_census, random_check] {
            check(&k, &case).unwrap_or_else(|e| panic!("unedited kernels: {e}"));
        }
    }
    for (slip, find, with, check, case) in slips {
        let k = Kernels::new(&|src| replace_once(src, find, with));
        let caught = check(&k, &case).expect_err(&format!("{slip}: not caught on {}", case.name));
        eprintln!("[kv8-tc planted] {slip}: caught: {caught}");
    }
}

/// Three lanes of different lengths through one command buffer and one shared partials region, as a prefill step
/// with three spans runs them: for each span, the attention kernel then `k_attn_fixed_combine`, a barrier after
/// each. The rows of all spans sit one after another in the arena.
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_prefill_attention_runs_lanes_of_different_lengths_in_one_batch() {
    let gpu = kv8_gpu("", &["k_attn_tc_fixed_blk", "k_attn_fixed_b_blk", "k_attn_fixed_combine"]);
    let mut rng = Rng::new(0x1a9e5);
    let relb: Vec<f32> = (0..(EXT + 1) * NREL).map(|i| if i < EXT * NREL { rng.unit() * 0.25 } else { f32::NAN }).collect();
    let pb = relbias_buffer(&gpu, &relb);
    for swa in [false, true] {
        let spans = if swa {
            [Case::window("lane A", 2040, 17), Case::window("lane B", 77, 5), Case::window("lane C", 1300, 1)]
        } else {
            [Case::full("lane A", 250, 17), Case::full("lane B", 3006, 40), Case::full("lane C", 77, 1)]
        };
        let rows: usize = spans.iter().map(|c| c.nrows).sum();
        let caches: Vec<Cache> = spans.iter().map(|c| Cache::random(c.end(), &mut rng)).collect();
        let lanes: Vec<Paged> = spans.iter().zip(&caches).map(|(c, cache)| Paged::new(&gpu, cache, c)).collect();
        let qs = Queries::random(rows, &mut rng);
        // arena: [q half | r | sink | gate | out (tensor cores) | out (simdgroups) | partials]
        let q_words = (rows * NH * HD).div_ceil(2);
        let (r_off, sink_off) = (q_words, q_words + qs.r.len());
        let gate_off = sink_off + qs.sink.len();
        let out_off = [gate_off + rows * NH * HD, gate_off + 2 * rows * NH * HD];
        let part_off = (gate_off + 3 * rows * NH * HD).next_multiple_of(64);
        let part_words = spans.iter().map(|c| c.nrows * NH * c.nsplit() * (HD + 2)).max().unwrap();
        let arena = gpu.buffer((part_off + part_words) * 4);
        unsafe {
            let a = arena.contents().as_ptr().cast::<f32>();
            std::ptr::copy_nonoverlapping(qs.q.as_ptr(), a.cast::<u16>(), qs.q.len());
            std::ptr::copy_nonoverlapping(qs.r.as_ptr(), a.add(r_off), qs.r.len());
            std::ptr::copy_nonoverlapping(qs.sink.as_ptr(), a.add(sink_off), qs.sink.len());
            // a wide-open gate: sigmoid(1e9) is 1
            std::slice::from_raw_parts_mut(a.add(gate_off), rows * NH * HD).fill(1e9);
        }
        for (tc, out) in [(true, out_off[0]), (false, out_off[1])] {
            let cb = gpu.cmd();
            let e = Enc::new(&cb);
            e.buf(&pb, 0, 1);
            e.buf(&arena, 0, 2);
            let mut r0 = 0;
            for (case, lane) in spans.iter().zip(&lanes) {
                let nsplit = case.nsplit();
                let (tg_rows, grid_x) = prefill_attn_grid(tc, swa, case.end(), 0, nsplit);
                let args = PreparedAttnArgs {
                    pos0: case.pos0 as u32,
                    window: if swa { EXT as u32 } else { 0 },
                    k_base: TEST_PASS,
                    q_off: (r0 * NH * HD / 2) as u32,
                    r_off: (r_off + r0 * NH * NREL) as u32,
                    sink_off: (sink_off + r0 * NH) as u32,
                    gate_off: (gate_off + r0 * NH * HD) as u32,
                    out_off: (out + r0 * NH * HD) as u32,
                    relbias_w: RELB_AT as u32,
                    part_off: part_off as u32,
                    kps: case.kps() as u32,
                    nsplit: nsplit as u32,
                    half_io: 1,
                    tg_rows: tg_rows as u32,
                    nrows: case.nrows as u32,
                    ..Default::default()
                };
                lane.bind(&e);
                e.bytes(&args, 5);
                e.pso(&gpu.pso(if tc { "k_attn_tc_fixed_blk" } else { "k_attn_fixed_b_blk" }));
                e.dispatch(if tc { tc_attn_dispatch_grid(false, grid_x, case.nrows, tg_rows) } else { (grid_x, NKV, case.nrows.div_ceil(tg_rows)) }, if tc { 96 } else { 128 });
                e.barrier();
                // the combine reads the queries' precision from `half_io`: here a float gate and a float output
                let combine_args = PreparedAttnArgs { half_io: 0, ..args };
                e.bytes(&combine_args, 5);
                e.pso(&gpu.pso("k_attn_fixed_combine"));
                e.dispatch((NH, case.nrows, 1), 128);
                e.barrier();
                r0 += case.nrows;
            }
            e.end();
            cb.commit();
            cb.waitUntilCompleted();
            Engine::assert_cmd_ok(&cb, "three spans");
        }
        let got = |off: usize, r0: usize, n: usize| -> Vec<f64> {
            let a = unsafe { std::slice::from_raw_parts(arena.contents().as_ptr().cast::<f32>().add(off + r0 * NH * HD), n * NH * HD) };
            a.iter().map(|&x| f64::from(x)).collect()
        };
        let mut r0 = 0;
        for (case, cache) in spans.iter().zip(&caches) {
            let span_qs = Queries {
                q: qs.q[r0 * NH * HD..][..case.nrows * NH * HD].to_vec(),
                r: qs.r[r0 * NH * NREL..][..case.nrows * NH * NREL].to_vec(),
                sink: qs.sink[r0 * NH..][..case.nrows * NH].to_vec(),
            };
            let want = reference(case, cache, &span_qs, &relb);
            let (tc, simd) = (got(out_off[0], r0, case.nrows), got(out_off[1], r0, case.nrows));
            let (d_tc, d_simd, d_pair) = (difference(&tc, &want), difference(&simd, &want), difference(&tc, &simd));
            eprintln!(
                "[kv8-tc lanes] {} {} at {} x {}: tc {:.2e}/{:.2e} simd {:.2e}/{:.2e} tc vs simd {:.2e}/{:.2e}",
                if swa { "window" } else { "full" },
                case.name,
                case.pos0,
                case.nrows,
                d_tc.0,
                d_tc.1,
                d_simd.0,
                d_simd.1,
                d_pair.0,
                d_pair.1
            );
            for (abs, rel) in [d_tc, d_simd, d_pair] {
                assert!(abs <= MAX_ABS && rel <= MAX_REL, "{}: {abs:.3e} abs, {rel:.3e} rel", case.name);
            }
            r0 += case.nrows;
        }
    }
}

/// The rows the attention kernels read are the rows `k_kvprep_b_blk` writes: run the real KV8 writer over a span
/// that crosses a block boundary and decode what it stored with the CPU row format.
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_rows_written_by_prefill_decode_with_the_cpu_row_format() {
    let gpu = kv8_gpu("", &["k_kvprep_b_blk"]);
    let (p0, t) = (58usize, 12usize);
    let mut rng = Rng::new(0x9e9);
    // PB: zero conv taps (the K/V of a row is then its own input times 1/sqrt(5)), unit clips
    let (kconv_w, qclip_w, relclip_w) = (0usize, NKV * HD * 4 * 4, (NKV * HD * 4 + NH * HD) * 4);
    let pb = gpu.buffer(relclip_w + NH * NREL * 4);
    // arena: [q | k | v | rel | qp | rp]
    let (q_off, k_off) = (0, t * NH * HD);
    let v_off = k_off + t * NKV * HD;
    let r_off = v_off + t * NKV * HD;
    let qp_off = r_off + t * NH * NREL;
    let rp_off = qp_off + t * NH * HD;
    let arena = gpu.buffer((rp_off + t * NH * NREL) * 4);
    let cs = gpu.buffer(2 * NKV * HD * 3 * 4);
    let kv_in: Vec<f32> = (0..2 * t * NKV * HD).map(|i| rng.unit() * (0.3 + 3.0 * (i / (NKV * HD) % 5) as f32)).collect();
    let n_blks = (p0 + t).div_ceil(BLOCK);
    let slab = gpu.buffer(n_blks * SLOT_BYTES);
    let bt = gpu.buffer(n_blks * 8);
    unsafe {
        let pbf = std::slice::from_raw_parts_mut(pb.contents().as_ptr().cast::<f32>(), relclip_w / 4 + NH * NREL);
        pbf[qclip_w / 4..].fill(1.0);
        let a = arena.contents().as_ptr().cast::<f32>();
        std::slice::from_raw_parts_mut(a, k_off).iter_mut().for_each(|q| *q = rng.unit());
        std::ptr::copy_nonoverlapping(kv_in.as_ptr(), a.add(k_off), kv_in.len());
        // the table runs back to front: block 1 sits before block 0
        let table = std::slice::from_raw_parts_mut(bt.contents().as_ptr().cast::<u64>(), n_blks);
        table.iter_mut().enumerate().for_each(|(b, e)| *e = ((n_blks - 1 - b) * SLOT_BYTES) as u64);
    }
    let args = KvPrepArgs {
        t: t as u32,
        p0: p0 as u32,
        k_base: TEST_PASS,
        q_off: q_off as u32,
        k_off: k_off as u32,
        v_off: v_off as u32,
        r_off: r_off as u32,
        kdyn_off: -1,
        vdyn_off: -1,
        qp_off: qp_off as u32,
        rp_off: rp_off as u32,
        kconv_w: kconv_w as u32,
        vconv_w: kconv_w as u32,
        qclip_w: qclip_w as u32,
        relclip_w: relclip_w as u32,
        log_alpha: 0.0,
        log_floor: 1.0,
        ..Default::default()
    };
    let cb = gpu.cmd();
    let e = Enc::new(&cb);
    e.buf(&pb, 0, 1);
    e.buf(&arena, 0, 2);
    e.buf(&slab, 0, 3);
    e.buf(&cs, 0, 4);
    e.bytes(&args, 5);
    e.buf(&bt, 0, 8);
    for i in [10, 11, 12] {
        e.buf(&slab, 0, i);
    }
    e.pso(&gpu.pso("k_kvprep_b_blk"));
    e.dispatch((t, NKV, 1), 128);
    e.end();
    cb.commit();
    cb.waitUntilCompleted();
    Engine::assert_cmd_ok(&cb, "k_kvprep_b_blk");

    let stored = buffer_bytes(&slab);
    let mut codes = std::collections::BTreeSet::new();
    for plane in 0..2 {
        for g in 0..NKV {
            for row in 0..t {
                let pos = p0 + row;
                // the vector the kernel quantises: K clipped to a norm of QK_CLIP, V scaled to a unit RMS
                let x: Vec<f64> = (0..HD).map(|d| f64::from(kv_in[((plane * t + row) * NKV + g) * HD + d]) * 0.447_213_595_499_957_9).collect();
                let sq = x.iter().map(|v| v * v).sum::<f64>();
                let f = if plane == 0 { (22.627_416_610_717_773 / (sq.sqrt() + 1e-6)).clamp(0.0, 1.0) } else { 1.0 / (sq / HD as f64 + 1e-6).sqrt() };
                let mx = x.iter().fold(0.0f64, |m, v| m.max(v.abs())) * f;
                let slot = (n_blks - 1 - pos / BLOCK) * SLOT_BYTES + TEST_PASS as usize * PASS_BYTES;
                let at = slot + ((plane * NKV + g) * BLOCK + pos % BLOCK) * HD;
                let bytes = &stored[at..at + HD];
                let s = f64::from(kv8_vscale_cpu(bytes));
                let at = format!("plane {plane} head {g} position {pos}");
                // the scale in the low bits is the smallest that holds the vector (one code of slack for float32)
                let c = kv8_code(mx as f32);
                let near = [c.saturating_sub(1), c, (c + 1).min(255)].map(|c| f64::from(kv8_scale(c)));
                assert!(near.contains(&s), "{at}: scale {s} for a largest value of {mx} (code {c})");
                assert!(s * 126.0 >= mx * (1.0 - 1e-5), "{at}: scale {s} clips {mx}");
                codes.insert(c);
                for (d, (&b, &v)) in bytes.iter().zip(&x).enumerate() {
                    let err = (f64::from(b as i8) * s - v * f).abs();
                    let steps = if d < 8 { 1.0 } else { 0.5 };
                    assert!(err <= steps * s * 1.001 + 1e-6, "{at} d {d}: {} stored as {} * {s}", v * f, b as i8);
                }
            }
        }
    }
    assert!(codes.len() >= 4, "the rows must carry several scales: {codes:?}");
}

/// Timings of the KV8 prefill attention kernels, model-free: the simdgroup kernel every KV8 prefill row runs today
/// against the tensor-core kernel, with the KV4 and FP16 tensor-core kernels beside them for scale. One batch of 64
/// query rows on a full pass at three depths and on a window pass. Run with `--nocapture`; the numbers are GPU
/// seconds of the best of 5 command buffers.
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn kv8_tc_prefill_attention_microbench() {
    let gpu = kv8_gpu("", &["k_attn_tc_fixed_blk", "k_attn_fixed_b_blk"]);
    let plain = kv8_gpu("#define TC_KV8_NO_INTERIOR 1\n", &["k_attn_tc_fixed_blk"]);
    let base = format!("{}\n{}", include_str!("../kernels.metal"), include_str!("../prefill.metal"));
    let kv4 = Gpu::new(&format!("#define KV4 1\n#define KV4_DC_OFF 256u\n{base}"), &["k_attn_tc_fixed_blk"]);
    let fp16 = Gpu::new(&base, &["k_attn_tc_fixed_blk"]);
    let mut rng = Rng::new(0xbe7c4);
    let relb: Vec<f32> = (0..(EXT + 1) * NREL).map(|_| rng.unit() * 0.25).collect();
    let pb = relbias_buffer(&gpu, &relb);
    let nrows = 64;
    let best = |f: &mut dyn FnMut() -> f64| (0..5).map(|_| f()).fold(f64::INFINITY, f64::min);
    eprintln!("[kv8-tc bench] 64 query rows x 24 heads, GPU ms per batch (rows/s of one attention pass)");
    eprintln!("[kv8-tc bench] {:<22} {:>18} {:>18} {:>18} {:>18} {:>18}", "pass at depth", "kv8 simdgroup", "kv8 tensor", "kv8 tensor plain", "kv4 tensor", "fp16 tensor");
    for (swa, depth) in [(false, 4096usize), (false, 20480), (false, 61440), (true, 20480)] {
        let case = Case { name: "bench", swa, pos0: depth - nrows, nrows, budget: 0 };
        // Only the keys the rows see cost time: a window pass gets 18 blocks, a full pass all of them. The bytes
        // are random; every row carries one of 24 realistic scale codes.
        let n = case.end();
        let mut cache = Cache::new(n);
        let lo = case.first_live_key() / BLOCK * BLOCK;
        for chunk in cache.kv.chunks_mut(8) {
            chunk.copy_from_slice(&rng.next().to_le_bytes().map(|b| b as i8));
        }
        for plane in 0..2 {
            for g in 0..NKV {
                for pos in lo..n {
                    let code = 88 + (rng.next() % 24) as u32;
                    let at = ((plane * NKV + g) * n + pos) * HD;
                    for (i, b) in cache.kv[at..at + 8].iter_mut().enumerate() {
                        *b = (*b & !1) | ((code >> (7 - i)) & 1) as i8;
                    }
                }
            }
        }
        let qs = Queries::random(nrows, &mut rng);
        let arena = Arena::new(&gpu, &case, &qs, 3);
        let paged = Paged::new(&gpu, &cache, &case);
        let store = Store::Paged(&paged);
        let simd = best(&mut || attend(&gpu, &pb, &arena, 0, &case, &store, false));
        let tc = best(&mut || attend(&gpu, &pb, &arena, 1, &case, &store, true));
        let tc_plain = best(&mut || attend(&plain, &pb, &arena, 2, &case, &store, true));
        // the benchmark's own check: both kernels computed the same attention (relative only: these rows are raw
        // random bytes, and the outputs are larger than a model's)
        let (a, b) = (combine(&case, arena.part(0), arena.nsplit), combine(&case, arena.part(1), arena.nsplit));
        let (_, rel) = difference(&b, &a);
        assert!(rel <= MAX_REL, "bench at {depth}: tensor cores vs simdgroups {rel:.3e} rel");
        assert_eq!(differing_values(&case, arena.part(1), arena.part(2), arena.nsplit), 0, "bench at {depth}: interior path");

        // the same shape for the other cache formats, for scale: random rows in their own layouts
        let mut r4 = Rng::new(depth as u64);
        let slab4 = other_format_slab(&kv4, n, true, &mut r4);
        let t_kv4 = best(&mut || attend_other_format(&kv4, &pb, &arena, 2, &case, true, &slab4));
        drop(slab4);
        let slab16 = other_format_slab(&fp16, n, false, &mut r4);
        let t_fp16 = best(&mut || attend_other_format(&fp16, &pb, &arena, 2, &case, false, &slab16));
        let cell = |t: f64| format!("{:.2} ({:.0})", t * 1e3, nrows as f64 / t);
        eprintln!(
            "[kv8-tc bench] {:<22} {:>18} {:>18} {:>18} {:>18} {:>18}   kv8 tensor/simdgroup speed x{:.2}",
            format!("{} at {depth}", if swa { "window" } else { "full" }),
            cell(simd),
            cell(tc),
            cell(tc_plain),
            cell(t_kv4),
            cell(t_fp16),
            simd / tc
        );
    }
}

// ---------------------------------------------------------------------------------------------------------------
// 4. The KV8 writers on the model's own conv weights and clips: given the same projections and conv state, the
//    prefill writers (`k_kvprep_b`, `k_kvprep_b_blk`) and the decode writer (`k_kvprep_dec`) store the same bytes,
//    and those bytes are the CPU codec's. So under `--kv8` a decode-written row differs from a prefill-written one
//    only when the hidden state feeding the K/V projection differs, never through the write or the quantiser.
// ---------------------------------------------------------------------------------------------------------------

fn kv8_model_engine() -> Engine {
    let model = std::env::var("INKY_TEST_MODEL").unwrap_or_else(|_| crate::default_model());
    assert!(std::path::Path::new(&model).exists(), "model not found at {model}");
    let prev = (KV8.swap(true, std::sync::atomic::Ordering::Relaxed), KV4.swap(false, std::sync::atomic::Ordering::Relaxed));
    let eng = Engine::load(&model, 4096);
    KV8.store(prev.0, std::sync::atomic::Ordering::Relaxed);
    KV4.store(prev.1, std::sync::atomic::Ordering::Relaxed);
    assert!(eng.kv8 && !eng.kv4);
    eng
}

/// Window and full layers, from the first physical layer to the last looped pass.
const KV8_PARITY_SLOTS: [usize; 8] = [0, 5, 6, 11, 17, 23, 35, 47];

#[test]
#[ignore = "requires local Inkling-2-Mini GGUF model on Metal GPU"]
fn kv8_prefill_and_decode_writers_store_identical_rows() {
    let eng = kv8_model_engine();
    let kinds: Vec<bool> = KV8_PARITY_SLOTS.iter().map(|&s| eng.slot_kind[s].0).collect();
    assert!(kinds.contains(&true) && kinds.contains(&false), "the slots must cover window and full layers: {kinds:?}");
    let (rows, exact_rows, exact_bytes, _) = eng.verify_quant_kv_writer_parity(&KV8_PARITY_SLOTS, 16, None);
    eprintln!("[kv8-writers] {exact_rows}/{rows} rows and {exact_bytes}/{} bytes identical across k_kvprep_b, k_kvprep_b_blk, k_kvprep_dec and the CPU codec", rows * HD);
    assert_eq!(rows, KV8_PARITY_SLOTS.len() * 16 * 2 * NKV);
    assert_eq!((exact_rows, exact_bytes), (rows, rows * HD));
}

/// Negative control: a decode writer that rounds its input to fp16 before quantising (the kind of precision slip
/// that would make decode-written rows drift from prefill's) is caught.
#[test]
#[ignore = "requires local Inkling-2-Mini GGUF model on Metal GPU"]
fn kv8_writer_parity_catches_a_planted_decode_slip() {
    let eng = kv8_model_engine();
    let kernels = include_str!("../kernels.metal");
    let at = kernels.find("kernel void k_kvprep_dec(").expect("k_kvprep_dec");
    let honest = "const float qk = kv_quant(k, sk, ck, tid), qv = kv_quant(v, sv, cv, tid);";
    let slip = "const float qk = kv_quant(float(half(k)), sk, ck, tid), qv = kv_quant(v, sv, cv, tid);";
    let rel = kernels[at..].find(honest).expect("k_kvprep_dec KV8 quantise");
    let edited = format!("{}{}{}", &kernels[..at + rel], slip, &kernels[at + rel + honest.len()..]);
    let no_mpp = if eng.use_mpp { "" } else { "#define NO_MPP 1\n" };
    let gpu = Gpu::new(&format!("#define KV8 1\n{no_mpp}{edited}"), &["k_kvprep_dec"]);
    let slipped = gpu.pso("k_kvprep_dec");
    // The same source unedited passes, so a catch below is the slip and not the separate compile.
    let honest_gpu = Gpu::new(&format!("#define KV8 1\n{no_mpp}{kernels}"), &["k_kvprep_dec"]);
    let (rows, exact_rows, _, _) = eng.verify_quant_kv_writer_parity(&KV8_PARITY_SLOTS, 16, Some(&honest_gpu.pso("k_kvprep_dec")));
    assert_eq!(exact_rows, rows);
    let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        eng.verify_quant_kv_writer_parity(&KV8_PARITY_SLOTS, 16, Some(&slipped))
    }))
    .expect_err("the planted fp16 rounding in k_kvprep_dec must be caught");
    let msg = caught.downcast_ref::<String>().cloned().unwrap_or_default();
    assert!(msg.contains("k_kvprep_b_blk vs k_kvprep_dec mismatch"), "caught for another reason: {msg}");
}
mod sparse_prefill;


// ---- the online softmax of the tensor-core kernels (`tc_softmax_row`, `tc_softmax_finish` in `prefill.metal`)

/// The per-row softmax the kernels ran before the row bookkeeping moved to one lane per row: every lane works out
/// every row's `alpha`, and the `O *= alpha` and zeroing passes always run.
const EAGER_SOFTMAX: &str = "#define TC_ATT_EAGER_SOFTMAX 1\n";

/// The KV8 builds of the two float reorderings, each alone and both together, as `model.rs` compiles them.
fn softmax_reorderings() -> [(&'static str, String); 3] {
    [
        ("exp2", tc_softmax_defines(true, true, false)),
        ("lazy rescale", tc_softmax_defines(true, false, true)),
        ("exp2 + lazy rescale", tc_softmax_defines(true, true, true)),
    ]
}

#[test]
fn tc_softmax_reorderings_are_kv8_only_off_by_default_and_one_define_each() {
    assert_eq!(tc_softmax_defines(true, false, false), "", "the default build reorders nothing");
    for (exp2, lazy) in [(false, false), (true, false), (false, true), (true, true)] {
        assert_eq!(tc_softmax_defines(false, exp2, lazy), "", "FP16 and KV4 never take a reordering");
    }
    assert_eq!(tc_softmax_defines(true, true, false), "#define TC_ATT_EXP2 1\n");
    assert_eq!(tc_softmax_defines(true, false, true), "#define TC_ATT_LAZY_RESCALE 1\n");
    assert_eq!(tc_softmax_defines(true, true, true), "#define TC_ATT_EXP2 1\n#define TC_ATT_LAZY_RESCALE 1\n");
    for (v, on) in [(None, false), (Some(""), false), (Some("0"), false), (Some("1"), true), (Some("yes"), true)] {
        assert_eq!(dev_switch(v), on, "{v:?}");
    }
    // the kernels refuse a reordering outside KV8, and the exact softmax sits behind none of these defines
    let src = include_str!("../prefill.metal");
    assert!(src.contains("#if (defined(TC_ATT_EXP2) || defined(TC_ATT_LAZY_RESCALE)) && !defined(KV8)\n#error"));
    let model = include_str!("model.rs");
    assert_eq!(model.matches("INK_TC_EXP2").count(), 1);
    assert_eq!(model.matches("INK_TC_LAZY_RESCALE").count(), 1);
    assert!(prefill_tc_attn(true, false, false) && !prefill_tc_attn(true, true, false), "no tensor-core prefill in --exact");
}

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn tc_prefill_softmax_is_bit_identical_to_the_per_row_softmax() {
    // KV8, both layers, every case: the engine build against the per-row softmax.
    let tc = ["k_attn_tc_fixed_blk", "k_attn_tc_fixed_b"];
    let (now, was) = (kv8_gpu("", &tc), kv8_gpu(EAGER_SOFTMAX, &tc));
    let mut rng = Rng::new(0x050f_73a8);
    let relb = random_relbias(&mut rng);
    let pb = relbias_buffer(&now, &relb);
    let deeper = Case::full("full: 12,000 keys deep", 12000, 48);
    let window_deep = Case::window("window: 9,000 keys deep", 9000, 40);
    let mut compared = 0usize;
    for case in CASES.iter().chain([&DEEP, &deeper, &window_deep]) {
        let cache = Cache::random(case.end(), &mut rng);
        let qs = Queries::random(case.nrows, &mut rng);
        let (paged, flat) = (Paged::new(&now, &cache, case), Flat::new(&now, &cache, case));
        let arena = Arena::new(&now, case, &qs, 4);
        for layer in 0..2 {
            let store = if layer == 0 { Store::Paged(&paged) } else { Store::Flat(&flat) };
            attend(&now, &pb, &arena, layer, case, &store, true);
            attend(&was, &pb, &arena, 2 + layer, case, &store, true);
            assert_slots_written("now", case, arena.part(layer), arena.nsplit);
            assert_slots_written("per-row softmax", case, arena.part(2 + layer), arena.nsplit);
            let n = differing_values(case, arena.part(layer), arena.part(2 + layer), arena.nsplit);
            assert_eq!(n, 0, "kv8 {}: Layer {}: {n} values differ from the per-row softmax", case.name, 3 - layer);
            compared += case.nrows;
        }
    }
    eprintln!("[tc softmax] kv8: {compared} rows x layers bit-identical to the per-row softmax");

    // FP16 and KV4 through the Layer 3 kernel, on their own grids.
    let base = format!("{}\n{}", include_str!("../kernels.metal"), include_str!("../prefill.metal"));
    for kv4 in [false, true] {
        let fmt = if kv4 { "#define KV4 1\n#define KV4_DC_OFF 256u\n" } else { "" };
        let mname = if kv4 { "kv4" } else { "fp16" };
        let now = Gpu::new(&format!("{fmt}{base}"), &["k_attn_tc_fixed_blk"]);
        let was = Gpu::new(&format!("{fmt}{EAGER_SOFTMAX}{base}"), &["k_attn_tc_fixed_blk"]);
        for case in [CASES[2], CASES[5], CASES[6], CASES[10], CASES[11], DEEP, deeper, window_deep] {
            let qs = Queries::random(case.nrows, &mut rng);
            let arena = Arena::new(&now, &case, &qs, 2);
            let slab = other_format_slab(&now, case.end(), kv4, &mut rng);
            attend_other_format(&now, &pb, &arena, 0, &case, kv4, &slab);
            attend_other_format(&was, &pb, &arena, 1, &case, kv4, &slab);
            assert_slots_written(mname, &case, arena.part(0), arena.nsplit);
            let n = differing_values(&case, arena.part(0), arena.part(1), arena.nsplit);
            assert_eq!(n, 0, "{mname} {}: {n} values differ from the per-row softmax", case.name);
        }
        eprintln!("[tc softmax] {mname}: bit-identical to the per-row softmax");
    }
    // FP16 and KV4 through the Layer 2 kernel: `k_attn_tc_fixed_b` runs the same softmax text (one helper), and the
    // grid test above runs it against its own old build; the census below shows the two kernels carry the same calls.
    let src = include_str!("../prefill.metal");
    assert_eq!(src.matches("tc_softmax_finish(acc, nr, lane, m_row[sg], l_row[sg], alpha_row[sg]);").count(), 2);
    assert_eq!(src.matches("if (passes & 1u) {").count(), 2);
    assert_eq!(src.matches("if (passes & 2u) {").count(), 2);
}

/// Largest distance in units in the last place between two attention outputs rounded to `f32`, over the outputs at
/// least 1% of their row's largest magnitude (near zero, a ULP is no measure of the error).
fn max_ulp(a: &[f64], b: &[f64]) -> u64 {
    let ordered = |x: f64| {
        let b = i64::from((x as f32).to_bits());
        if b < 0x8000_0000 { b } else { 0x8000_0000 - b }
    };
    let mut worst = 0;
    for (a, b) in a.chunks(HD).zip(b.chunks(HD)) {
        let floor = 0.01 * b.iter().fold(0.0f64, |m, b| m.max(b.abs()));
        for (&x, &y) in a.iter().zip(b) {
            if y.abs() >= floor {
                worst = worst.max(ordered(x).abs_diff(ordered(y)));
            }
        }
    }
    worst
}

#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn tc_prefill_softmax_reorderings_stay_within_float_rounding_of_the_exact_order() {
    // Each reordering against the engine's KV8 build on the attention output after the split combine, and both
    // against the double-precision reference. Bounds: max relative difference 1e-5 of a row's largest output, the
    // reference bound the kernels already meet (`MAX_REL`).
    let tc = ["k_attn_tc_fixed_blk", "k_attn_tc_fixed_b"];
    let now = kv8_gpu("", &tc);
    let builds: Vec<(&str, Gpu)> = softmax_reorderings().into_iter().map(|(name, d)| (name, kv8_gpu(&d, &tc))).collect();
    let mut rng = Rng::new(0xe4b2);
    let relb = random_relbias(&mut rng);
    let pb = relbias_buffer(&now, &relb);
    let mut worst = vec![(0.0f64, 0.0f64, 0u64); builds.len()];
    let deeper = Case::full("full: 12,000 keys deep", 12000, 48);
    for (ci, case) in CASES.iter().chain([&DEEP, &deeper]).enumerate() {
        let cache = Cache::random(case.end(), &mut rng);
        let qs = Queries::random(case.nrows, &mut rng);
        let (paged, flat) = (Paged::new(&now, &cache, case), Flat::new(&now, &cache, case));
        let arena = Arena::new(&now, case, &qs, 2 * (builds.len() + 1));
        let want = (ci <= CASES.len()).then(|| reference(case, &cache, &qs, &relb));
        for layer in 0..2 {
            let store = if layer == 0 { Store::Paged(&paged) } else { Store::Flat(&flat) };
            attend(&now, &pb, &arena, layer, case, &store, true);
            let base = combine(case, arena.part(layer), arena.nsplit);
            for (b, (name, gpu)) in builds.iter().enumerate() {
                let part = 2 * (b + 1) + layer;
                attend(gpu, &pb, &arena, part, case, &store, true);
                assert_slots_written(name, case, arena.part(part), arena.nsplit);
                let got = combine(case, arena.part(part), arena.nsplit);
                let (abs, rel) = difference(&got, &base);
                let ulp = max_ulp(&got, &base);
                assert!(rel <= 1e-5, "{name}: {}: Layer {}: {rel:.3e} rel ({abs:.3e} abs, {ulp} ULP) from the exact order", case.name, 3 - layer);
                if let Some(want) = &want {
                    let (_, rel_ref) = difference(&got, want);
                    assert!(rel_ref <= MAX_REL, "{name}: {}: {rel_ref:.3e} rel from the reference", case.name);
                }
                let w = &mut worst[b];
                *w = (w.0.max(abs), w.1.max(rel), w.2.max(ulp));
            }
        }
    }
    for ((name, _), (abs, rel, ulp)) in builds.iter().zip(&worst) {
        eprintln!("[tc softmax] {name:<20} vs the exact order: max abs {abs:.3e}, max rel {rel:.3e}, max {ulp} ULP");
        assert!(*ulp > 0, "{name}: no bit moved, so the build did not take the define");
    }
}

/// GPU time of the tensor-core prefill attention under each softmax build, model-free, mirrored rounds (A B C .. then
/// .. C B A, `INK_SOFTMAX_BENCH_ROUNDS`, default 9): the median of each build and its median paired speedup. 64 query rows x 24 heads at the depths of a long prompt's last chunk. Run with
/// `--nocapture`. The numbers say which change pays on the GPU it runs on; M5 numbers come from an M5.
#[test]
#[ignore = "requires a Metal 4 GPU with MetalPerformancePrimitives"]
fn tc_prefill_softmax_microbench() {
    let tc = ["k_attn_tc_fixed_blk"];
    let mut kv8_builds: Vec<(String, Gpu)> = vec![
        ("per-row (before)".into(), kv8_gpu(EAGER_SOFTMAX, &tc)),
        ("row-parallel, both passes".into(), kv8_gpu("#define TC_ATT_ALWAYS_PASSES 1\n", &tc)),
        ("row-parallel + skips (now)".into(), kv8_gpu("", &tc)),
    ];
    for (name, d) in softmax_reorderings() {
        kv8_builds.push((name.to_string(), kv8_gpu(&d, &tc)));
    }
    let base = format!("{}\n{}", include_str!("../kernels.metal"), include_str!("../prefill.metal"));
    let fp16_builds = [
        ("fp16 per-row".to_string(), Gpu::new(&format!("{EAGER_SOFTMAX}{base}"), &tc)),
        ("fp16 row-parallel, both passes".to_string(), Gpu::new(&format!("#define TC_ATT_ALWAYS_PASSES 1\n{base}"), &tc)),
        ("fp16 now".to_string(), Gpu::new(&base, &tc)),
    ];
    let rounds: usize = std::env::var("INK_SOFTMAX_BENCH_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(9);
    let mut rng = Rng::new(0x50f7);
    let relb: Vec<f32> = (0..(EXT + 1) * NREL).map(|_| rng.unit() * 0.25).collect();
    let pb = relbias_buffer(&kv8_builds[0].1, &relb);
    let nrows = 64;
    let median = |mut v: Vec<f64>| {
        v.sort_by(f64::total_cmp);
        v[v.len() / 2]
    };
    // mirrored rounds over `n` builds: each round runs every build once, odd rounds in reverse. Per build: the median
    // time, and the median over rounds of the first build's time over this build's in the same round (a paired
    // speedup, steadier than a ratio of medians when the GPU is shared).
    let mirrored = |n: usize, run: &mut dyn FnMut(usize) -> f64| -> Vec<(f64, f64)> {
        let mut t = vec![Vec::new(); n];
        for round in 0..rounds {
            for k in 0..n {
                let b = if round % 2 == 0 { k } else { n - 1 - k };
                t[b].push(run(b));
            }
        }
        let speedups: Vec<f64> = (0..n).map(|b| median((0..rounds).map(|r| t[0][r] / t[b][r]).collect())).collect();
        t.into_iter().map(median).zip(speedups).collect()
    };
    for (swa, depth) in [(false, 4096usize), (false, 20480), (false, 32768), (false, 61440), (false, 102400), (true, 20480)] {
        let case = Case { name: "bench", swa, pos0: depth - nrows, nrows, budget: 0 };
        let n = case.end();
        let mut cache = Cache::new(n);
        let lo = case.first_live_key() / BLOCK * BLOCK;
        for chunk in cache.kv.chunks_mut(8) {
            chunk.copy_from_slice(&rng.next().to_le_bytes().map(|b| b as i8));
        }
        for plane in 0..2 {
            for g in 0..NKV {
                for pos in lo..n {
                    let code = 88 + (rng.next() % 24) as u32;
                    let at = ((plane * NKV + g) * n + pos) * HD;
                    for (i, b) in cache.kv[at..at + 8].iter_mut().enumerate() {
                        *b = (*b & !1) | ((code >> (7 - i)) & 1) as i8;
                    }
                }
            }
        }
        let qs = Queries::random(nrows, &mut rng);
        let arena = Arena::new(&kv8_builds[0].1, &case, &qs, kv8_builds.len());
        let paged = Paged::new(&kv8_builds[0].1, &cache, &case);
        let store = Store::Paged(&paged);
        let t8 = mirrored(kv8_builds.len(), &mut |b| attend(&kv8_builds[b].1, &pb, &arena, b, &case, &store, true));
        for b in [1, 2] {
            assert_eq!(differing_values(&case, arena.part(0), arena.part(b), arena.nsplit), 0, "bench at {depth}: {} vs per-row", kv8_builds[b].0);
        }
        drop(paged);
        let slab = other_format_slab(&fp16_builds[0].1, n, false, &mut rng);
        let t16 = mirrored(fp16_builds.len(), &mut |b| attend_other_format(&fp16_builds[b].1, &pb, &arena, b, &case, false, &slab));
        let at = format!("{} at {depth}", if swa { "window" } else { "full" });
        for (b, (name, _)) in kv8_builds.iter().enumerate() {
            eprintln!("[tc softmax bench] {at:<16} kv8 {name:<30} {:>8.3} ms  x{:.3} vs per-row", t8[b].0 * 1e3, t8[b].1);
        }
        for (b, (name, _)) in fp16_builds.iter().enumerate() {
            eprintln!("[tc softmax bench] {at:<16} {name:<34} {:>8.3} ms  x{:.3} vs per-row", t16[b].0 * 1e3, t16[b].1);
        }
    }
}