snaptokens 0.2.6

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

use crate::pre_tokenizers::FusedPieceSink;

// -----------------------------------------------------------------------

/// Does this x86_64 CPU have the full AVX-512 tier (Zen 4/5, Ice
/// Lake+)? Schemes dispatch their batch classifier on this: the AVX-512
/// front-end when true, the AVX2 one otherwise.
#[cfg(target_arch = "x86_64")]
#[inline]
fn avx512_scanner_available() -> bool {
    // std's feature cache makes this an atomic load + bit test after the
    // first call.
    std::arch::is_x86_feature_detected!("avx512f")
        && std::arch::is_x86_feature_detected!("avx512bw")
        && std::arch::is_x86_feature_detected!("avx512vl")
        && std::arch::is_x86_feature_detected!("bmi1")
        && std::arch::is_x86_feature_detected!("bmi2")
        && std::arch::is_x86_feature_detected!("lzcnt")
        && std::arch::is_x86_feature_detected!("popcnt")
}

/// Does this x86_64 CPU have the AVX2 tier (Haswell+, all Zen)? The bit
/// features (BMI1/2, LZCNT, POPCNT) arrived with or before AVX2 on every
/// AVX2 CPU, but are detected explicitly since the boundary algebra's
/// codegen relies on them.
#[cfg(target_arch = "x86_64")]
#[inline]
fn avx2_scanner_available() -> bool {
    std::arch::is_x86_feature_detected!("avx2")
        && std::arch::is_x86_feature_detected!("bmi1")
        && std::arch::is_x86_feature_detected!("bmi2")
        && std::arch::is_x86_feature_detected!("lzcnt")
        && std::arch::is_x86_feature_detected!("popcnt")
}

/// Is the SIMD mask scanner usable on this machine? aarch64 always has
/// NEON; x86_64 requires AVX-512 (Zen 4/5, Ice Lake+) or AVX2 (Haswell+,
/// Zen 1-3), detected at runtime. When this returns false, [`MaskState`]
/// runs every token through the scheme's scalar `advance`.
#[cfg(target_arch = "x86_64")]
#[inline]
fn simd_scanner_available() -> bool {
    avx512_scanner_available() || avx2_scanner_available()
}

#[cfg(not(target_arch = "x86_64"))]
#[inline]
fn simd_scanner_available() -> bool {
    cfg!(target_arch = "aarch64")
}

// The x86-64 batch classifiers are annotated
// `#[target_feature(enable = "avx512f,avx512bw,avx512vl,bmi1,bmi2,lzcnt,popcnt")]`
// (AVX-512 tier) or `#[target_feature(enable = "avx2,bmi1,bmi2,lzcnt,popcnt")]`
// (AVX2 tier). Besides the wide byte ops, the scalar-visible bit features
// (BMI1/2, LZCNT, POPCNT) are enabled so the boundary algebra inlined
// into those functions compiles to tzcnt/lzcnt/blsr instead of
// baseline-x86 bsf sequences. The sets must stay in sync with
// [`avx512_scanner_available`] / [`avx2_scanner_available`].

/// simdjson-style movemask: 4 mask vectors (64 lanes of 0x00/0xFF) -> u64,
/// bit i = lane i.
#[cfg(target_arch = "aarch64")]
#[inline(always)]
unsafe fn movemask64(
    v0: std::arch::aarch64::uint8x16_t,
    v1: std::arch::aarch64::uint8x16_t,
    v2: std::arch::aarch64::uint8x16_t,
    v3: std::arch::aarch64::uint8x16_t,
) -> u64 {
    use std::arch::aarch64::*;
    unsafe {
        let magic = vld1q_u32([0xf0f1_f3f8, 0x0f1f_3f80, 0xf0f1_f3f8, 0x0f1f_3f80].as_ptr());
        let first = vpaddq_u32(
            vmulq_u32(vreinterpretq_u32_u8(v0), magic),
            vmulq_u32(vreinterpretq_u32_u8(v1), magic),
        );
        let second = vpaddq_u32(
            vmulq_u32(vreinterpretq_u32_u8(v2), magic),
            vmulq_u32(vreinterpretq_u32_u8(v3), magic),
        );
        // Each gathered byte contains eight consecutive predicate bits.
        let tables = uint8x16x2_t(vreinterpretq_u8_u32(first), vreinterpretq_u8_u32(second));
        let indices = vld1_u8([3, 7, 11, 15, 19, 23, 27, 31].as_ptr());
        let packed = vqtbl2_u8(tables, indices);
        vget_lane_u64::<0>(vreinterpret_u64_u8(packed))
    }
}

/// One u64 mask (bit i = byte scan+i) per byte predicate, for 64 bytes.
/// The working currency of scheme boundary algebra: everything after this
/// is platform-independent u64 bit math.
#[derive(Clone, Copy, Default)]
struct AsciiMasks {
    /// ASCII letters.
    pub l: u64,
    /// ASCII digits.
    pub d: u64,
    /// Space (0x20) only.
    pub s: u64,
    /// Non-newline ASCII whitespace: \t, \x0b, \x0c.
    pub wt: u64,
    /// Newlines: \r, \n.
    pub n: u64,
    /// Non-ASCII bytes (>= 0x80).
    pub hi: u64,
    /// ASCII apostrophes.
    pub ap: u64,
}

/// Classify one 64-byte block with runtime-gated AVX-512 instructions.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vl,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
fn ascii_masks_avx512(bytes: &[u8], scan: usize) -> AsciiMasks {
    use std::arch::x86_64::*;
    unsafe {
        let v = _mm512_loadu_si512(bytes.as_ptr().add(scan) as *const _);
        let lowered = _mm512_or_si512(v, _mm512_set1_epi8(0x20));
        let l = _mm512_cmple_epu8_mask(
            _mm512_sub_epi8(lowered, _mm512_set1_epi8(b'a' as i8)),
            _mm512_set1_epi8(25),
        );
        let d = _mm512_cmple_epu8_mask(
            _mm512_sub_epi8(v, _mm512_set1_epi8(b'0' as i8)),
            _mm512_set1_epi8(9),
        );
        let s = _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8(b' ' as i8));
        let n = _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8(b'\r' as i8))
            | _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8(b'\n' as i8));
        // \t (9), \x0b (11), \x0c (12): ascii ws minus \r\n and space.
        let wt =
            _mm512_cmple_epu8_mask(_mm512_sub_epi8(v, _mm512_set1_epi8(9)), _mm512_set1_epi8(4))
                & !n;
        let hi = _mm512_movepi8_mask(v) as u64;
        let ap = _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8(b'\'' as i8));
        AsciiMasks {
            l,
            d,
            s,
            wt,
            n,
            hi,
            ap,
        }
    }
}

/// Classify `bytes[scan..scan+64]` with AVX2 (requires
/// `scan + 64 <= bytes.len()`). Two 32-byte loads; each predicate is one
/// vector compare per half plus a `vpmovmskb` ladder into the u64 the bit
/// algebra wants — more mask-extraction traffic than the AVX-512 version
/// (whose k-register compares ARE the u64s), but the output currency is
/// identical, so everything downstream is shared. AVX2 has no unsigned
/// byte compare; `x <= lim` is `min_epu8(x, lim) == x`.
///
/// Runtime-gated: callers reach this only after
/// [`avx2_scanner_available`] reported AVX2 support (enforced by the
/// schemes' dispatch, behind [`MaskState`]'s `simd_scanner_available`
/// gate).
///
/// `#[inline(never)]` is load-bearing: inlined, LLVM's vector combiner
/// sees the compare vectors behind the returned u64s and pulls the
/// caller's scalar boundary algebra back into the byte-vector domain,
/// expanding every mask<->vector crossing into vpinsrb/vpextrb ladders
/// (~240 byte ops per batch, measured 3.5x slower end to end on Zen 2).
/// The AVX-512 tier has no such domain to return to (k-register compares
/// ARE the u64s), so it stays inline.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2,bmi1,bmi2,lzcnt,popcnt")]
#[inline(never)]
fn ascii_masks_avx2(bytes: &[u8], scan: usize) -> AsciiMasks {
    use std::arch::x86_64::*;
    unsafe {
        // Closures inherit the enclosing fn's target features.
        let le =
            |v: __m256i, lim: __m256i| -> __m256i { _mm256_cmpeq_epi8(_mm256_min_epu8(v, lim), v) };
        let mm = |m0: __m256i, m1: __m256i| -> u64 {
            (_mm256_movemask_epi8(m0) as u32 as u64)
                | ((_mm256_movemask_epi8(m1) as u32 as u64) << 32)
        };

        let p = bytes.as_ptr().add(scan);
        let v0 = _mm256_loadu_si256(p as *const _);
        let v1 = _mm256_loadu_si256(p.add(32) as *const _);

        let x20 = _mm256_set1_epi8(0x20);
        let ca = _mm256_set1_epi8(b'a' as i8);
        let c25 = _mm256_set1_epi8(25);
        let l = mm(
            le(_mm256_sub_epi8(_mm256_or_si256(v0, x20), ca), c25),
            le(_mm256_sub_epi8(_mm256_or_si256(v1, x20), ca), c25),
        );
        let c0 = _mm256_set1_epi8(b'0' as i8);
        let c9 = _mm256_set1_epi8(9);
        let d = mm(
            le(_mm256_sub_epi8(v0, c0), c9),
            le(_mm256_sub_epi8(v1, c0), c9),
        );
        let sp = _mm256_set1_epi8(b' ' as i8);
        let s = mm(_mm256_cmpeq_epi8(v0, sp), _mm256_cmpeq_epi8(v1, sp));
        let cr = _mm256_set1_epi8(b'\r' as i8);
        let lf = _mm256_set1_epi8(b'\n' as i8);
        let n = mm(
            _mm256_or_si256(_mm256_cmpeq_epi8(v0, cr), _mm256_cmpeq_epi8(v0, lf)),
            _mm256_or_si256(_mm256_cmpeq_epi8(v1, cr), _mm256_cmpeq_epi8(v1, lf)),
        );
        // \t (9), \x0b (11), \x0c (12): ascii ws minus \r\n and space.
        let c4 = _mm256_set1_epi8(4);
        let wt = mm(
            le(_mm256_sub_epi8(v0, c9), c4),
            le(_mm256_sub_epi8(v1, c9), c4),
        ) & !n;
        let hi = mm(v0, v1); // vpmovmskb takes the sign bit directly
        let apc = _mm256_set1_epi8(b'\'' as i8);
        let ap = mm(_mm256_cmpeq_epi8(v0, apc), _mm256_cmpeq_epi8(v1, apc));
        AsciiMasks {
            l,
            d,
            s,
            wt,
            n,
            hi,
            ap,
        }
    }
}

/// Test whether the scalar at an in-bounds lookahead position is non-whitespace.
#[inline(always)]
unsafe fn nn_at_full(bytes: &[u8], index: usize) -> bool {
    let byte = bytes[index];
    if byte < 0x80 {
        return !is_ascii_ws(byte);
    }
    let (codepoint, _) = unsafe { decode_cp_inbounds(bytes, index) };
    o200k_class_of(codepoint) != O200kCharClass::Whitespace
}

/// Token-start bits inside ASCII digit runs for `\p{N}{1,3}`: each run
/// splits into 3-char tokens, so boundaries sit at run start + 3k. (For a
/// plain `\p{N}` scheme every digit is a start — no helper needed.)
#[inline(always)]
fn digit_run_splits3(d: u64) -> u64 {
    let mut b = d & !(d << 1); // run starts
    // A start at p re-arms at p+3 while the run continues: hop condition
    // c = "p..p+3 all digits". Log-doubling covers 64-bit runs in 5 steps.
    let mut c = d & (d >> 1) & (d >> 2) & (d >> 3);
    let mut sh = 3u32;
    while sh < 64 {
        b |= (b & c) << sh;
        c &= c >> sh;
        sh <<= 1;
    }
    b
}

// -----------------------------------------------------------------------
// The batch walker
// -----------------------------------------------------------------------

/// The two per-scheme hooks of a mask-scanner pretokenizer.
trait MaskScheme {
    /// Scalar ground truth: end of the token starting at `pos`
    /// (`pos < bytes.len()`, `pos` on a token boundary).
    fn advance(bytes: &[u8], pos: usize) -> usize;

    /// `(usable, bad)` for `bytes[scan..scan+64]` (`scan+70 <= len`):
    /// `usable` bit k = trustworthy token start at scan+k; `bad` bit k =
    /// byte scan+k needs the scalar path. `usable & bad` must be 0.
    ///
    /// On x86_64 the implementations dispatch into AVX-512 or AVX2 code
    /// and must only be called when [`simd_scanner_available`] is true —
    /// [`MaskState`] guarantees this by never leaving the scalar path
    /// otherwise.
    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64);
}

/// Scheme-agnostic mask-scanner state: pops trusted boundary bits, walks
/// bad zones through the scheme's scalar `advance`, runs the buffer tail
/// scalar, and precomputes one batch ahead so the SIMD chain retires under
/// the previous batch's pops. Without SIMD support (non-aarch64/x86_64
/// targets, or an x86_64 CPU without AVX-512 or AVX2) `scalar_until`
/// starts at `usize::MAX`, so every token takes the scalar path.
struct MaskState {
    /// Start of the pending (not yet emitted) token.
    pub pos: usize,
    /// Base of the next batch to scan.
    scan: usize,
    /// Base the `rem`/`batch_*` bits refer to.
    mask_base: usize,
    /// Boundary bits of the current segment (trusted, pop-ready).
    rem: u64,
    /// Full usable mask of the current batch (later segments).
    batch_usable: u64,
    /// Bad zones of the current batch not yet passed.
    batch_bad: u64,
    /// Emit tokens via the scalar advance while `pos < scalar_until`.
    scalar_until: usize,
    /// Eagerly computed masks for the batch at `pre_base` (usize::MAX =
    /// none).
    pre_base: usize,
    pre_usable: u64,
    pre_bad: u64,
}

impl MaskState {
    #[inline]
    fn new(pos: usize) -> Self {
        let scalar_until = if simd_scanner_available() {
            pos
        } else {
            usize::MAX
        };
        Self {
            pos,
            scan: pos,
            mask_base: pos,
            rem: 0,
            batch_usable: 0,
            batch_bad: 0,
            scalar_until,
            pre_base: usize::MAX,
            pre_usable: 0,
            pre_bad: 0,
        }
    }

    /// Load the segment of `batch_usable` bits in [from_bit, next bad run)
    /// into `rem` and aim `scalar_until` past that bad run at the next
    /// trusted boundary (or the batch end).
    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn load_segment(&mut self, from_bit: u32) {
        let live = u64::MAX << from_bit;
        let seg_bad = self.batch_bad & live;
        if seg_bad == 0 {
            self.rem = self.batch_usable & live;
            self.batch_bad = 0;
        } else {
            let nb = seg_bad.trailing_zeros();
            self.rem = self.batch_usable & live & ((1u64 << nb) - 1);
            let rest = self.batch_usable & (u64::MAX << nb);
            self.scalar_until = if rest != 0 {
                self.mask_base + rest.trailing_zeros() as usize
            } else {
                self.mask_base + 64
            };
        }
        // A bit at the pending token's own start is not an end. Branchless:
        // whether the pending token starts exactly at this segment's first
        // bit is a ~20% coin flip on natural text.
        let at_start = self.pos == self.mask_base + from_bit as usize;
        self.rem &= !(u64::from(at_start) << from_bit);
    }

    /// Visit token ranges while keeping the mask state live across every piece.
    #[inline(always)]
    fn for_each_span<S: MaskScheme>(&mut self, input: &str, sink: &mut impl FusedPieceSink) {
        let bytes = input.as_bytes();
        let len = bytes.len();
        loop {
            if self.rem != 0 {
                let rem = std::mem::take(&mut self.rem);
                // SAFETY: mask bits are exact UTF-8 token boundaries.
                unsafe { sink.push_mask(input, self.mask_base, &mut self.pos, rem) };
            }
            while self.pos < self.scalar_until {
                if self.pos >= len {
                    return;
                }
                let start = self.pos;
                let end = S::advance(bytes, start);
                self.pos = end;
                // SAFETY: `advance` returns the next exact UTF-8 boundary.
                unsafe { sink.push_piece(input, start, end) };
            }
            #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
            {
                // Continue with the current batch's next trusted segment
                // after a scalar gap (each batch is computed exactly once).
                if self.batch_bad != 0 && self.pos < self.mask_base + 64 {
                    self.load_segment((self.pos - self.mask_base) as u32);
                    continue;
                }
                self.batch_bad = 0;
                // Resume after a scalar overrun WITHOUT leaving the
                // 64-byte grid: the precomputed next batch (and the
                // prefetch chain behind it) stays valid, where rebasing
                // to the token boundary invalidated it on every bad-zone
                // overrun — a large part of a deferral's ~800-cycle
                // cost. Grid bits below `pos` may be stale run-internal
                // bits (a ws or digit run the scalar walked through can
                // cross the grid base); they are masked by the
                // `from_bit` passed to load_segment below, and every
                // path that puts `pos` inside such a run goes through a
                // deferral first, so those bits are never trusted.
                while self.scan + 64 <= self.pos {
                    self.scan += 64;
                }
                if self.scan + 70 > len {
                    // Tail: scalar to the end of the buffer.
                    self.scalar_until = usize::MAX;
                    continue;
                }
                let (usable, bad) = if self.pre_base == self.scan {
                    (self.pre_usable, self.pre_bad)
                } else {
                    S::batch_masks(bytes, self.scan)
                };
                self.mask_base = self.scan;
                self.scan += 64;
                self.batch_usable = usable;
                self.batch_bad = bad;
                // Kick off the next batch now; its SIMD chain overlaps this
                // batch's pops instead of stalling the next refill. Also
                // done for dirty batches: a scalar overrun past the batch
                // end just leaves the precompute unused (`pre_base` misses),
                // while gaps that resolve inside the batch — the common
                // case — keep the pipeline primed. Dirty batches used to
                // skip this, and paying the whole SIMD chain latency at the
                // next refill was a large part of their ~270-cycle cost.
                if self.scan + 70 <= len {
                    let (u2, b2) = S::batch_masks(bytes, self.scan);
                    self.pre_base = self.scan;
                    self.pre_usable = u2;
                    self.pre_bad = b2;
                } else {
                    self.pre_base = usize::MAX;
                }
                // An overrun may have left `pos` inside this grid batch;
                // start from its bit so stale bits below never pop. The
                // no-overrun case keeps the constant argument (and its
                // folded codegen) — schemes with few bad zones take that
                // branch essentially always.
                if self.pos > self.mask_base {
                    self.load_segment((self.pos - self.mask_base) as u32);
                } else {
                    self.load_segment(0);
                }
            }
            #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
            {
                // Unreachable: scalar_until is usize::MAX on this arch.
                self.scalar_until = usize::MAX;
            }
        }
    }
}

/// Unicode classes needed by the case-aware o200k grammar.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
enum O200kCharClass {
    Upper,
    Lower,
    Caseless,
    Mark,
    Number,
    Whitespace,
    Other,
}

/// Orthogonal packed-table bit for Kimi's leading Han alternative.
const O200K_HAN: u8 = 1 << 3;

/// Compile-time grammar policy shared by the o200k mask algebra.
trait O200kFlavor {
    /// Whether suffix contractions form their own alternatives.
    const CONTRACTIONS: bool;
    /// Whether number runs split into groups of at most three scalars.
    const THREE_DIGIT_NUMBERS: bool;
    /// Whether slash may be absorbed into a punctuation token's newline tail.
    const SLASH_PUNCT_TAIL: bool;
    /// Whether Unicode batches can use the shared o200k class algebra.
    const SIMD_UNICODE: bool;
}

/// Build the packed o200k class table once from ICU's canonical properties.
fn build_o200k_class_table() -> Box<[u8]> {
    use icu_properties::{
        CodePointMapData, CodePointSetData,
        props::{GeneralCategory, GeneralCategoryGroup, Script, WhiteSpace},
    };

    let mut classes = vec![O200kCharClass::Other as u8; 0x110000];
    let categories = CodePointMapData::<GeneralCategory>::new();
    for (category, class) in [
        (GeneralCategory::UppercaseLetter, O200kCharClass::Upper),
        (GeneralCategory::TitlecaseLetter, O200kCharClass::Upper),
        (GeneralCategory::LowercaseLetter, O200kCharClass::Lower),
        (GeneralCategory::ModifierLetter, O200kCharClass::Caseless),
        (GeneralCategory::OtherLetter, O200kCharClass::Caseless),
    ] {
        for range in categories.iter_ranges_for_value(category) {
            classes[*range.start() as usize..=*range.end() as usize].fill(class as u8);
        }
    }
    for (group, class) in [
        (GeneralCategoryGroup::Mark, O200kCharClass::Mark),
        (GeneralCategoryGroup::Number, O200kCharClass::Number),
    ] {
        for range in categories.iter_ranges_for_group(group) {
            classes[*range.start() as usize..=*range.end() as usize].fill(class as u8);
        }
    }
    for range in CodePointSetData::new::<WhiteSpace>().iter_ranges() {
        classes[*range.start() as usize..=*range.end() as usize]
            .fill(O200kCharClass::Whitespace as u8);
    }
    for range in CodePointMapData::<Script>::new().iter_ranges_for_value(Script::Han) {
        for class in &mut classes[*range.start() as usize..=*range.end() as usize] {
            *class |= O200K_HAN;
        }
    }
    // Unicode has an even number of scalar values, so every class byte forms one packed pair.
    classes
        .as_chunks::<2>()
        .0
        .iter()
        .map(|pair| pair[0] | pair[1] << 4)
        .collect()
}

static O200K_CLASS_TABLE: std::sync::LazyLock<Box<[u8]>> =
    std::sync::LazyLock::new(build_o200k_class_table);

/// Pre-resolved view of the packed class table for Unicode batch loops.
#[derive(Clone, Copy)]
struct O200kClassTable(&'static [u8]);

impl O200kClassTable {
    /// Resolve the lazy static and its boxed slice once.
    #[inline]
    fn get() -> Self {
        Self(&O200K_CLASS_TABLE)
    }

    /// Load one scalar's packed class and orthogonal Han bit.
    #[inline(always)]
    fn tag_of(self, codepoint: u32) -> u8 {
        let packed = unsafe { *self.0.get_unchecked((codepoint >> 1) as usize) };
        packed >> ((codepoint & 1) << 2) & 0x0f
    }

    /// Return one scalar's o200k class and orthogonal Han membership.
    #[inline(always)]
    fn class_and_han(self, codepoint: u32) -> (O200kCharClass, bool) {
        let tag = self.tag_of(codepoint);
        let class = match tag & !O200K_HAN {
            0 => O200kCharClass::Upper,
            1 => O200kCharClass::Lower,
            2 => O200kCharClass::Caseless,
            3 => O200kCharClass::Mark,
            4 => O200kCharClass::Number,
            5 => O200kCharClass::Whitespace,
            _ => O200kCharClass::Other,
        };
        (class, tag & O200K_HAN != 0)
    }

    /// Classify one valid scalar with one unchecked packed-table load.
    #[inline(always)]
    fn class_of(self, codepoint: u32) -> O200kCharClass {
        self.class_and_han(codepoint).0
    }

    /// Return whether one valid scalar belongs to the Unicode Han script.
    #[inline(always)]
    fn is_han(self, codepoint: u32) -> bool {
        // Dense unified-ideograph blocks avoid a dependent table load on ordinary Han text.
        matches!(codepoint, 0x3400..=0x4dbf | 0x4e00..=0x9fff)
            || self.tag_of(codepoint) & O200K_HAN != 0
    }
}

/// Classify one valid scalar with a single packed-table load.
#[inline(always)]
fn o200k_class_of(codepoint: u32) -> O200kCharClass {
    O200kClassTable::get().class_of(codepoint)
}

/// Test one ASCII byte for the Unicode letter subset.
#[inline(always)]
fn is_letter(byte: u8) -> bool {
    (byte | 0x20).wrapping_sub(b'a') < 26
}

/// Test one ASCII byte for the Unicode number subset.
#[inline(always)]
fn is_digit(byte: u8) -> bool {
    byte.wrapping_sub(b'0') < 10
}

/// Test one ASCII byte for tokenizer whitespace.
#[inline(always)]
fn is_ascii_ws(byte: u8) -> bool {
    byte == b' ' || byte.wrapping_sub(9) < 5
}

/// Test one ASCII byte for strict uppercase.
#[inline(always)]
fn is_upper_ascii(byte: u8) -> bool {
    byte.wrapping_sub(b'A') < 26
}

/// Test one byte for the flavor's punctuation tail class.
#[inline(always)]
fn is_tail_byte<F: O200kFlavor>(byte: u8) -> bool {
    matches!(byte, b'\r' | b'\n') || (F::SLASH_PUNCT_TAIL && byte == b'/')
}

/// Decode one valid non-ASCII scalar without a bounds check in batch interiors.
#[inline(always)]
unsafe fn decode_cp_inbounds(bytes: &[u8], pos: usize) -> (u32, usize) {
    unsafe {
        let first = *bytes.get_unchecked(pos) as u32;
        let second = (*bytes.get_unchecked(pos + 1) & 0x3f) as u32;
        if first < 0xe0 {
            return (((first & 0x1f) << 6) | second, 2);
        }
        let third = (*bytes.get_unchecked(pos + 2) & 0x3f) as u32;
        if first < 0xf0 {
            return (((first & 0x0f) << 12) | (second << 6) | third, 3);
        }
        let fourth = (*bytes.get_unchecked(pos + 3) & 0x3f) as u32;
        (
            ((first & 7) << 18) | (second << 12) | (third << 6) | fourth,
            4,
        )
    }
}

/// Decode one valid non-ASCII scalar near any buffer position.
#[inline(always)]
unsafe fn decode_cp(bytes: &[u8], pos: usize) -> (u32, usize) {
    if pos + 4 <= bytes.len() {
        return unsafe { decode_cp_inbounds(bytes, pos) };
    }
    let text = unsafe { std::str::from_utf8_unchecked(&bytes[pos..]) };
    let ch = unsafe { text.chars().next().unwrap_unchecked() };
    (ch as u32, ch.len_utf8())
}

/// Scan Kimi's leading `\p{Han}+` alternative directly from one token boundary.
#[inline(always)]
fn scan_kimi_han_run(bytes: &[u8], pos: usize) -> Option<usize> {
    if bytes[pos] < 0x80 {
        return None;
    }
    let classes = O200kClassTable::get();
    // SAFETY: mask schemes receive bytes from the caller's valid UTF-8 `str`.
    let (codepoint, length) = unsafe { decode_cp(bytes, pos) };
    if !classes.is_han(codepoint) {
        return None;
    }

    let mut end = pos + length;
    while end < bytes.len() && bytes[end] >= 0x80 {
        // SAFETY: `end` advances only by decoded scalar lengths from valid UTF-8.
        let (codepoint, length) = unsafe { decode_cp(bytes, end) };
        if !classes.is_han(codepoint) {
            break;
        }
        end += length;
    }
    Some(end)
}

/// Scan an unambiguous Kimi punctuation run and its carriage-return/newline tail.
#[inline(always)]
fn scan_kimi_punctuation_run(bytes: &[u8], pos: usize) -> Option<usize> {
    let classes = O200kClassTable::get();
    let first = bytes[pos];
    let first_end = if first < 0x80 {
        if is_letter(first) || is_digit(first) || is_ascii_ws(first) {
            return None;
        }
        pos + 1
    } else {
        // SAFETY: mask schemes receive bytes from the caller's valid UTF-8 `str`.
        let (codepoint, length) = unsafe { decode_cp(bytes, pos) };
        let (class, han) = classes.class_and_han(codepoint);
        if class != O200kCharClass::Other || han {
            return None;
        }
        pos + length
    };

    if first_end < bytes.len() {
        let next = bytes[first_end];
        let starts_word = if next < 0x80 {
            is_letter(next)
        } else {
            // SAFETY: `first_end` is the boundary after one valid scalar.
            let (codepoint, _) = unsafe { decode_cp(bytes, first_end) };
            let (class, han) = classes.class_and_han(codepoint);
            !han && matches!(
                class,
                O200kCharClass::Upper
                    | O200kCharClass::Lower
                    | O200kCharClass::Caseless
                    | O200kCharClass::Mark
            )
        };
        // One punctuation scalar may be the optional prefix of a word alternative.
        if starts_word {
            return None;
        }
    }

    let mut end = first_end;
    while end < bytes.len() {
        let byte = bytes[end];
        if byte < 0x80 {
            if is_letter(byte) || is_digit(byte) || is_ascii_ws(byte) {
                break;
            }
            end += 1;
            continue;
        }
        // SAFETY: `end` advances only by decoded scalar lengths from valid UTF-8.
        let (codepoint, length) = unsafe { decode_cp(bytes, end) };
        let class = classes.class_of(codepoint);
        if !matches!(class, O200kCharClass::Other | O200kCharClass::Mark) {
            break;
        }
        end += length;
    }
    while matches!(bytes.get(end), Some(b'\r' | b'\n')) {
        end += 1;
    }
    Some(end)
}

/// Return the class, lead, and end of the scalar containing `pos - 1`.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
unsafe fn char_through_o200k(bytes: &[u8], pos: usize) -> (O200kCharClass, usize, usize) {
    let byte = bytes[pos - 1];
    if byte < 0x80 {
        let class = if is_upper_ascii(byte) {
            O200kCharClass::Upper
        } else if is_letter(byte) {
            O200kCharClass::Lower
        } else if is_digit(byte) {
            O200kCharClass::Number
        } else if is_ascii_ws(byte) {
            O200kCharClass::Whitespace
        } else {
            O200kCharClass::Other
        };
        return (class, pos - 1, pos);
    }
    let mut lead = pos - 1;
    while lead > 0 && bytes[lead] & 0xc0 == 0x80 {
        lead -= 1;
    }
    let (codepoint, length) = unsafe { decode_cp_inbounds(bytes, lead) };
    (o200k_class_of(codepoint), lead, lead + length)
}

/// Test one in-bounds scalar for GPT-2 whitespace semantics.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn r50k_is_ws_at(bytes: &[u8], index: usize) -> bool {
    let byte = bytes[index];
    if byte < 0x80 {
        return is_ascii_ws(byte);
    }
    let (codepoint, _) = unsafe { decode_cp_inbounds(bytes, index) };
    o200k_class_of(codepoint) == O200kCharClass::Whitespace
}

/// Derive exact GPT-2 token starts from effective ASCII and Unicode masks.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn r50k_algebra(
    bytes: &[u8],
    scan: usize,
    masks: AsciiMasks,
    unicode: OUni,
    carries: (u64, u64, u64, u64, u64),
) -> (u64, u64) {
    let ascii_ws = masks.s | masks.wt | masks.n;
    let letter = masks.l | unicode.l;
    let digit = masks.d | unicode.n;
    let whitespace = ascii_ws | unicode.ws;
    let other = !(masks.l | masks.d | ascii_ws | masks.hi) | unicode.o;
    let (previous_letter, previous_digit, previous_space, previous_ws, previous_other) = carries;

    let same_run = (letter & ((letter << 1) | previous_letter))
        | (digit & ((digit << 1) | previous_digit))
        | (other & ((other << 1) | previous_other));
    let after_space = (masks.s << 1) | previous_space;
    let ordinary = !whitespace & !same_run & !after_space & !unicode.cont;

    // Lead-length masks test the scalar after each whitespace character.
    let non_ws = !whitespace;
    let mut split =
        (ascii_ws & (non_ws >> 1)) | (unicode.w2 & (non_ws >> 2)) | (unicode.w3 & (non_ws >> 3));
    let edge_multi = (unicode.w2 & (1 << 62)) | (unicode.w3 & (1 << 61));
    let next = bytes[scan + 64];
    if next < 0x80 && edge_multi == 0 {
        split = (split & !(1 << 63)) | ((u64::from(!is_ascii_ws(next)) << 63) & ascii_ws);
    } else {
        let edge = edge_multi | ((1 << 63) & ascii_ws);
        if edge != 0 {
            if !r50k_is_ws_at(bytes, scan + 64) {
                split |= edge;
            } else {
                split &= !edge;
            }
        }
    }
    let previous_ws = (whitespace << 1) | previous_ws;
    let whitespace_boundary = (ascii_ws | unicode.w2 | unicode.w3) & (!previous_ws | split);
    let mut boundary = ordinary | whitespace_boundary;
    let mut bad = unicode.resid | (unicode.resid << 1) | (unicode.resid >> 1);

    let mut contractions = masks.ap & boundary & !bad;
    while contractions != 0 {
        let index = contractions.trailing_zeros() as usize;
        contractions &= contractions - 1;
        if index >= 61 {
            bad |= u64::MAX << index;
            break;
        }
        let length = match bytes[scan + index + 1] {
            b's' | b'd' | b'm' | b't' => 2,
            b'l' if bytes[scan + index + 2] == b'l' => 3,
            b'v' if bytes[scan + index + 2] == b'e' => 3,
            b'r' if bytes[scan + index + 2] == b'e' => 3,
            _ => 0,
        };
        if length != 0 {
            boundary &= !(1u64 << (index + 1));
            boundary |= 1u64 << (index + length);
        }
    }
    (boundary & !bad, bad)
}

/// Resolve a GPT-2 block containing or following a Unicode scalar.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[cfg_attr(
    target_arch = "x86_64",
    target_feature(enable = "bmi1,bmi2,lzcnt,popcnt")
)]
#[inline(never)]
fn r50k_extended_masks(bytes: &[u8], scan: usize, masks: AsciiMasks) -> (u64, u64) {
    let mut claimed = OUni::default();
    let carries = if scan == 0 {
        (0, 0, 0, 0, 0)
    } else if bytes[scan - 1] < 0x80 {
        let byte = bytes[scan - 1];
        let letter = u64::from(is_letter(byte));
        let digit = u64::from(is_digit(byte));
        let whitespace = u64::from(is_ascii_ws(byte));
        (
            letter,
            digit,
            u64::from(byte == b' '),
            whitespace,
            u64::from(letter == 0 && digit == 0 && whitespace == 0),
        )
    } else {
        let (class, _, end) = unsafe { char_through_o200k(bytes, scan) };
        // Claim continuation bytes from the scalar that straddles this block.
        let bytes_in_batch = if end > scan {
            (1u64 << (end - scan)) - 1
        } else {
            0
        };
        claimed.cont = bytes_in_batch;
        match class {
            O200kCharClass::Upper | O200kCharClass::Lower | O200kCharClass::Caseless => {
                claimed.l = bytes_in_batch;
                (1, 0, 0, 0, 0)
            }
            O200kCharClass::Number => {
                claimed.n = bytes_in_batch;
                (0, 1, 0, 0, 0)
            }
            O200kCharClass::Whitespace => {
                claimed.ws = bytes_in_batch;
                claimed.resid = bytes_in_batch;
                (0, 0, 0, 1, 0)
            }
            O200kCharClass::Mark | O200kCharClass::Other => {
                claimed.o = bytes_in_batch;
                (0, 0, 0, 0, 1)
            }
        }
    };

    let mut unicode = unsafe { classify_uni_o200k::<false>(bytes, scan, masks.hi & !claimed.cont) };
    unicode.l |= claimed.l;
    unicode.n |= claimed.n;
    unicode.o |= claimed.o;
    unicode.ws |= claimed.ws;
    unicode.cont |= claimed.cont;
    unicode.resid |= claimed.resid;
    r50k_algebra(bytes, scan, masks, unicode, carries)
}

/// Resolve one GPT-2 block with the ASCII or full Unicode mask algebra.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[cfg_attr(
    target_arch = "x86_64",
    target_feature(enable = "bmi1,bmi2,lzcnt,popcnt")
)]
#[cfg_attr(target_arch = "aarch64", inline(always))]
#[cfg_attr(target_arch = "x86_64", inline)]
fn r50k_masks(bytes: &[u8], scan: usize, masks: AsciiMasks) -> (u64, u64) {
    if masks.hi != 0 || (scan != 0 && bytes[scan - 1] >= 0x80) {
        return r50k_extended_masks(bytes, scan, masks);
    }
    let carries = if scan == 0 {
        (0, 0, 0, 0, 0)
    } else {
        let byte = bytes[scan - 1];
        let letter = u64::from(is_letter(byte));
        let digit = u64::from(is_digit(byte));
        let whitespace = u64::from(is_ascii_ws(byte));
        (
            letter,
            digit,
            u64::from(byte == b' '),
            whitespace,
            u64::from(letter == 0 && digit == 0 && whitespace == 0),
        )
    };
    r50k_algebra(bytes, scan, masks, OUni::default(), carries)
}

/// Classify one GPT-2 block with NEON.
#[cfg(target_arch = "aarch64")]
#[inline]
fn r50k_batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
    use std::arch::aarch64::*;
    debug_assert!(scan + 70 <= bytes.len());
    unsafe {
        let pointer = bytes.as_ptr().add(scan);
        let zero = vdupq_n_u8(0);
        let mut letters = [zero; 4];
        let mut digits = [zero; 4];
        let mut spaces = [zero; 4];
        let mut whitespace = [zero; 4];
        let mut apostrophes = [zero; 4];
        let mut high = [zero; 4];
        for index in 0..4 {
            let value = vld1q_u8(pointer.add(index * 16));
            let lower = vorrq_u8(value, vdupq_n_u8(0x20));
            letters[index] = vcleq_u8(vsubq_u8(lower, vdupq_n_u8(b'a')), vdupq_n_u8(25));
            digits[index] = vcleq_u8(vsubq_u8(value, vdupq_n_u8(b'0')), vdupq_n_u8(9));
            spaces[index] = vceqq_u8(value, vdupq_n_u8(b' '));
            whitespace[index] = vorrq_u8(
                spaces[index],
                vcleq_u8(vsubq_u8(value, vdupq_n_u8(9)), vdupq_n_u8(4)),
            );
            apostrophes[index] = vceqq_u8(value, vdupq_n_u8(b'\''));
            high[index] = vcltzq_s8(vreinterpretq_s8_u8(value));
        }
        let letter = movemask64(letters[0], letters[1], letters[2], letters[3]);
        let digit = movemask64(digits[0], digits[1], digits[2], digits[3]);
        let space = movemask64(spaces[0], spaces[1], spaces[2], spaces[3]);
        let ws = movemask64(whitespace[0], whitespace[1], whitespace[2], whitespace[3]);
        let high = movemask64(high[0], high[1], high[2], high[3]);
        let apostrophe_any = vorrq_u8(
            vorrq_u8(apostrophes[0], apostrophes[1]),
            vorrq_u8(apostrophes[2], apostrophes[3]),
        );
        let apostrophe = if vmaxvq_u8(apostrophe_any) == 0 {
            0
        } else {
            movemask64(
                apostrophes[0],
                apostrophes[1],
                apostrophes[2],
                apostrophes[3],
            )
        };
        r50k_masks(
            bytes,
            scan,
            AsciiMasks {
                l: letter,
                d: digit,
                s: space,
                wt: ws & !space,
                n: 0,
                hi: high,
                ap: apostrophe,
            },
        )
    }
}

/// Classify one GPT-2 block with the runtime-selected x86 SIMD tier.
#[cfg(target_arch = "x86_64")]
#[inline(always)]
fn r50k_batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
    debug_assert!(simd_scanner_available());
    if avx512_scanner_available() {
        return unsafe { r50k_batch_masks_avx512(bytes, scan) };
    }
    unsafe { r50k_batch_masks_avx2(bytes, scan) }
}

/// Classify one GPT-2 block with AVX-512.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vl,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
unsafe fn r50k_batch_masks_avx512(bytes: &[u8], scan: usize) -> (u64, u64) {
    let masks = ascii_masks_avx512(bytes, scan);
    r50k_masks(bytes, scan, masks)
}

/// Classify one GPT-2 block with AVX2.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
unsafe fn r50k_batch_masks_avx2(bytes: &[u8], scan: usize) -> (u64, u64) {
    let masks = ascii_masks_avx2(bytes, scan);
    r50k_masks(bytes, scan, masks)
}

/// Build Qwen-family carries from the two preceding ASCII bytes.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn qwen_ascii_carries(bytes: &[u8], scan: usize) -> OCarries {
    if scan == 0 {
        return OCarries::default();
    }
    let previous = bytes[scan - 1];
    let letter = is_letter(previous);
    let digit = is_digit(previous);
    let whitespace = is_ascii_ws(previous);
    let previous_two = scan >= 2
        && (bytes[scan - 2] == b' '
            || (!is_letter(bytes[scan - 2])
                && !is_digit(bytes[scan - 2])
                && !is_ascii_ws(bytes[scan - 2])));
    OCarries {
        pl: u64::from(letter),
        ps: u64::from(previous == b' '),
        pwt: u64::from(whitespace && !matches!(previous, b' ' | b'\r' | b'\n')),
        po: u64::from(!letter && !digit && !whitespace),
        pws: u64::from(whitespace),
        pd: u64::from(digit),
        c2_os: u64::from(previous_two),
        ..OCarries::default()
    }
}

/// Derive exact Qwen-family token starts from byte-class masks.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn qwen_algebra<const WORD_MARKS: bool, const DIGITS3: bool>(
    bytes: &[u8],
    scan: usize,
    masks: AsciiMasks,
    carries: OCarries,
    mut unicode: OUni,
) -> (u64, u64) {
    if WORD_MARKS {
        unicode.l |= unicode.mk;
        unicode.o &= !unicode.mk;
    }

    let letter = masks.l | unicode.l;
    let whitespace_tail = masks.wt | unicode.ws;
    let other = !(masks.l | masks.d | masks.s | masks.wt | masks.n | masks.hi) | unicode.o;
    let whitespace = masks.s | whitespace_tail | masks.n;

    // An optional punctuation prefix is absorbed only when it did not
    // itself follow punctuation or a literal space.
    let one_byte = !(unicode.cont | unicode.lead2 | unicode.lead3 | unicode.lead4);
    let previous_other_or_space = ((other | masks.s) << 1) | carries.po | carries.ps;
    let two_back = ((previous_other_or_space & one_byte) << 1)
        | ((previous_other_or_space & unicode.lead2) << 2)
        | ((previous_other_or_space & unicode.lead3) << 3)
        | ((previous_other_or_space & unicode.lead4) << 4)
        | carries.c2_os
        | carries.b2b_in;
    let previous_letter = (letter << 1) | carries.pl;
    let previous_space = (masks.s << 1) | carries.ps;
    let previous_tail_ws = (whitespace_tail << 1) | carries.pwt;
    let previous_other = (other << 1) | carries.po;
    let absorbed_prefix = previous_other & !two_back;
    let letter_boundaries = letter
        & !unicode.cont
        & !previous_letter
        & !previous_space
        & !previous_tail_ws
        & !absorbed_prefix;

    let digit_boundaries = if DIGITS3 && masks.d & (masks.d >> 1) != 0 {
        digit_run_splits3(masks.d)
    } else if DIGITS3 {
        masks.d
    } else {
        masks.d | (unicode.n & !unicode.cont)
    };
    let punctuation_boundaries = other & !unicode.cont & !previous_other & !previous_space;

    // CR/LF directly after punctuation remains part of that punctuation token.
    let absorbed_newline_seed = masks.n & ((other << 1) | carries.po);
    let absorbed_newlines = if absorbed_newline_seed == 0 {
        0
    } else {
        smear_up(absorbed_newline_seed, masks.n)
    };
    let effective_whitespace = whitespace & !absorbed_newlines;
    let mut bad = unicode.resid | (unicode.resid << 1) | (unicode.resid >> 1);

    // Resolve whitespace that reaches byte 63 only when the following
    // scalar proves the run ends at this block boundary.
    let next = bytes[scan + 64];
    let next_non_whitespace = if next < 0x80 {
        !is_ascii_ws(next)
    } else {
        bad >> 63 == 0 && !r50k_is_ws_at(bytes, scan + 64)
    };
    if absorbed_newlines >> 63 != 0 && !next_non_whitespace {
        bad |= 1 << 63;
    }
    let non_whitespace = !effective_whitespace;
    if effective_whitespace >> 63 != 0 && !next_non_whitespace {
        if non_whitespace == 0 {
            return (0, u64::MAX);
        }
        let highest_non_whitespace = 63 - non_whitespace.leading_zeros();
        bad |= u64::MAX << (highest_non_whitespace + 1);
    }

    // Three-character number groups crossing a scalar-only zone must
    // preserve their phase in the scalar fallback.
    if DIGITS3 {
        let seed = (masks.d & (bad << 1)) | (masks.d & carries.pd);
        if seed != 0 {
            bad |= smear_up(seed, masks.d);
        }
    }

    let whitespace_leads = (masks.s | masks.wt | masks.n | unicode.w2 | unicode.w3)
        & effective_whitespace
        & !absorbed_newlines;
    let previous_whitespace = (effective_whitespace << 1) | carries.pws;
    let edge_last = ((masks.s | masks.wt | masks.n) & (1 << 63))
        | (unicode.w2 & (1 << 62))
        | (unicode.w3 & (1 << 61));
    let next_non_whitespace_mask = u64::from(next_non_whitespace).wrapping_neg();
    let split_before_last = ((masks.s | masks.wt | masks.n) & (non_whitespace >> 1))
        | (unicode.w2 & (non_whitespace >> 2))
        | (unicode.w3 & (non_whitespace >> 3))
        | (edge_last & next_non_whitespace_mask);
    let mut whitespace_boundaries = whitespace_leads & (!previous_whitespace | split_before_last);

    // A whitespace run containing newlines ends at its last newline;
    // any remaining whitespace becomes a separate tail token.
    let mut newline_runs = masks.n & effective_whitespace & !bad;
    while newline_runs != 0 {
        let first_newline = newline_runs.trailing_zeros();
        let gap_below = non_whitespace & ((1u64 << first_newline) - 1);
        let run_start = if gap_below == 0 {
            0
        } else {
            64 - gap_below.leading_zeros()
        };
        let run_end = (non_whitespace & (u64::MAX << first_newline)).trailing_zeros();
        let run = (u64::MAX << run_start) & !u64::MAX.unbounded_shl(run_end);
        whitespace_boundaries &= !run;
        whitespace_boundaries |= 1 << run_start;
        let last_newline = 63 - (masks.n & run).leading_zeros();
        if last_newline + 1 < run_end {
            whitespace_boundaries |= 1 << (last_newline + 1);
            let tail = whitespace_leads & run & (u64::MAX << (last_newline + 1));
            whitespace_boundaries |= 1 << (63 - tail.leading_zeros());
        }
        newline_runs &= !run;
    }

    let mut boundaries =
        letter_boundaries | digit_boundaries | punctuation_boundaries | whitespace_boundaries;

    // Move boundaries across the fixed case-insensitive contraction suffixes.
    let mut contractions = masks.ap & boundaries & !bad;
    while contractions != 0 {
        let index = contractions.trailing_zeros() as usize;
        contractions &= contractions - 1;
        if index >= 61 {
            bad |= u64::MAX << index;
            break;
        }
        let first = bytes[scan + index + 1];
        if first >= 0x80 {
            bad |= 0b111 << index;
            continue;
        }
        let length = match first | 0x20 {
            b's' | b'd' | b'm' | b't' => 2,
            b'l' if bytes[scan + index + 2] | 0x20 == b'l' => 3,
            b'v' if bytes[scan + index + 2] | 0x20 == b'e' => 3,
            b'r' if bytes[scan + index + 2] | 0x20 == b'e' => 3,
            _ => 0,
        };
        if length != 0 {
            boundaries &= !(1 << (index + 1));
            boundaries |= 1 << (index + length);
        }
    }

    (boundaries & !bad, bad)
}

/// Resolve a Qwen-family block containing or following Unicode scalars.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[cfg_attr(
    target_arch = "x86_64",
    target_feature(enable = "bmi1,bmi2,lzcnt,popcnt")
)]
#[inline(never)]
fn qwen_extended_masks<const WORD_MARKS: bool, const DIGITS3: bool>(
    bytes: &[u8],
    scan: usize,
    masks: AsciiMasks,
) -> (u64, u64) {
    let mut claimed = OUni::default();
    let carries = if scan == 0 {
        OCarries::default()
    } else if bytes[scan - 1] < 0x80 && (scan < 2 || bytes[scan - 2] < 0x80) {
        qwen_ascii_carries(bytes, scan)
    } else {
        // Claim any scalar that starts before this block and ends inside it.
        let (class, lead, end) = unsafe { char_through_o200k(bytes, scan) };
        let claimed_bytes = if end > scan {
            (1 << (end - scan)) - 1
        } else {
            0
        };
        claimed.cont = claimed_bytes;
        let previous_two_other_or_space = if lead == 0 {
            false
        } else if bytes[lead - 1] == b' ' {
            true
        } else {
            let previous_two = unsafe { char_through_o200k(bytes, lead) }.0;
            matches!(previous_two, O200kCharClass::Other)
                || (!WORD_MARKS && previous_two == O200kCharClass::Mark)
        };
        let mut carries = OCarries {
            c2_os: u64::from(end <= scan && previous_two_other_or_space),
            b2b_in: if end > scan {
                u64::from(previous_two_other_or_space) << (end - scan)
            } else {
                0
            },
            pd: u64::from(class == O200kCharClass::Number),
            ..OCarries::default()
        };
        match class {
            O200kCharClass::Upper | O200kCharClass::Lower | O200kCharClass::Caseless => {
                claimed.l = claimed_bytes;
                carries.pl = 1;
            }
            O200kCharClass::Mark if WORD_MARKS => {
                claimed.l = claimed_bytes;
                carries.pl = 1;
            }
            O200kCharClass::Mark | O200kCharClass::Other => {
                claimed.o = claimed_bytes;
                carries.po = 1;
            }
            O200kCharClass::Number => {
                claimed.n = claimed_bytes;
                claimed.resid = claimed_bytes;
            }
            O200kCharClass::Whitespace => {
                claimed.ws = claimed_bytes;
                claimed.resid = claimed_bytes;
                let previous_byte = bytes[scan - 1];
                carries.ps = u64::from(previous_byte == b' ');
                carries.pwt = u64::from(
                    previous_byte >= 0x80 || !matches!(previous_byte, b' ' | b'\r' | b'\n'),
                );
                carries.pws = 1;
            }
        }
        carries
    };

    let mut unicode =
        unsafe { classify_uni_o200k::<DIGITS3>(bytes, scan, masks.hi & !claimed.cont) };
    unicode.l |= claimed.l;
    unicode.n |= claimed.n;
    unicode.o |= claimed.o;
    unicode.ws |= claimed.ws;
    unicode.cont |= claimed.cont;
    unicode.resid |= claimed.resid;
    qwen_algebra::<WORD_MARKS, DIGITS3>(bytes, scan, masks, carries, unicode)
}

/// Resolve one Qwen-family block with ASCII or full Unicode mask algebra.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[cfg_attr(
    target_arch = "x86_64",
    target_feature(enable = "bmi1,bmi2,lzcnt,popcnt")
)]
#[cfg_attr(target_arch = "aarch64", inline(always))]
#[cfg_attr(target_arch = "x86_64", inline)]
fn qwen_masks<const WORD_MARKS: bool, const DIGITS3: bool>(
    bytes: &[u8],
    scan: usize,
    masks: AsciiMasks,
) -> (u64, u64) {
    if masks.hi != 0
        || (scan >= 1 && bytes[scan - 1] >= 0x80)
        || (scan >= 2 && bytes[scan - 2] >= 0x80)
    {
        return qwen_extended_masks::<WORD_MARKS, DIGITS3>(bytes, scan, masks);
    }
    qwen_algebra::<WORD_MARKS, DIGITS3>(
        bytes,
        scan,
        masks,
        qwen_ascii_carries(bytes, scan),
        OUni::default(),
    )
}

/// Classify one Qwen-family block with NEON.
#[cfg(target_arch = "aarch64")]
#[inline]
fn qwen_batch_masks<const WORD_MARKS: bool, const DIGITS3: bool>(
    bytes: &[u8],
    scan: usize,
) -> (u64, u64) {
    use std::arch::aarch64::*;
    debug_assert!(scan + 70 <= bytes.len());
    unsafe {
        let pointer = bytes.as_ptr().add(scan);
        let zero = vdupq_n_u8(0);
        let mut letters = [zero; 4];
        let mut digits = [zero; 4];
        let mut spaces = [zero; 4];
        let mut whitespace = [zero; 4];
        let mut newlines = [zero; 4];
        let mut apostrophes = [zero; 4];
        let mut high = [zero; 4];
        for index in 0..4 {
            let value = vld1q_u8(pointer.add(index * 16));
            let lower = vorrq_u8(value, vdupq_n_u8(0x20));
            letters[index] = vcleq_u8(vsubq_u8(lower, vdupq_n_u8(b'a')), vdupq_n_u8(25));
            digits[index] = vcleq_u8(vsubq_u8(value, vdupq_n_u8(b'0')), vdupq_n_u8(9));
            spaces[index] = vceqq_u8(value, vdupq_n_u8(b' '));
            whitespace[index] = vorrq_u8(
                spaces[index],
                vcleq_u8(vsubq_u8(value, vdupq_n_u8(9)), vdupq_n_u8(4)),
            );
            newlines[index] = vorrq_u8(
                vceqq_u8(value, vdupq_n_u8(b'\r')),
                vceqq_u8(value, vdupq_n_u8(b'\n')),
            );
            apostrophes[index] = vceqq_u8(value, vdupq_n_u8(b'\''));
            high[index] = vcltzq_s8(vreinterpretq_s8_u8(value));
        }
        let letter = movemask64(letters[0], letters[1], letters[2], letters[3]);
        let digit = movemask64(digits[0], digits[1], digits[2], digits[3]);
        let space = movemask64(spaces[0], spaces[1], spaces[2], spaces[3]);
        let ws = movemask64(whitespace[0], whitespace[1], whitespace[2], whitespace[3]);
        let newline = movemask64(newlines[0], newlines[1], newlines[2], newlines[3]);
        let high = movemask64(high[0], high[1], high[2], high[3]);
        let apostrophe_any = vorrq_u8(
            vorrq_u8(apostrophes[0], apostrophes[1]),
            vorrq_u8(apostrophes[2], apostrophes[3]),
        );
        let apostrophe = if vmaxvq_u8(apostrophe_any) == 0 {
            0
        } else {
            movemask64(
                apostrophes[0],
                apostrophes[1],
                apostrophes[2],
                apostrophes[3],
            )
        };
        qwen_masks::<WORD_MARKS, DIGITS3>(
            bytes,
            scan,
            AsciiMasks {
                l: letter,
                d: digit,
                s: space,
                wt: ws & !space & !newline,
                n: newline,
                hi: high,
                ap: apostrophe,
            },
        )
    }
}

/// Classify one Qwen-family block with the runtime-selected x86 SIMD tier.
#[cfg(target_arch = "x86_64")]
#[inline(always)]
fn qwen_batch_masks<const WORD_MARKS: bool, const DIGITS3: bool>(
    bytes: &[u8],
    scan: usize,
) -> (u64, u64) {
    debug_assert!(simd_scanner_available());
    if avx512_scanner_available() {
        return unsafe { qwen_batch_masks_avx512::<WORD_MARKS, DIGITS3>(bytes, scan) };
    }
    unsafe { qwen_batch_masks_avx2::<WORD_MARKS, DIGITS3>(bytes, scan) }
}

/// Classify one Qwen-family block with AVX-512.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vl,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
unsafe fn qwen_batch_masks_avx512<const WORD_MARKS: bool, const DIGITS3: bool>(
    bytes: &[u8],
    scan: usize,
) -> (u64, u64) {
    qwen_masks::<WORD_MARKS, DIGITS3>(bytes, scan, ascii_masks_avx512(bytes, scan))
}

/// Classify one Qwen-family block with AVX2.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
unsafe fn qwen_batch_masks_avx2<const WORD_MARKS: bool, const DIGITS3: bool>(
    bytes: &[u8],
    scan: usize,
) -> (u64, u64) {
    qwen_masks::<WORD_MARKS, DIGITS3>(bytes, scan, ascii_masks_avx2(bytes, scan))
}

// -----------------------------------------------------------------------
// Mask-scanner boundary algebra
// -----------------------------------------------------------------------

/// Smear `seed` upward (toward higher bits) through contiguous set bits of
/// `within`, in log steps.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn smear_up(seed: u64, within: u64) -> u64 {
    let mut a = seed;
    let mut m = within;
    let mut sh = 1u32;
    while sh < 64 {
        a |= (a << sh) & m;
        m &= m << sh;
        sh <<= 1;
    }
    a
}

/// Per-byte class masks for a batch's unicode chars under the o200k
/// classifier — the o200k analogue of [`UniClasses`], with the
/// case-split letter masks the scheme needs. Every byte of a classified
/// char carries the char's class, so byte-adjacency == char-adjacency.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[derive(Clone, Copy, Default)]
struct OUni {
    /// All letter-run bytes (upper + lower + caseless; marks excluded —
    /// they are contextual and deferred via `mk`).
    l: u64,
    /// Strict-upper (Lu/Lt) bytes.
    u: u64,
    /// Caseless-letter (Lm/Lo) bytes.
    cl: u64,
    /// Number / punct-run / whitespace bytes.
    n: u64,
    o: u64,
    ws: u64,
    /// Whitespace lead bits by char length (for `(?!\S)` shift tests).
    w2: u64,
    w3: u64,
    /// Lead bits of all classified chars by length (two-chars-back rule).
    lead2: u64,
    lead3: u64,
    lead4: u64,
    /// Continuation bytes of classified chars.
    cont: u64,
    /// Bytes only the scalar path can decide (±1 bad smear): number chars
    /// when their scheme groups by count, whitespace straddling the batch
    /// end, and stray continuation bytes.
    resid: u64,
    /// Mark bytes (±4 bad smear). A mark's run-contextual class can
    /// affect boundaries up to two CHARS after it, which multi-byte
    /// followers can push past the 4-byte smear; those stragglers are
    /// wrongly-cleared bits (extending the scalar walk) or wrongly-set
    /// bits interior to a token starting inside the zone, both killed by
    /// MaskState's resume masking after the scalar overrun — the same
    /// invariant the resid zones rely on.
    mk: u64,
}

/// Boundary carries from the chars before the batch (o200k variant of the
/// cl100k family's `Carries`, plus the case and absorbed-tail bits).
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[derive(Clone, Copy, Default)]
struct OCarries {
    /// P1 is a letter / strict-upper / caseless / space (0x20) /
    /// non-newline non-space ws / punct / any ws / digit.
    pl: u64,
    pu: u64,
    pcl: u64,
    ps: u64,
    pwt: u64,
    po: u64,
    pws: u64,
    pd: u64,
    /// P2 is punct-or-space, for a char lead at bit 0.
    c2_os: u64,
    /// Same test positioned at the first lead AFTER a straddling-in P1.
    b2b_in: u64,
    /// P1 is an absorbed `[\r\n/]*` tail byte whose token may continue
    /// into this batch (seeds the tail smear at bit 0).
    p_abs: bool,
    /// The tail walkback could not resolve (pathological run): the batch's
    /// leading tail-class run must be a bad zone.
    force_bad_lead: bool,
}

/// Was the tail-class byte at `scan - 1` absorbed by a punct run's
/// `[\r\n/]*` tail (as opposed to being a fresh punct-run `/` or a
/// ws-run newline)? Walks the tail-class run back (bounded) and
/// classifies the byte before it. `None`: unresolved (over-long run, or a
/// preceding mark whose own class is run-contextual).
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
fn prev_tail_absorbed<F: O200kFlavor>(bytes: &[u8], scan: usize) -> Option<bool> {
    debug_assert!(scan >= 1 && is_tail_byte::<F>(bytes[scan - 1]));
    let mut r = scan - 1;
    let mut steps = 0;
    while r > 0 && is_tail_byte::<F>(bytes[r - 1]) {
        r -= 1;
        steps += 1;
        if steps > 8 {
            return None;
        }
    }
    // T-run = bytes[r..scan]. The `[\r\n/]*` tail is greedy, so once
    // absorption triggers — at the first newline that directly follows a
    // punct-run char (an in-run slash, or the pre-run char for a
    // run-leading newline) — everything to the run's end is absorbed.
    // Before the trigger, newlines are ws-run members and slashes are
    // ordinary punct-run bytes.
    let run = &bytes[r..scan];
    let mut trigger = usize::MAX;
    let mut seen_slash = false;
    for (j, &b) in run.iter().enumerate() {
        if b == b'/' {
            seen_slash = true;
            continue;
        }
        if seen_slash {
            trigger = j;
            break;
        }
        if j == 0 {
            // Run-leading newline: the pre-run char decides.
            if r == 0 {
                continue;
            }
            let pb = bytes[r - 1];
            let pred_punct = if pb < 0x80 {
                if !is_letter(pb) && !is_digit(pb) && !is_ascii_ws(pb) {
                    Some(true)
                } else {
                    Some(false)
                }
            } else {
                let mut k = r - 1;
                while k > 0 && bytes[k] & 0xC0 == 0x80 {
                    k -= 1;
                }
                let (cp, _) = unsafe { decode_cp(bytes, k) };
                match o200k_class_of(cp) {
                    O200kCharClass::Other => Some(true),
                    // A mark continues whatever run precedes it.
                    O200kCharClass::Mark => None,
                    _ => Some(false),
                }
            };
            match pred_punct {
                Some(true) => {
                    trigger = 0;
                    break;
                }
                Some(false) => {}
                None => return None,
            }
        }
    }
    Some(scan - 1 - r >= trigger)
}

/// Two-back "punct or space" test (`c2_os`) for the ASCII byte at `idx`.
/// A slash may be an absorbed tail byte — a token end, neither punct-run
/// member nor space — so it resolves through the walkback. `None`:
/// unresolved (callers set `force_bad_lead`).
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn c2_os_ascii<F: O200kFlavor>(bytes: &[u8], idx: usize) -> Option<u64> {
    let b2 = bytes[idx];
    if F::SLASH_PUNCT_TAIL && b2 == b'/' {
        return prev_tail_absorbed::<F>(bytes, idx + 1).map(|abs| u64::from(!abs));
    }
    Some(u64::from(
        b2 == b' ' || (!is_letter(b2) && !is_digit(b2) && !is_ascii_ws(b2)),
    ))
}

/// Pure-ASCII carries. Requires `scan > 0`, `bytes[scan-1] < 0x80` (and
/// `bytes[scan-2] < 0x80` when present), and `bytes[scan-1]` NOT a
/// tail-class byte (those route through [`prev_tail_absorbed`] first).
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn ascii_carries<F: O200kFlavor>(bytes: &[u8], scan: usize) -> OCarries {
    let b = bytes[scan - 1];
    debug_assert!(!is_tail_byte::<F>(b));
    let bit = |c: bool| u64::from(c);
    let (l, d, w) = (is_letter(b), is_digit(b), is_ascii_ws(b));
    let (c2_os, c2_unresolved) = if scan >= 2 {
        match c2_os_ascii::<F>(bytes, scan - 2) {
            Some(v) => (v, false),
            None => (0, true),
        }
    } else {
        (0, false)
    };
    OCarries {
        force_bad_lead: c2_unresolved,
        pl: bit(l),
        pu: bit(is_upper_ascii(b)),
        pcl: 0,
        ps: bit(b == b' '),
        pwt: bit(w && b != b' '), // \r\n excluded by the debug_assert
        po: bit(!l && !d && !w),
        pws: bit(w),
        pd: bit(d),
        c2_os,
        b2b_in: 0,
        p_abs: false,
    }
}

/// Carries when the byte before the batch is tail-class (`[\r\n/]`):
/// resolves absorbed-tail vs fresh-run via [`prev_tail_absorbed`]. An
/// absorbed tail ended the previous token, so every "P1 is X" carry is
/// zero and only the tail-continuation seed survives.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(never)]
fn tail_carries<F: O200kFlavor>(bytes: &[u8], scan: usize) -> OCarries {
    match prev_tail_absorbed::<F>(bytes, scan) {
        Some(true) => OCarries {
            p_abs: true,
            ..OCarries::default()
        },
        Some(false) => {
            let b = bytes[scan - 1];
            let bit = |c: bool| u64::from(c);
            // A fresh '/' is an ordinary punct byte; \r\n are newlines
            // (ws class, po = 0). c2_os as in ascii_carries when P2 is
            // ASCII; a non-ASCII P2 next to a tail byte is rare — defer.
            if scan >= 2 && bytes[scan - 2] >= 0x80 {
                return OCarries {
                    force_bad_lead: true,
                    ..OCarries::default()
                };
            }
            let c2_os = if scan >= 2 {
                let b2 = bytes[scan - 2];
                bit(b2 == b' ' || (!is_letter(b2) && !is_digit(b2) && !is_ascii_ws(b2)))
            } else {
                0
            };
            OCarries {
                po: bit(b == b'/'),
                pws: bit(b != b'/'),
                c2_os,
                ..OCarries::default()
            }
        }
        None => OCarries {
            force_bad_lead: true,
            ..OCarries::default()
        },
    }
}

/// Classify every unicode char whose lead bit is in `m` for
/// `bytes[scan..scan+64]` with the o200k classifier — the o200k analogue
/// of [`classify_uni_chars`] (NUMBERS = false, LEADS = true), with
/// case-split letter masks and marks deferred via `mk`.
///
/// # Safety
///
/// `scan + 70 <= bytes.len()` (the batch classifiers' lookahead guard).
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
unsafe fn classify_uni_o200k<const DEFER_NUMBERS: bool>(
    bytes: &[u8],
    scan: usize,
    mut m: u64,
) -> OUni {
    let classes = O200kClassTable::get();
    let mut u = OUni::default();
    while m != 0 {
        let i = m.trailing_zeros() as usize;
        m &= m - 1;
        let b = bytes[scan + i];
        if b < 0xE0 {
            // Two-byte UTF-8 dominates western Unicode text, so keep its
            // decode and constant-width masks off the general length ladder.
            if b < 0xC2 {
                u.resid |= 1 << i; // stray continuation byte (invalid UTF-8)
                continue;
            }
            let lead = 1u64 << i;
            let chm = 3u64 << i; // in-batch bytes (excess drops at bit 63)
            // SAFETY: the function's lookahead contract covers i + 1.
            let b1 = unsafe { *bytes.get_unchecked(scan + i + 1) };
            let cp = ((b as u32 & 0x1F) << 6) | (b1 as u32 & 0x3F);
            match classes.class_of(cp) {
                O200kCharClass::Upper => {
                    u.l |= chm;
                    u.u |= chm;
                }
                O200kCharClass::Lower => u.l |= chm,
                O200kCharClass::Caseless => {
                    u.l |= chm;
                    u.cl |= chm;
                }
                O200kCharClass::Mark => {
                    u.o |= chm;
                    u.mk |= chm;
                }
                O200kCharClass::Number => {
                    u.n |= chm;
                    if DEFER_NUMBERS {
                        u.resid |= chm;
                    }
                }
                O200kCharClass::Other => u.o |= chm,
                O200kCharClass::Whitespace => {
                    u.ws |= chm;
                    if i + 2 > 64 {
                        u.resid |= chm;
                    } else {
                        u.w2 |= lead;
                    }
                }
            }
            u.lead2 |= lead;
            u.cont |= chm & !lead;
            m &= !chm;
            continue;
        }
        let l = if b < 0xF0 { 3 } else { 4 };
        let chm = ((1u64 << l) - 1) << i; // in-batch bytes (excess drops)
        let lead = 1u64 << i;
        // SAFETY: scan + 70 <= len (this fn's contract), i <= 63, so
        // scan + i + 4 <= len even for a 4-byte lead at bit 63.
        let (cp, _) = unsafe { decode_cp_inbounds(bytes, scan + i) };
        match classes.class_of(cp) {
            O200kCharClass::Upper => {
                u.l |= chm;
                u.u |= chm;
            }
            O200kCharClass::Lower => u.l |= chm,
            O200kCharClass::Caseless => {
                u.l |= chm;
                u.cl |= chm;
            }
            O200kCharClass::Mark => {
                // Contextual (letter-run joiner AND punct-run member):
                // punct-class for the neighbors' mask algebra, deferred
                // (±4) for everything the context could change.
                u.o |= chm;
                u.mk |= chm;
            }
            O200kCharClass::Number => {
                u.n |= chm;
                if DEFER_NUMBERS {
                    u.resid |= chm;
                }
            }
            O200kCharClass::Other => u.o |= chm,
            O200kCharClass::Whitespace => {
                u.ws |= chm;
                if i + l > 64 || l == 4 {
                    u.resid |= chm; // straddling-out ws stays a bad zone
                } else {
                    u.w3 |= lead;
                }
            }
        }
        if l == 3 {
            u.lead3 |= lead;
        } else {
            u.lead4 |= lead;
        }
        u.cont |= chm & !lead;
        m &= !chm;
    }
    u
}

/// ASCII class masks the o200k algebra needs on top of
/// [`AsciiMasks`]: strict-uppercase letters and slashes.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[derive(Clone, Copy, Default)]
struct OAsciiExtra {
    up: u64,
    sl: u64,
}

/// Slow(er) path for batches with non-ASCII in or just before them — the
/// o200k analogue of `cl100k_family::family_extended_masks`: carries walk
/// back through multi-byte chars with the o200k classifier, unicode chars
/// join the effective class masks, then the shared algebra applies.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[cfg_attr(
    target_arch = "x86_64",
    target_feature(enable = "bmi1,bmi2,lzcnt,popcnt")
)]
#[inline(never)]
fn o200k_extended_masks<F: O200kFlavor>(
    bytes: &[u8],
    scan: usize,
    am: AsciiMasks,
    ax: OAsciiExtra,
) -> (u64, u64) {
    let mut cl = OUni::default();
    let cr = if scan == 0 {
        OCarries::default()
    } else if bytes[scan - 1] < 0x80 && is_tail_byte::<F>(bytes[scan - 1]) {
        tail_carries::<F>(bytes, scan)
    } else if bytes[scan - 1] < 0x80 && (scan < 2 || bytes[scan - 2] < 0x80) {
        ascii_carries::<F>(bytes, scan)
    } else {
        // A multi-byte char within two bytes of the batch start.
        // SAFETY: scan > 0, and the batch guard covers pos + 3 <= len.
        let (c1, j1, e1) = unsafe { char_through_o200k(bytes, scan) };
        let chm = if e1 > scan {
            (1u64 << (e1 - scan)) - 1
        } else {
            0
        };
        cl.cont = chm;
        let (c2v, c2_defer) = if j1 == 0 {
            (0, false)
        } else if F::SLASH_PUNCT_TAIL && bytes[j1 - 1] == b'/' {
            // An absorbed tail slash is a token end, not a punct-run char.
            match prev_tail_absorbed::<F>(bytes, j1) {
                Some(abs) => (u64::from(!abs), false),
                None => (0, true),
            }
        } else {
            // SAFETY: j1 > 0, j1 < scan keeps the decode in the guard.
            let c2c = unsafe { char_through_o200k(bytes, j1) }.0;
            (
                u64::from(
                    bytes[j1 - 1] == b' '
                        || matches!(c2c, O200kCharClass::Other | O200kCharClass::Mark),
                ),
                // A mark P2 makes the two-back test run-contextual.
                c2c == O200kCharClass::Mark,
            )
        };
        let mut c = OCarries::default();
        if e1 > scan {
            c.b2b_in = c2v << (e1 - scan);
        } else {
            c.c2_os = c2v;
        }
        if c2_defer {
            c.force_bad_lead = true;
        }
        c.pd = u64::from(c1 == O200kCharClass::Number);
        match c1 {
            O200kCharClass::Upper => {
                cl.l |= chm;
                cl.u |= chm;
                c.pl = 1;
                c.pu = 1;
            }
            O200kCharClass::Lower => {
                cl.l |= chm;
                c.pl = 1;
            }
            O200kCharClass::Caseless => {
                cl.l |= chm;
                cl.cl |= chm;
                c.pl = 1;
                c.pcl = 1;
            }
            O200kCharClass::Mark => {
                // Contextual: defer the batch front to the scalar path.
                cl.o |= chm;
                cl.mk |= chm | 1; // bit 0 seeds the ±4 smear even when
                // the mark sits entirely before the batch
                c.po = 1;
            }
            O200kCharClass::Number => {
                cl.n |= chm;
                // A digit char straddling INTO the batch: the leading
                // ASCII digit run's `\p{N}{1,3}` phase started before the
                // batch, and the `pd` seed below can't see it (bit 0 is a
                // continuation byte, not an ASCII digit). Defer via resid
                // so the bad<<1 seed catches the run.
                cl.resid |= chm;
            }
            O200kCharClass::Other => {
                cl.o |= chm;
                c.po = 1;
            }
            O200kCharClass::Whitespace => {
                cl.ws |= chm;
                if e1 > scan {
                    cl.resid |= chm;
                }
                let pb = bytes[scan - 1];
                c.ps = u64::from(pb == b' ');
                let nl = pb == b'\r' || pb == b'\n';
                c.pwt = u64::from(pb < 0x80 && pb != b' ' && !nl || pb >= 0x80);
                c.pws = 1;
            }
        }
        c
    };

    let mut uni = if am.hi != 0 {
        // SAFETY: the batch guard is exactly `classify_uni_o200k`'s
        // contract.
        unsafe { classify_uni_o200k::<true>(bytes, scan, am.hi & !cl.cont) }
    } else {
        OUni::default()
    };
    uni.l |= cl.l;
    uni.u |= cl.u;
    uni.cl |= cl.cl;
    uni.n |= cl.n;
    uni.o |= cl.o;
    uni.ws |= cl.ws;
    uni.cont |= cl.cont;
    uni.resid |= cl.resid;
    uni.mk |= cl.mk;

    o200k_algebra::<F>(bytes, scan, am, ax, cr, uni)
}

/// The o200k family's shared u64 boundary algebra over per-byte class
/// masks — `cl100k_family::family_algebra` with the o200k rules: casing
/// boundaries inside letter runs, suffix contractions, `[\r\n/]*` punct
/// tails. `uni` is all-zero on the pure-ASCII path.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn o200k_algebra<F: O200kFlavor>(
    bytes: &[u8],
    scan: usize,
    am: AsciiMasks,
    ax: OAsciiExtra,
    cr: OCarries,
    uni: OUni,
) -> (u64, u64) {
    let OCarries {
        pl,
        pu,
        pcl,
        ps,
        pwt,
        po,
        pws,
        pd,
        c2_os,
        b2b_in,
        p_abs,
        force_bad_lead,
    } = cr;
    let contm = uni.cont;

    // Effective per-byte classes.
    let lb = am.l | uni.l;
    let ub = ax.up | uni.u;
    let clb = uni.cl;
    let sb = am.s;
    let wtb = am.wt | uni.ws;
    let ob = !(am.l | am.d | am.s | am.wt | am.n | am.hi) | uni.o;
    let ws_all = sb | wtb | am.n;

    // --- Absorbed `[\r\n/]*` tails -----------------------------------------
    // Seed: a newline right after a punct byte (a slash after a punct run
    // is already a run member, so tails always begin with a newline), or
    // a tail continuing from before the batch. Smear through [\r\n/].
    let tcls = if F::SLASH_PUNCT_TAIL {
        am.n | ax.sl
    } else {
        am.n
    };
    let abs_seed = (am.n & ((ob << 1) | po)) | (u64::from(p_abs) & tcls);
    let abs_t = if abs_seed == 0 {
        0
    } else {
        smear_up(abs_seed, tcls)
    };
    // Absorbed bytes are no longer punct-run members for any boundary rule.
    let ob_eff = ob & !abs_t;

    // --- Letters -------------------------------------------------------------
    let len1 = !(contm | uni.lead2 | uni.lead3 | uni.lead4);
    let c_test = ((ob_eff | sb) << 1) | po | ps; // bit 0: byte scan-1 in O|S
    let b2back = ((c_test & len1) << 1)
        | ((c_test & uni.lead2) << 2)
        | ((c_test & uni.lead3) << 3)
        | ((c_test & uni.lead4) << 4)
        | c2_os
        | b2b_in;
    let p_l = (lb << 1) | pl;
    let p_u = (ub << 1) | pu;
    let p_cl = (clb << 1) | pcl;
    let p_s = (sb << 1) | ps;
    let p_wt = (wtb << 1) | pwt;
    let p_o = (ob_eff << 1) | po;
    let absorb = p_o & !b2back;
    // Casing boundary: a strict-upper char after a strict-lower one. (For
    // ASCII text this is the whole rule; see the module docs.)
    let p_sl = p_l & !p_u & !p_cl;
    let b_su = ub & !contm & p_sl;
    let b_letters = (lb & !contm & !p_l & !p_s & !p_wt & !absorb) | b_su;

    // --- Digits: `\p{N}{1,3}` or `\p{N}` -------------------------------------
    let b_digits = if F::THREE_DIGIT_NUMBERS && am.d & (am.d >> 1) != 0 {
        digit_run_splits3(am.d)
    } else {
        am.d
    };

    // --- Punct: ` ?[^\s\p{L}\p{N}]+[\r\n/]*` ----------------------------------
    let b_punct = ob_eff & !contm & !p_o & !p_s;

    // --- Bad zones ------------------------------------------------------------
    let resid = uni.resid;
    let mut bad = resid | resid << 1 | resid >> 1;
    // Marks are run-contextual: they, and anything whose boundary rules
    // can see them (up to two chars back — 4 bytes of lookahead for the
    // following leads), go to the scalar path.
    let mk = uni.mk;
    if mk != 0 {
        bad |= mk | mk << 1 | mk << 2 | mk << 3 | mk << 4 | mk >> 1;
    }
    // A strict-upper char after a caseless letter: phase- and
    // lookahead-dependent (see the module docs) — scalar.
    bad |= ub & !contm & ((clb << 1) | pcl);
    if force_bad_lead {
        // Unresolved carries: the leading tail-class run (plus the byte
        // after it) can't be trusted.
        bad |= smear_up(tcls & 1, tcls) << 1 | 0b11;
    }

    // --- Whitespace -----------------------------------------------------------
    let ws_eff = ws_all & !abs_t;

    // Byte-64 lookahead: is the char at the next batch's first byte
    // non-ws? (See cl100k_family for the full reasoning.)
    let nb64 = bytes[scan + 64]; // in bounds: scan + 70 <= len
    let nn64 = if nb64 < 0x80 {
        !is_ascii_ws(nb64)
    } else {
        // SAFETY: the batch guard puts the decode at scan + 64 in bounds.
        bad >> 63 == 0 && unsafe { nn_at_full(bytes, scan + 64) }
    };
    let nn64m = u64::from(nn64).wrapping_neg();

    // An absorbed tail touching the batch end continues iff byte 64 is
    // tail-class; the next batch's `tail_carries` walkback re-derives the
    // context either way, so nothing defers here. A ws run touching the
    // batch end still defers when byte 64 is ws (its last newline may lie
    // beyond this batch).
    let nonws = !ws_eff;
    if ws_eff >> 63 != 0 && !nn64 {
        if nonws == 0 {
            return (0, u64::MAX); // whole batch one ws run
        }
        let h = 63 - nonws.leading_zeros(); // highest non-ws bit (< 63)
        bad |= u64::MAX << (h + 1);
    }

    // A digit run whose `\p{N}{1,3}` phase did not start inside this batch
    // (continuation from before it, or after a bad zone) defers.
    if F::THREE_DIGIT_NUMBERS {
        let seed = (am.d & (bad << 1)) | (am.d & pd);
        if seed != 0 {
            bad |= smear_up(seed, am.d);
        }
    }

    // Base rule (NL-free runs; NL runs are overridden below).
    let ws_leads1 = (am.s | am.wt | am.n) & ws_eff;
    let ws_leads = (ws_leads1 | uni.w2 | uni.w3) & !abs_t;
    let p_ws = (ws_eff << 1) | pws;
    let edge_last = (ws_leads1 & (1 << 63)) | (uni.w2 & (1 << 62)) | (uni.w3 & (1 << 61));
    let split_ok = (ws_leads1 & (nonws >> 1))
        | (uni.w2 & (nonws >> 2))
        | (uni.w3 & (nonws >> 3))
        | (edge_last & nn64m);
    let mut b_ws = ws_leads & (!p_ws | split_ok);

    // Override every run containing a (non-absorbed) newline: one token
    // through the run's last newline, then tail rules.
    let mut runs_n = am.n & ws_eff & !bad;
    while runs_n != 0 {
        let f = runs_n.trailing_zeros();
        let below_gap = nonws & ((1u64 << f) - 1);
        let a = if below_gap == 0 {
            0
        } else {
            64 - below_gap.leading_zeros()
        };
        let e = (nonws & (u64::MAX << f)).trailing_zeros();
        let run_mask = (u64::MAX << a) & !u64::MAX.unbounded_shl(e);
        b_ws &= !run_mask;
        b_ws |= 1u64 << a;
        let q = 63 - (am.n & run_mask).leading_zeros(); // last NL in run
        if (q + 1) < e {
            b_ws |= 1u64 << (q + 1);
            let tail = run_mask & (u64::MAX << (q + 1));
            let tail_leads = ws_leads & tail;
            b_ws |= 1u64 << (63 - tail_leads.leading_zeros());
        }
        runs_n &= !run_mask;
    }

    let mut boundary = b_letters | b_digits | b_punct | b_ws;

    // --- Contractions: suffix `(?i:'s|'t|'re|'ve|'m|'ll|'d)?` ----------------
    // An apostrophe right after a letter-run char merges the suffix into
    // that token and forces a boundary right after it. ('Å¿ is non-ASCII:
    // an apostrophe before any non-ASCII char defers.)
    if F::CONTRACTIONS {
        let mut cand = am.ap & boundary & p_l & !bad;
        let mut last_forced = usize::MAX;
        while cand != 0 {
            let i = cand.trailing_zeros() as usize;
            cand &= cand - 1;
            if i <= 2 {
                // The preceding letter could itself end an earlier
                // contraction that started before the batch — scalar.
                bad |= 0b111u64 << i;
                continue;
            }
            if i >= 61 {
                bad |= u64::MAX << i;
                break;
            }
            if i == last_forced {
                // "x'll'd": the letter before this apostrophe is a
                // consumed suffix's last char; a new (prefix) match
                // starts here instead.
                continue;
            }
            // The letter before this apostrophe may itself be a consumed
            // suffix's last char resolved where last_forced can't see it
            // (a scalar-walked zone like 'Å¿, or a fixup before the
            // batch): locally ambiguous, defer.
            let p = scan + i;
            let prev_suffix_possible = (bytes[p - 2] == b'\''
                && matches!(bytes[p - 1] | 0x20, b's' | b'd' | b'm' | b't'))
                || (p >= 3
                    && bytes[p - 3] == b'\''
                    && (matches!(
                        (bytes[p - 2] | 0x20, bytes[p - 1] | 0x20),
                        (b'l', b'l') | (b'v', b'e') | (b'r', b'e')
                    ) || (bytes[p - 2] == 0xC5 && bytes[p - 1] == 0xBF)));
            if prev_suffix_possible {
                bad |= 0b111u64 << i;
                continue;
            }
            let b1 = bytes[scan + i + 1];
            if b1 >= 0x80 {
                bad |= 0b111u64 << i;
                continue;
            }
            let k = match b1 | 0x20 {
                b's' | b'd' | b'm' | b't' => 2,
                b'l' if bytes[scan + i + 2] | 0x20 == b'l' => 3,
                b'v' if bytes[scan + i + 2] | 0x20 == b'e' => 3,
                b'r' if bytes[scan + i + 2] | 0x20 == b'e' => 3,
                _ => 0,
            };
            if k != 0 {
                boundary &= !(1u64 << i);
                boundary &= !(((1u64 << (k - 1)) - 1) << (i + 1));
                boundary |= 1u64 << (i + k);
                last_forced = i + k;
            }
        }
    }

    (boundary & !bad, bad)
}

// -----------------------------------------------------------------------
// Batch classifiers (per-arch front-ends)
// -----------------------------------------------------------------------

/// Carries for a batch known to have only ASCII in and just before it:
/// tail-class prev bytes route through the walkback, everything else
/// through the branchless ASCII carries.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
#[inline(always)]
fn ascii_batch_carries<F: O200kFlavor>(bytes: &[u8], scan: usize) -> OCarries {
    if scan == 0 {
        OCarries::default()
    } else if is_tail_byte::<F>(bytes[scan - 1]) {
        tail_carries::<F>(bytes, scan)
    } else {
        ascii_carries::<F>(bytes, scan)
    }
}

/// `(usable, bad)` for `bytes[scan..scan+64]` under the o200k-family
/// rules — same contract as the cl100k family's `batch_masks`.
///
/// NEON front-end: classifies the ASCII classes (letter, upper, digit,
/// space, whitespace, newline) with movemasks; apostrophe and slash sit
/// behind horizontal any-tests. Batches with non-ASCII in or just before
/// them take [`o200k_extended_masks`].
#[cfg(target_arch = "aarch64")]
#[inline]
fn batch_masks<F: O200kFlavor>(bytes: &[u8], scan: usize) -> (u64, u64) {
    use std::arch::aarch64::*;
    debug_assert!(scan + 70 <= bytes.len());
    unsafe {
        let p = bytes.as_ptr().add(scan);
        let zero = vdupq_n_u8(0);
        let mut lv = [zero; 4];
        let mut casev = [zero; 4];
        let mut dv = [zero; 4];
        let mut sv = [zero; 4];
        let mut wsv = [zero; 4];
        let mut nv = [zero; 4];
        let mut apv = [zero; 4];
        let mut hi_any = zero;
        let newline_table =
            vld1q_u8([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0, 0, 0xff, 0, 0].as_ptr());
        for i in 0..4 {
            let v = vld1q_u8(p.add(16 * i));
            hi_any = vorrq_u8(hi_any, v);
            let lowered = vorrq_u8(v, vdupq_n_u8(0x20));
            lv[i] = vcleq_u8(vsubq_u8(lowered, vdupq_n_u8(b'a')), vdupq_n_u8(25));
            casev[i] = vtstq_u8(v, vdupq_n_u8(0x20));
            dv[i] = vcleq_u8(vsubq_u8(v, vdupq_n_u8(b'0')), vdupq_n_u8(9));
            sv[i] = vceqq_u8(v, vdupq_n_u8(b' '));
            wsv[i] = vorrq_u8(sv[i], vcleq_u8(vsubq_u8(v, vdupq_n_u8(9)), vdupq_n_u8(4)));
            // `tbl` zeroes indices above 15, so only CR and LF select set lanes.
            nv[i] = vqtbl1q_u8(newline_table, v);
            apv[i] = vceqq_u8(v, vdupq_n_u8(b'\''));
        }
        let l64 = movemask64(lv[0], lv[1], lv[2], lv[3]);
        let bit5 = movemask64(casev[0], casev[1], casev[2], casev[3]);
        // ASCII lowercase letters set bit 5; `l64` excludes every other byte.
        let u64_ = l64 & !bit5;
        let d64 = movemask64(dv[0], dv[1], dv[2], dv[3]);
        let wsa = movemask64(wsv[0], wsv[1], wsv[2], wsv[3]);
        // Space is the only byte in the ASCII whitespace set with bit 5 set.
        let s64 = wsa & bit5;
        let n64 = movemask64(nv[0], nv[1], nv[2], nv[3]);

        // Apostrophes only matter for the contraction fixup.
        let ap64 = if F::CONTRACTIONS {
            let ap_any = vorrq_u8(vorrq_u8(apv[0], apv[1]), vorrq_u8(apv[2], apv[3]));
            if vmaxvq_u8(ap_any) != 0 {
                movemask64(apv[0], apv[1], apv[2], apv[3])
            } else {
                0
            }
        } else {
            0
        };
        // Slashes affect only absorbed newline tails. Without a newline or
        // a tail-class carry, this block cannot start or continue one.
        let sl64 = if F::SLASH_PUNCT_TAIL
            && (n64 != 0 || (scan != 0 && is_tail_byte::<F>(bytes[scan - 1])))
        {
            let s0 = vceqq_u8(vld1q_u8(p), vdupq_n_u8(b'/'));
            let s1 = vceqq_u8(vld1q_u8(p.add(16)), vdupq_n_u8(b'/'));
            let s2 = vceqq_u8(vld1q_u8(p.add(32)), vdupq_n_u8(b'/'));
            let s3 = vceqq_u8(vld1q_u8(p.add(48)), vdupq_n_u8(b'/'));
            movemask64(s0, s1, s2, s3)
        } else {
            0
        };

        let am = AsciiMasks {
            l: l64,
            d: d64,
            s: s64,
            wt: wsa & !s64 & !n64,
            n: n64,
            hi: 0,
            ap: ap64,
        };
        let ax = OAsciiExtra { up: u64_, sl: sl64 };

        if vmaxvq_u8(hi_any) >= 0x80
            || (scan >= 1 && bytes[scan - 1] >= 0x80)
            || (scan >= 2 && bytes[scan - 2] >= 0x80)
        {
            // Kimi's Han classes still route through its exact scalar scanner.
            if !F::SIMD_UNICODE {
                return (0, u64::MAX);
            }
            let h0 = vcltzq_s8(vreinterpretq_s8_u8(vld1q_u8(p)));
            let h1 = vcltzq_s8(vreinterpretq_s8_u8(vld1q_u8(p.add(16))));
            let h2 = vcltzq_s8(vreinterpretq_s8_u8(vld1q_u8(p.add(32))));
            let h3 = vcltzq_s8(vreinterpretq_s8_u8(vld1q_u8(p.add(48))));
            let mut am = am;
            am.hi = movemask64(h0, h1, h2, h3);
            return o200k_extended_masks::<F>(bytes, scan, am, ax);
        }

        let cr = ascii_batch_carries::<F>(bytes, scan);
        o200k_algebra::<F>(bytes, scan, am, ax, cr, OUni::default())
    }
}

/// x86-64 front-end: same contract as the NEON `batch_masks` above,
/// dispatching on the runtime-detected SIMD tier (AVX-512 or AVX2).
#[cfg(target_arch = "x86_64")]
#[inline(always)]
fn batch_masks<F: O200kFlavor>(bytes: &[u8], scan: usize) -> (u64, u64) {
    debug_assert!(simd_scanner_available());
    if avx512_scanner_available() {
        // SAFETY: runtime AVX-512 detection right above.
        unsafe { batch_masks_avx512::<F>(bytes, scan) }
    } else {
        // SAFETY: MaskState enables the mask-scanner path only after
        // runtime detection; without AVX-512 that detection was AVX2's.
        unsafe { batch_masks_avx2::<F>(bytes, scan) }
    }
}

/// The strict-uppercase and slash masks for `bytes[scan..scan+64]`,
/// AVX-512 tier.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vl,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
fn ascii_extra_avx512(bytes: &[u8], scan: usize) -> OAsciiExtra {
    use std::arch::x86_64::*;
    unsafe {
        let v = _mm512_loadu_si512(bytes.as_ptr().add(scan) as *const _);
        let up = _mm512_cmple_epu8_mask(
            _mm512_sub_epi8(v, _mm512_set1_epi8(b'A' as i8)),
            _mm512_set1_epi8(25),
        );
        let sl = _mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8(b'/' as i8));
        OAsciiExtra { up, sl }
    }
}

/// The strict-uppercase and slash masks for `bytes[scan..scan+64]`,
/// AVX2 tier. `#[inline(never)]` for the same vector-domain reason as
/// [`ascii_masks_avx2`].
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2,bmi1,bmi2,lzcnt,popcnt")]
#[inline(never)]
fn ascii_extra_avx2(bytes: &[u8], scan: usize) -> OAsciiExtra {
    use std::arch::x86_64::*;
    unsafe {
        let le =
            |v: __m256i, lim: __m256i| -> __m256i { _mm256_cmpeq_epi8(_mm256_min_epu8(v, lim), v) };
        let mm = |m0: __m256i, m1: __m256i| -> u64 {
            (_mm256_movemask_epi8(m0) as u32 as u64)
                | ((_mm256_movemask_epi8(m1) as u32 as u64) << 32)
        };
        let p = bytes.as_ptr().add(scan);
        let v0 = _mm256_loadu_si256(p as *const _);
        let v1 = _mm256_loadu_si256(p.add(32) as *const _);
        let ca = _mm256_set1_epi8(b'A' as i8);
        let c25 = _mm256_set1_epi8(25);
        let up = mm(
            le(_mm256_sub_epi8(v0, ca), c25),
            le(_mm256_sub_epi8(v1, ca), c25),
        );
        let slc = _mm256_set1_epi8(b'/' as i8);
        let sl = mm(_mm256_cmpeq_epi8(v0, slc), _mm256_cmpeq_epi8(v1, slc));
        OAsciiExtra { up, sl }
    }
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx512f,avx512bw,avx512vl,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
fn batch_masks_avx512<F: O200kFlavor>(bytes: &[u8], scan: usize) -> (u64, u64) {
    debug_assert!(scan + 70 <= bytes.len());
    let am = ascii_masks_avx512(bytes, scan);
    let ax = ascii_extra_avx512(bytes, scan);
    if am.hi != 0
        || (scan >= 1 && bytes[scan - 1] >= 0x80)
        || (scan >= 2 && bytes[scan - 2] >= 0x80)
    {
        if !F::SIMD_UNICODE {
            return (0, u64::MAX);
        }
        return o200k_extended_masks::<F>(bytes, scan, am, ax);
    }
    let cr = ascii_batch_carries::<F>(bytes, scan);
    o200k_algebra::<F>(bytes, scan, am, ax, cr, OUni::default())
}

#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2,bmi1,bmi2,lzcnt,popcnt")]
#[inline]
fn batch_masks_avx2<F: O200kFlavor>(bytes: &[u8], scan: usize) -> (u64, u64) {
    debug_assert!(scan + 70 <= bytes.len());
    let am = ascii_masks_avx2(bytes, scan);
    let ax = ascii_extra_avx2(bytes, scan);
    if am.hi != 0
        || (scan >= 1 && bytes[scan - 1] >= 0x80)
        || (scan >= 2 && bytes[scan - 2] >= 0x80)
    {
        if !F::SIMD_UNICODE {
            return (0, u64::MAX);
        }
        return o200k_extended_masks::<F>(bytes, scan, am, ax);
    }
    let cr = ascii_batch_carries::<F>(bytes, scan);
    o200k_algebra::<F>(bytes, scan, am, ax, cr, OUni::default())
}

/// GPT-2's case-sensitive R50K grammar.
struct R50kScheme;

impl MaskScheme for R50kScheme {
    #[inline(always)]
    fn advance(bytes: &[u8], pos: usize) -> usize {
        let input = unsafe { std::str::from_utf8_unchecked(bytes) };
        super::advance_gpt2(input, pos, false)
    }

    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
        r50k_batch_masks(bytes, scan)
    }
}

/// Qwen2/Qwen3 grammar with one-character number tokens.
struct QwenScheme;

impl MaskScheme for QwenScheme {
    #[inline(always)]
    fn advance(bytes: &[u8], pos: usize) -> usize {
        let input = unsafe { std::str::from_utf8_unchecked(bytes) };
        super::advance_qwen(input, pos)
    }

    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
        qwen_batch_masks::<false, false>(bytes, scan)
    }
}

/// Qwen3.5 grammar, where Unicode marks join word runs.
struct QwenMarkScheme;

impl MaskScheme for QwenMarkScheme {
    #[inline(always)]
    fn advance(bytes: &[u8], pos: usize) -> usize {
        let input = unsafe { std::str::from_utf8_unchecked(bytes) };
        super::scan_qwen::<true, 1>(input, pos).expect("Qwen3.5 token boundary")
    }

    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
        qwen_batch_masks::<true, false>(bytes, scan)
    }
}

/// Phi/GLM grammar with three-character number groups.
struct PhiGlmScheme;

impl MaskScheme for PhiGlmScheme {
    #[inline(always)]
    fn advance(bytes: &[u8], pos: usize) -> usize {
        let input = unsafe { std::str::from_utf8_unchecked(bytes) };
        super::scan_qwen::<false, 3>(input, pos).expect("Phi/GLM token boundary")
    }

    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
        qwen_batch_masks::<false, true>(bytes, scan)
    }
}

/// o200k with contractions and three-character number groups.
struct ContractionScheme;

impl O200kFlavor for ContractionScheme {
    const CONTRACTIONS: bool = true;
    const THREE_DIGIT_NUMBERS: bool = true;
    const SLASH_PUNCT_TAIL: bool = true;
    const SIMD_UNICODE: bool = true;
}

impl MaskScheme for ContractionScheme {
    #[inline(always)]
    fn advance(bytes: &[u8], pos: usize) -> usize {
        let input = unsafe { std::str::from_utf8_unchecked(bytes) };
        super::scan_llama::<true, 3>(input, pos).expect("o200k token boundary")
    }

    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
        batch_masks::<Self>(bytes, scan)
    }
}

/// Kimi's o200k variant, with exact scalar handling for its Han and slash differences.
struct KimiScheme;

impl O200kFlavor for KimiScheme {
    const CONTRACTIONS: bool = true;
    const THREE_DIGIT_NUMBERS: bool = true;
    const SLASH_PUNCT_TAIL: bool = false;
    const SIMD_UNICODE: bool = false;
}

impl MaskScheme for KimiScheme {
    /// Return the next exact Kimi boundary for scalar gaps and buffer tails.
    #[inline(always)]
    fn advance(bytes: &[u8], pos: usize) -> usize {
        if let Some(end) = scan_kimi_han_run(bytes, pos) {
            return end;
        }
        if let Some(end) = scan_kimi_punctuation_run(bytes, pos) {
            return end;
        }
        let input = unsafe { std::str::from_utf8_unchecked(bytes) };
        super::scan_kimi(input, pos).expect("Kimi token boundary")
    }

    /// Reuse o200k masks only where Kimi has identical ASCII semantics.
    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
        batch_masks::<Self>(bytes, scan)
    }
}

/// o200k-family grammar without contractions and with one-character numbers.
struct PlainScheme;

impl O200kFlavor for PlainScheme {
    const CONTRACTIONS: bool = false;
    const THREE_DIGIT_NUMBERS: bool = false;
    const SLASH_PUNCT_TAIL: bool = true;
    const SIMD_UNICODE: bool = true;
}

impl MaskScheme for PlainScheme {
    #[inline(always)]
    fn advance(bytes: &[u8], pos: usize) -> usize {
        let input = unsafe { std::str::from_utf8_unchecked(bytes) };
        super::scan_llama::<false, 1>(input, pos).expect("o200k token boundary")
    }

    #[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
    #[inline(always)]
    fn batch_masks(bytes: &[u8], scan: usize) -> (u64, u64) {
        batch_masks::<Self>(bytes, scan)
    }
}

/// Visit exact R50K pieces through a concrete fused sink.
#[inline(never)]
pub(super) fn for_each_r50k_match_into<S: FusedPieceSink>(input: &str, sink: &mut S) {
    walk::<R50kScheme, _>(input, sink);
}

/// Visit exact Kimi pieces through the concrete fused sink.
#[inline(never)]
pub(super) fn for_each_kimi_match_into<S: FusedPieceSink>(input: &str, sink: &mut S) {
    walk::<KimiScheme, _>(input, sink);
}

/// Visit exact Qwen-family pieces through a concrete fused sink.
#[inline(never)]
pub(super) fn for_each_qwen_match_into<
    const WORD_MARKS: bool,
    const DIGITS: usize,
    S: FusedPieceSink,
>(
    input: &str,
    sink: &mut S,
) {
    if WORD_MARKS {
        debug_assert_eq!(DIGITS, 1);
        walk::<QwenMarkScheme, _>(input, sink);
    } else if DIGITS == 3 {
        walk::<PhiGlmScheme, _>(input, sink);
    } else {
        debug_assert_eq!(DIGITS, 1);
        walk::<QwenScheme, _>(input, sink);
    }
}

/// Visit exact o200k-family pieces through a concrete fused sink.
#[inline(never)]
pub(super) fn for_each_match_into<
    const CONTRACTIONS: bool,
    const DIGITS: usize,
    S: FusedPieceSink,
>(
    input: &str,
    sink: &mut S,
) {
    if CONTRACTIONS {
        debug_assert_eq!(DIGITS, 3);
        walk::<ContractionScheme, _>(input, sink);
    } else {
        debug_assert_eq!(DIGITS, 1);
        walk::<PlainScheme, _>(input, sink);
    }
}

/// Walk one selected mask scheme from the first byte through the scalar tail.
#[inline(always)]
fn walk<S: MaskScheme, E: FusedPieceSink>(input: &str, sink: &mut E) {
    let mut state = MaskState::new(0);
    state.for_each_span::<S>(input, sink);
}