Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
# --------------------------------------------------------------------------
# Copyright 2020 The HuggingFace Inc. team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation.  All rights reserved.
# Licensed under the MIT License.  See License.txt in the project root for
# license information.
# -------------------------------------------------------------------------
import math
import os
import platform
import random
import sys
import tempfile
import unittest
from unittest.mock import patch
 
import numpy
import torch
from einops import rearrange, repeat
from onnx import TensorProto, helper
from packaging import version
from parameterized import parameterized
 
from onnxruntime import (
    GraphOptimizationLevel,
    InferenceSession,
    OrtValue,
    SessionOptions,
    get_available_providers,
    get_ep_devices,
    register_execution_provider_library,
)
 
_webgpu_plugin_path = os.environ.get("ORT_WEBGPU_PLUGIN_PATH")
if _webgpu_plugin_path and "WebGpuExecutionProvider" not in get_available_providers():
    register_execution_provider_library("webgpu_test", _webgpu_plugin_path)
 
torch.manual_seed(0)
 
pipeline_mode = True  # Reduces number of tests so pipeline doesn't time out
 
# Element type of the paged KV cache, keyed by Config.kv_cache_type.
KV_CACHE_TENSOR_PROTO = {
    "float16": TensorProto.FLOAT16,
    "int8": TensorProto.INT8,
    "fp8": TensorProto.FLOAT8E4M3FN,
}
 
# Largest magnitude representable by each quantized cache type.
KV_CACHE_QMAX = {"int8": 127.0, "fp8": 448.0}
 
 
# EP -> (torch_device_when_cuda_available, ort_iobinding_device).
# The torch device is where reference tensors live. WebGPU has no torch backend,
# so we still allocate reference tensors on CUDA when it's available (faster and
# matches CUDA fp16 semantics), else on CPU. The ORT device is the device string
# passed to OrtValue / IO-binding.
_EP_TO_ORT_DEVICE = {
    "CUDAExecutionProvider": "cuda",
    "WebGpuExecutionProvider": "webgpu",
}
 
 
class Config:
    batch_size = 0
    sequence_length = 0
    total_sequence_length = 0
    num_heads = 0
    kv_num_heads = 0
    head_size = 0
    paged_kv_block_size = 0
    local = False
    rotary = False
    rotary_interleaved = False
    packed = False
    softcap = 0.0
    ep = "CUDAExecutionProvider"
    # Optional features layered on top of the original schema. They default to off so that every
    # pre-existing parameterized test keeps its generated name and behavior.
    use_slot_mapping = False
    use_head_sink = False
    use_qk_norm = False
    qk_norm_epsilon = 1e-6
    # Quantized paged KV cache. "float16" keeps the cache unquantized; "int8" and "fp8" store the
    # cache in the corresponding narrow type and require a matching non-"NONE" quant type.
    kv_cache_type = "float16"
    k_quant_type = "NONE"
    v_quant_type = "NONE"
    # "" means the cache tensor's own element type is the logical element type. Sub-byte names
    # ("int4", "float4e2m1") describe a uint8 packed cache and are not supported yet. Every legal
    # value is signed: quantization is symmetric with no zero point, so "uint4"/"uint8" are invalid.
    k_cache_dtype = ""
    v_cache_dtype = ""
 
    def __init__(
        self,
        batch_size,
        sequence_length,
        total_sequence_length,
        num_heads,
        kv_num_heads,
        head_size,
        paged_kv_block_size,
        local,
        rotary,
        rotary_interleaved,
        packed,
        softcap,
        ep="CUDAExecutionProvider",
    ):
        self.batch_size = batch_size
        self.sequence_length = sequence_length
        self.total_sequence_length = total_sequence_length
        self.num_heads = num_heads
        self.kv_num_heads = kv_num_heads
        self.head_size = head_size
        self.paged_kv_block_size = paged_kv_block_size
        self.local = local
        self.rotary = rotary
        self.rotary_interleaved = rotary_interleaved
        self.packed = packed
        self.softcap = softcap
        self.ep = ep
 
    @property
    def torch_device(self) -> str:
        """Device string for torch tensor allocation (inputs + reference).
 
        For CUDA EP: always "cuda" (must match the EP device).
        For other EPs (e.g., WebGPU): prefer CUDA if torch has it (faster,
        matches CUDA fp16 semantics); otherwise CPU. The reference math never
        touches the ORT session, so torch device does not need to equal the EP
        device.
        """
        if self.ep == "CUDAExecutionProvider":
            return "cuda"
        return "cuda" if torch.cuda.is_available() else "cpu"
 
    @property
    def ort_device(self) -> str:
        """Device string for OrtValue / IO-binding (must match the EP device)."""
        try:
            return _EP_TO_ORT_DEVICE[self.ep]
        except KeyError as exc:
            raise ValueError(f"Unknown EP for PagedAttention parity tests: {self.ep!r}") from exc
 
    def __repr__(self):
        short_ep = self.ep[: -len("ExecutionProvider")].lower()
        return (
            f"Config(batch_size={self.batch_size}, sequence_length={self.sequence_length}, "
            f"total_sequence_length={self.total_sequence_length}, num_heads={self.num_heads}, "
            f"kv_num_heads={self.kv_num_heads}, head_size={self.head_size}, "
            f"paged_kv_block_size={self.paged_kv_block_size} rotary={self.rotary}, "
            f"rotary_interleaved={self.rotary_interleaved}, packed={self.packed}, softcap={self.softcap}, "
            f"ep={short_ep})"
        )
 
 
def kv_scale_shape(config, quant_type):
    """Shape of the k_scale / v_scale input for a given quantization granularity."""
    if quant_type == "PER_TENSOR":
        return [1]
    if quant_type == "PER_CHANNEL":
        return [config.kv_num_heads, 1, config.head_size]
    raise ValueError(f"Unsupported quant_type: {quant_type}")
 
 
def compute_kv_scale(tensors, quant_type, kv_cache_type, kv_num_heads, head_size):
    """Symmetric (zero-point-free) scale for the paged KV cache.
 
    'tensors' are every tensor that will end up in the cache -- the pre-existing pages *and* the new
    tokens the kernel is about to write -- so that the chosen scale never clips and the reference can
    reproduce the kernel bit-for-bit. Each tensor's two trailing dimensions are (kv_num_heads,
    head_size), which is exactly the PER_CHANNEL scale layout.
    """
    qmax = KV_CACHE_QMAX[kv_cache_type]
    if quant_type == "PER_TENSOR":
        amax = max(float(t.abs().max().item()) for t in tensors)
        return torch.tensor([max(amax, 1e-6) / qmax], dtype=torch.float32, device="cuda")
    amax = None
    for t in tensors:
        per_channel = t.reshape(-1, kv_num_heads, head_size).abs().amax(dim=0)
        amax = per_channel if amax is None else torch.maximum(amax, per_channel)
    scale = torch.clamp(amax.to(torch.float32), min=1e-6) / qmax
    return scale.reshape(kv_num_heads, 1, head_size)
 
 
def broadcast_kv_scale(scale, quant_type, kv_num_heads, head_size):
    """View the scale so that it broadcasts against any tensor shaped (..., kv_num_heads, head_size)."""
    if quant_type == "PER_TENSOR":
        return scale
    return scale.reshape(1, 1, kv_num_heads, head_size)
 
 
def quantize_kv(tensor_float, scale, kv_cache_type):
    """Mirror of QuantizeToCache in paged_attention_impl.cu.
 
    The kernel multiplies by the reciprocal of the scale rather than dividing, so the reference does
    the same: with round-to-nearest-even the two differ by one LSB often enough to make an exact
    comparison of the updated cache flaky otherwise.
    """
    scaled = tensor_float.to(torch.float32) * torch.reciprocal(scale)
    if kv_cache_type == "fp8":
        return torch.clamp(scaled, -KV_CACHE_QMAX["fp8"], KV_CACHE_QMAX["fp8"]).to(torch.float8_e4m3fn)
    return torch.clamp(torch.round(scaled), -128.0, 127.0).to(torch.int8)
 
 
def dequantize_kv(quantized, scale):
    """Mirror of DequantizeFromCache in paged_attention_impl.cu."""
    return (quantized.to(torch.float32) * scale).to(torch.float16)
 
 
def quantize_dequantize_kv(tensor_float, scale, kv_cache_type):
    return dequantize_kv(quantize_kv(tensor_float, scale, kv_cache_type), scale)
 
 
def create_paged_attention_graph(
    config,
    num_tokens,
    num_blocks,
    max_blocks_per_sequence,
    local_window_size=-1,
):
    cache_proto_type = KV_CACHE_TENSOR_PROTO[config.kv_cache_type]
    # The scale inputs and the quantization attributes are emitted independently of the cache dtype
    # so that invalid combinations (quantized cache without a quant type, and vice versa) can be
    # built and their rejection tested.
    has_k_scale = config.k_quant_type != "NONE"
    has_v_scale = config.v_quant_type != "NONE"
    # Optional host-side [max_query_len_bound, max_kv_len_bound, optional max_kv_len_lower_bound].
    # When present the kernel can skip the device readback of the cumulative length arrays, so
    # results must be identical either way.
    has_attention_metadata = getattr(config, "use_attention_metadata", False)
    quant_attrs = (
        {
            "k_quant_type": config.k_quant_type,
            "v_quant_type": config.v_quant_type,
            "k_cache_dtype": config.k_cache_dtype,
            "v_cache_dtype": config.v_cache_dtype,
        }
        if (has_k_scale or has_v_scale or config.kv_cache_type != "float16")
        else {}
    )
    optional_inputs = [
        "slot_mapping" if config.use_slot_mapping else "",
        "head_sink" if config.use_head_sink else "",
        "q_norm_weight" if config.use_qk_norm else "",
        "k_norm_weight" if config.use_qk_norm else "",
        "k_scale" if has_k_scale else "",
        "v_scale" if has_v_scale else "",
        "attention_metadata" if has_attention_metadata else "",
    ]
    last_optional_idx = -1
    for i, name in enumerate(optional_inputs):
        if name:
            last_optional_idx = i
 
    # Keep the node compact when none of the post-v1 optional inputs are used.
    # This allows the baseline WebGPU path to run on runtimes that still expose
    # the older 10-input schema while remaining compatible with the expanded
    # schema when newer optional inputs are exercised.
    node_inputs = [
        "query",
        "key" if not config.packed else "",
        "value" if not config.packed else "",
        "key_cache",
        "value_cache",
        "cumulative_sequence_length",
        "past_seqlens",
        "block_table",
        "cos_cache" if config.rotary else "",
        "sin_cache" if config.rotary else "",
    ]
    if last_optional_idx >= 0:
        node_inputs.extend(optional_inputs[: last_optional_idx + 1])
 
    node_attrs = {
        "num_heads": config.num_heads,
        "kv_num_heads": config.kv_num_heads,
        "local_window_size": local_window_size,
        "do_rotary": config.rotary,
        "rotary_interleaved": config.rotary_interleaved,
        "softcap": config.softcap,
        "domain": "com.microsoft",
    }
    # Keep baseline graphs compatible with older PagedAttention schema builds.
    # qk_norm_epsilon is only needed when QK-Norm is exercised.
    if config.use_qk_norm:
        node_attrs["qk_norm_epsilon"] = config.qk_norm_epsilon
    if not getattr(config, "is_causal", True):
        node_attrs["is_causal"] = 0
 
    nodes = [
        helper.make_node(
            "PagedAttention",
            node_inputs,
            ["output", "key_cache_out", "value_cache_out"],
            "PagedAttention_0",
            **node_attrs,
            **quant_attrs,
        ),
    ]
 
    graph_input = [
        helper.make_tensor_value_info(
            "query",
            TensorProto.FLOAT16,
            [
                num_tokens,
                (config.num_heads * config.head_size)
                if not config.packed
                else (config.num_heads * config.head_size + 2 * config.kv_num_heads * config.head_size),
            ],
        ),
        helper.make_tensor_value_info(
            "key_cache",
            cache_proto_type,
            [
                num_blocks,
                config.paged_kv_block_size,
                config.kv_num_heads,
                config.head_size,
            ],
        ),
        helper.make_tensor_value_info(
            "value_cache",
            cache_proto_type,
            [
                num_blocks,
                config.paged_kv_block_size,
                config.kv_num_heads,
                config.head_size,
            ],
        ),
        helper.make_tensor_value_info(
            "cumulative_sequence_length",
            TensorProto.INT32,
            [config.batch_size + 1],
        ),
        helper.make_tensor_value_info(
            "past_seqlens",
            TensorProto.INT32,
            [config.batch_size],
        ),
        helper.make_tensor_value_info(
            "block_table",
            TensorProto.INT32,
            [config.batch_size, max_blocks_per_sequence],
        ),
    ]
    if not config.packed:
        graph_input += [
            helper.make_tensor_value_info(
                "key",
                TensorProto.FLOAT16,
                [
                    num_tokens,
                    config.kv_num_heads * config.head_size,
                ],
            ),
            helper.make_tensor_value_info(
                "value",
                TensorProto.FLOAT16,
                [
                    num_tokens,
                    config.kv_num_heads * config.head_size,
                ],
            ),
        ]
    if config.rotary:
        graph_input += [
            helper.make_tensor_value_info(
                "cos_cache",
                TensorProto.FLOAT16,
                [
                    config.total_sequence_length,
                    (math.floor(config.head_size / 16) * 16) // 2,
                ],
            ),
            helper.make_tensor_value_info(
                "sin_cache",
                TensorProto.FLOAT16,
                [
                    config.total_sequence_length,
                    (math.floor(config.head_size / 16) * 16) // 2,
                ],
            ),
        ]
    if config.use_slot_mapping:
        graph_input += [
            helper.make_tensor_value_info("slot_mapping", TensorProto.INT32, [num_tokens]),
        ]
    if config.use_head_sink:
        graph_input += [
            helper.make_tensor_value_info("head_sink", TensorProto.FLOAT16, [config.num_heads]),
        ]
    if config.use_qk_norm:
        graph_input += [
            helper.make_tensor_value_info("q_norm_weight", TensorProto.FLOAT16, [config.head_size]),
            helper.make_tensor_value_info("k_norm_weight", TensorProto.FLOAT16, [config.head_size]),
        ]
    if has_k_scale:
        graph_input += [
            helper.make_tensor_value_info("k_scale", TensorProto.FLOAT, kv_scale_shape(config, config.k_quant_type)),
        ]
    if has_v_scale:
        graph_input += [
            helper.make_tensor_value_info("v_scale", TensorProto.FLOAT, kv_scale_shape(config, config.v_quant_type)),
        ]
    if has_attention_metadata:
        graph_input += [
            helper.make_tensor_value_info(
                "attention_metadata",
                TensorProto.INT32,
                getattr(config, "attention_metadata_shape", [2]),
            ),
        ]
 
    graph_output = [
        helper.make_tensor_value_info(
            "output",
            TensorProto.FLOAT16,
            [num_tokens, config.num_heads * config.head_size],
        ),
        helper.make_tensor_value_info(
            "key_cache_out",
            cache_proto_type,
            [
                num_blocks,
                config.paged_kv_block_size,
                config.kv_num_heads,
                config.head_size,
            ],
        ),
        helper.make_tensor_value_info(
            "value_cache_out",
            cache_proto_type,
            [
                num_blocks,
                config.paged_kv_block_size,
                config.kv_num_heads,
                config.head_size,
            ],
        ),
    ]
 
    graph = helper.make_graph(
        nodes,
        "PagedAttention_Graph",
        graph_input,
        graph_output,
    )
 
    # Pin ai.onnx to opset 22. helper.make_model() otherwise stamps the
    # installed onnx package's newest opset, which may exceed the runtime's
    # kMaxSupportedOpset (e.g. onnx 1.22 stamps opset 27 while ORT tops out
    # at 26 today) and causes InferenceSession creation to fail.
    model = helper.make_model(
        graph,
        opset_imports=[
            helper.make_opsetid("", 22),
            helper.make_opsetid("com.microsoft", 1),
        ],
    )
    return model.SerializeToString()
 
 
def rotary_options_for_current_os():
    # Reference implementation of rotary uses triton, which is not available in Windows.
    # So we only test rotary in Linux right now.
    return [(False, False)] if platform.system() != "Linux" else [(True, False), (True, True), (False, False)]
 
 
def create_webgpu_session(onnx_model_str, sess_options):
    sess_options.graph_optimization_level = GraphOptimizationLevel.ORT_DISABLE_ALL
    webgpu_devices = [device for device in get_ep_devices() if device.ep_name == "WebGpuExecutionProvider"]
    if not webgpu_devices:
        raise RuntimeError("No WebGPU EP device found.")
    sess_options.add_provider_for_devices([webgpu_devices[0]], {})
    return InferenceSession(onnx_model_str, sess_options)
 
 
def paged_attention_func(
    config,
    query,
    key,
    value,
    key_cache,
    value_cache,
    cumulative_sequence_length,
    past_seqlens,
    block_table,
    cos=None,
    sin=None,
    window_size=-1,
    sdpa_kernel=0,
    slot_mapping=None,
    head_sink=None,
    q_norm_weight=None,
    k_norm_weight=None,
    k_scale=None,
    v_scale=None,
):
    num_tokens = cumulative_sequence_length[-1].item()
    num_blocks = key_cache.shape[0]
    max_blocks_per_sequence = block_table.shape[1]
    quantized = config.kv_cache_type != "float16"
    onnx_model_str = create_paged_attention_graph(
        config,
        num_tokens,
        num_blocks,
        max_blocks_per_sequence,
        local_window_size=window_size,
    )
    ort_inputs = {
        "query": query.detach().cpu().numpy(),
        "cumulative_sequence_length": cumulative_sequence_length.detach().cpu().numpy(),
        "past_seqlens": past_seqlens.detach().cpu().numpy(),
        "block_table": block_table.detach().cpu().numpy(),
    }
    key_cache_np = key_cache.detach().cpu().numpy()
    value_cache_np = value_cache.detach().cpu().numpy()
 
    if getattr(config, "use_attention_metadata", False):
        override = getattr(config, "attention_metadata_override", None)
        if override is not None:
            ort_inputs["attention_metadata"] = override
        else:
            cum_q = cumulative_sequence_length.detach().cpu().numpy().astype(numpy.int64)
            query_lens = cum_q[1:] - cum_q[:-1]
            kv_lens = past_seqlens.detach().cpu().numpy().astype(numpy.int64) + query_lens
            # The exact per-step maxima are valid upper bounds for a single Run, which is what these
            # tests do. A real scheduler would pass looser, replay-wide bounds instead.
            ort_inputs["attention_metadata"] = numpy.array([query_lens.max(), kv_lens.max()], dtype=numpy.int32)
 
    # CUDA pre-allocates the K/V cache on-device so the same OrtValue can be
    # bound as both input (key_cache) and output (key_cache_out), giving an
    # in-place update we can read back at the end. WebGPU cannot construct
    # device-side OrtValues from numpy without a session-registered shared
    # allocator, so we bind cache tensors from CPU for WebGPU.
    if config.ep == "CUDAExecutionProvider" and not quantized:
        ort_inputs["key_cache"] = OrtValue.ortvalue_from_numpy(key_cache_np, config.ort_device, 0)
        ort_inputs["value_cache"] = OrtValue.ortvalue_from_numpy(value_cache_np, config.ort_device, 0)
    sess_options = SessionOptions()
    if config.ep == "WebGpuExecutionProvider":
        ort_session = create_webgpu_session(onnx_model_str, sess_options)
    else:
        if sdpa_kernel != 0 and config.ep == "CUDAExecutionProvider":
            providers = [(config.ep, {"sdpa_kernel": str(sdpa_kernel)})]
        else:
            providers = [config.ep]
        ort_session = InferenceSession(onnx_model_str, sess_options, providers=providers)
    io_binding = ort_session.io_binding()
    if key is not None and value is not None:
        ort_inputs["key"] = key.detach().cpu().numpy()
        ort_inputs["value"] = value.detach().cpu().numpy()
        io_binding.bind_cpu_input("key", ort_inputs["key"])
        io_binding.bind_cpu_input("value", ort_inputs["value"])
    if cos is not None and sin is not None:
        ort_inputs["cos_cache"] = cos.detach().cpu().numpy()
        ort_inputs["sin_cache"] = sin.detach().cpu().numpy()
        io_binding.bind_cpu_input("cos_cache", ort_inputs["cos_cache"])
        io_binding.bind_cpu_input("sin_cache", ort_inputs["sin_cache"])
    for name, tensor in (
        ("slot_mapping", slot_mapping),
        ("head_sink", head_sink),
        ("q_norm_weight", q_norm_weight),
        ("k_norm_weight", k_norm_weight),
        ("k_scale", k_scale),
        ("v_scale", v_scale),
    ):
        if tensor is not None:
            ort_inputs[name] = tensor.detach().cpu().numpy()
            io_binding.bind_cpu_input(name, ort_inputs[name])
    if "attention_metadata" in ort_inputs:
        io_binding.bind_cpu_input("attention_metadata", ort_inputs["attention_metadata"])
    io_binding.bind_cpu_input("query", ort_inputs["query"])
    if config.ep == "CUDAExecutionProvider":
        if quantized:
            # A quantized cache has no numpy dtype, so bind the torch device buffers directly.
            cache_proto_type = KV_CACHE_TENSOR_PROTO[config.kv_cache_type]
            key_cache = key_cache.contiguous()
            value_cache = value_cache.contiguous()
            io_binding.bind_input(
                "key_cache", "cuda", 0, cache_proto_type, tuple(key_cache.shape), key_cache.data_ptr()
            )
            io_binding.bind_input(
                "value_cache", "cuda", 0, cache_proto_type, tuple(value_cache.shape), value_cache.data_ptr()
            )
        else:
            io_binding.bind_input(
                "key_cache",
                config.ort_device,
                0,
                numpy.float16,
                ort_inputs["key_cache"].shape(),
                ort_inputs["key_cache"].data_ptr(),
            )
            io_binding.bind_input(
                "value_cache",
                config.ort_device,
                0,
                numpy.float16,
                ort_inputs["value_cache"].shape(),
                ort_inputs["value_cache"].data_ptr(),
            )
    else:
        io_binding.bind_cpu_input("key_cache", key_cache_np)
        io_binding.bind_cpu_input("value_cache", value_cache_np)
    io_binding.bind_cpu_input("cumulative_sequence_length", ort_inputs["cumulative_sequence_length"])
    io_binding.bind_cpu_input("past_seqlens", ort_inputs["past_seqlens"])
    io_binding.bind_cpu_input("block_table", ort_inputs["block_table"])
    io_binding.bind_output("output")
    if config.ep == "CUDAExecutionProvider":
        if quantized:
            # Each cache output must alias its input, which is what the op requires anyway.
            io_binding.bind_output(
                "key_cache_out", "cuda", 0, cache_proto_type, tuple(key_cache.shape), key_cache.data_ptr()
            )
            io_binding.bind_output(
                "value_cache_out", "cuda", 0, cache_proto_type, tuple(value_cache.shape), value_cache.data_ptr()
            )
        else:
            io_binding.bind_ortvalue_output("key_cache_out", ort_inputs["key_cache"])
            io_binding.bind_ortvalue_output("value_cache_out", ort_inputs["value_cache"])
    else:
        # These cache tensors are graph inputs, so the allocation planner does
        # not guarantee aliasing. Bind separate outputs to exercise the
        # WebGPU copy fallback; production IO-binding should alias these
        # buffers to avoid the extra cache copy.
        io_binding.bind_output("key_cache_out")
        io_binding.bind_output("value_cache_out")
    ort_session.run_with_iobinding(io_binding)
    if quantized:
        output = torch.tensor(numpy.array(io_binding.copy_outputs_to_cpu()[0]))
        return output, key_cache, value_cache
    output, key_cache_out, value_cache_out = io_binding.copy_outputs_to_cpu()
    output = torch.tensor(numpy.array(output))
 
    # WebGPU EP has an ownership/destruction race that segfaults during Python
    # interpreter shutdown GC if sessions are left to be reclaimed implicitly.
    # Release the binding and session explicitly here so each parity test
    # completes with a clean process state.
    del io_binding
    del ort_session
 
    return output, key_cache_out, value_cache_out
 
 
def construct_local_mask(
    seqlen_q,
    seqlen_k,
    window_size=(-1, -1),  # -1 means infinite window size
    query_padding_mask=None,
    key_padding_mask=None,
    device=None,
):
    row_idx = rearrange(torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1")
    col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long)
    sk = seqlen_k if key_padding_mask is None else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1")
    sq = seqlen_q if query_padding_mask is None else rearrange(query_padding_mask.sum(-1), "b -> b 1 1 1")
    if window_size[0] < 0:
        return col_idx > row_idx + sk - sq + window_size[1]
    else:
        sk = torch.full_like(col_idx, seqlen_k) if key_padding_mask is None else sk
        return torch.logical_or(
            col_idx > torch.minimum(row_idx + sk - sq + window_size[1], sk),
            col_idx <= row_idx + sk - sq - window_size[0],
        )
 
 
def attention_ref(
    q,
    k,
    v,
    query_padding_mask=None,
    key_padding_mask=None,
    dropout_p=0.0,
    dropout_mask=None,
    causal=False,
    window_size=(-1, -1),  # -1 means infinite window size
    softcap=0.0,
    upcast=True,
    reorder_ops=False,
    head_sink=None,
):
    """
    Arguments:
        q: (batch_size, seqlen_q, nheads, head_dim)
        k: (batch_size, seqlen_k, nheads_k, head_dim)
        v: (batch_size, seqlen_k, nheads_k, head_dim)
        query_padding_mask: (batch_size, seqlen_q)
        key_padding_mask: (batch_size, seqlen_k)
        dropout_p: float
        dropout_mask: (batch_size, nheads, seqlen_q, seqlen_k)
        causal: whether to apply causal masking
        window_size: (int, int), left and right window size
        upcast: whether to cast all inputs to fp32, do all computation in fp32, then cast
            output back to fp16/bf16.
        reorder_ops: whether to change the order of operations (scaling k instead of scaling k, etc.)
            without changing the math. This is to estimate the numerical error from operation
            reordering.
    Output:
        output: (batch_size, seqlen_q, nheads, head_dim)
        attention: (batch_size, nheads, seqlen_q, seqlen_k), softmax after dropout
    """
    if causal:
        window_size = (window_size[0], 0)
    dtype_og = q.dtype
    if upcast:
        q, k, v = q.float(), k.float(), v.float()
    seqlen_q, seqlen_k = q.shape[1], k.shape[1]
    k = repeat(k, "b s h d -> b s (h g) d", g=q.shape[2] // k.shape[2])
    v = repeat(v, "b s h d -> b s (h g) d", g=q.shape[2] // v.shape[2])
    d = q.shape[-1]
    if not reorder_ops:
        scores = torch.einsum("bthd,bshd->bhts", q / math.sqrt(d), k)
    else:
        scores = torch.einsum("bthd,bshd->bhts", q, k / math.sqrt(d))
    if softcap > 0:
        scores = scores / softcap
        scores = scores.tanh()
        scores = scores * softcap
    if key_padding_mask is not None:
        scores.masked_fill_(rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf"))
    if window_size[0] >= 0 or window_size[1] >= 0:
        local_mask = construct_local_mask(
            seqlen_q,
            seqlen_k,
            window_size,
            query_padding_mask,
            key_padding_mask,
            q.device,
        )
        scores.masked_fill_(local_mask, float("-inf"))
 
    if head_sink is not None:
        # Append one extra logit per (batch, head, query) to the softmax denominator that
        # contributes no value. head_sink is the learned logit.
        b, n, s, _ = scores.shape
        sink = head_sink.to(scores.dtype).reshape(1, n, 1, 1).expand(b, -1, s, -1)
        attention = torch.softmax(torch.cat([scores, sink], dim=-1), dim=-1)[..., :-1]
    else:
        attention = torch.softmax(scores, dim=-1)
 
    # Some rows might be completely masked out so we fill them with zero instead of NaN
    if window_size[0] >= 0 or window_size[1] >= 0:
        attention = attention.masked_fill(torch.all(local_mask, dim=-1, keepdim=True), 0.0)
    # We want to mask here so that the attention matrix doesn't have any NaNs
    # Otherwise we'll get NaN in dV
    if query_padding_mask is not None:
        attention = attention.masked_fill(rearrange(~query_padding_mask, "b s -> b 1 s 1"), 0.0)
    dropout_scaling = 1.0 / (1 - dropout_p)
    if dropout_mask is not None:
        attention_drop = attention.masked_fill(~dropout_mask, 0.0)
    else:
        attention_drop = attention
    output = torch.einsum("bhts,bshd->bthd", attention_drop, v * dropout_scaling)
    if query_padding_mask is not None:
        output.masked_fill_(rearrange(~query_padding_mask, "b s -> b s 1 1"), 0.0)
    return output.to(dtype=dtype_og), attention.to(dtype=dtype_og)
 
 
def rms_norm_ref(x, weight, epsilon):
    """Per-head RMSNorm reference matching the fused CUDA prologue: reduce in fp32 over the last
    dimension (head_size), scale, then cast back to the input dtype.
 
    Arguments:
        x: (..., head_size)
        weight: (head_size)
    """
    x_f32 = x.float()
    inv_rms = torch.rsqrt(x_f32.pow(2).mean(dim=-1, keepdim=True) + epsilon)
    return (x_f32 * inv_rms * weight.float()).to(dtype=x.dtype)
 
 
def rotary_embedding(*args, **kwargs):
    # Use local import since triton is not available in Windows.
    from rotary_flash import apply_rotary_emb  # noqa: PLC0415
 
    return apply_rotary_emb(*args, **kwargs)
 
 
def unpad_qkv(config: Config, q, k, v, cum_seqlens):
    token_count = cum_seqlens[-1]
    q_unpad = torch.zeros(
        token_count,
        config.num_heads * config.head_size,
        dtype=torch.float16,
        device=config.torch_device,
    )
    k_unpad = torch.zeros(
        token_count,
        config.kv_num_heads * config.head_size,
        dtype=torch.float16,
        device=config.torch_device,
    )
    v_unpad = torch.zeros(
        token_count,
        config.kv_num_heads * config.head_size,
        dtype=torch.float16,
        device=config.torch_device,
    )
    for i in range(config.batch_size):
        new_seqlen = cum_seqlens[i + 1] - cum_seqlens[i]
        q_unpad[cum_seqlens[i] : cum_seqlens[i + 1]] = rearrange(q[i, :new_seqlen], "s n h -> s (n h)")
        k_unpad[cum_seqlens[i] : cum_seqlens[i + 1]] = rearrange(k[i, :new_seqlen], "s n h -> s (n h)")
        v_unpad[cum_seqlens[i] : cum_seqlens[i + 1]] = rearrange(v[i, :new_seqlen], "s n h -> s (n h)")
    return q_unpad, k_unpad, v_unpad
 
 
def generate_block_kvcache(config: Config, device, dtype):
    num_blocks = math.ceil(config.total_sequence_length / config.paged_kv_block_size) * config.batch_size * 3
    k_cache_paged = torch.randn(
        num_blocks, config.paged_kv_block_size, config.kv_num_heads, config.head_size, device=device, dtype=dtype
    )
    v_cache_paged = torch.randn(
        num_blocks, config.paged_kv_block_size, config.kv_num_heads, config.head_size, device=device, dtype=dtype
    )
    block_table = rearrange(
        torch.randperm(num_blocks, dtype=torch.int32, device=device),
        "(b nblocks) -> b nblocks",
        b=config.batch_size,
    )
    k_cache = rearrange(
        # pytorch 1.12 doesn't have indexing with int32
        k_cache_paged[block_table.to(dtype=torch.long).flatten()],
        "(b nblocks) block_size ... -> b (nblocks block_size) ...",
        b=config.batch_size,
    )[:, : config.total_sequence_length]
    v_cache = rearrange(
        v_cache_paged[block_table.to(dtype=torch.long).flatten()],
        "(b nblocks) block_size ... -> b (nblocks block_size) ...",
        b=config.batch_size,
    )[:, : config.total_sequence_length]
    return k_cache, v_cache, block_table, k_cache_paged, v_cache_paged
 
 
def gather_paged_to_batch(config: Config, paged, block_table):
    """Gather a paged [num_blocks, block_size, kv_num_heads, head_size] cache into the dense
    [batch_size, total_sequence_length, kv_num_heads, head_size] view the reference works with."""
    return rearrange(
        paged[block_table.to(dtype=torch.long).flatten()],
        "(b nblocks) block_size ... -> b (nblocks block_size) ...",
        b=config.batch_size,
    )[:, : config.total_sequence_length]
 
 
def derive_slot_mapping(config: Config, past_seqlens, new_seqlens, cum_seqlens, block_table):
    """Reproduce, on the host, the flat cache slot that the kernel derives for every query token
    when 'slot_mapping' is absent: block_table[b, pos // block_size] * block_size + pos % block_size
    where pos = past_seqlens[b] + index_of_token_within_its_sequence."""
    token_count = int(cum_seqlens[-1].item())
    slot_mapping = torch.empty(token_count, dtype=torch.int32, device="cuda")
    block_table_cpu = block_table.cpu()
    for b in range(config.batch_size):
        start = int(cum_seqlens[b].item())
        for j in range(int(new_seqlens[b].item())):
            pos = int(past_seqlens[b].item()) + j
            block_id = int(block_table_cpu[b, pos // config.paged_kv_block_size].item())
            slot_mapping[start + j] = block_id * config.paged_kv_block_size + pos % config.paged_kv_block_size
    return slot_mapping
 
 
def parity_check_paged_attention(
    config: Config,
    rtol=1e-3,
    atol=1e-3,
    sdpa_kernel=0,
    new_seqlens_override=None,
    local_window_size_override=None,
    past_seqlens_override=None,
    k_scale_max_override=None,
):
    # Generate padded inputs
    q = torch.randn(
        config.batch_size,
        config.sequence_length,
        config.num_heads,
        config.head_size,
        device=config.torch_device,
        dtype=torch.float16,
        requires_grad=False,
    )
    k_new = torch.randn(
        config.batch_size,
        config.sequence_length,
        config.kv_num_heads,
        config.head_size,
        device=config.torch_device,
        dtype=torch.float16,
        requires_grad=False,
    )
    v_new = torch.randn(
        config.batch_size,
        config.sequence_length,
        config.kv_num_heads,
        config.head_size,
        device=config.torch_device,
        dtype=torch.float16,
        requires_grad=False,
    )
 
    # Generate random sequence lengths
    if past_seqlens_override is not None:
        past_seqlens = past_seqlens_override.to(dtype=torch.int32, device=config.torch_device)
        assert past_seqlens.shape == (config.batch_size,)
        assert int(past_seqlens.min().item()) >= 0
        assert int(past_seqlens.max().item()) <= config.total_sequence_length - config.sequence_length
    else:
        past_seqlens = torch.randint(
            0,
            config.total_sequence_length - config.sequence_length + 1,  # one above highest integer to be drawn
            (config.batch_size,),
            dtype=torch.int32,
            device=config.torch_device,
        )
    if new_seqlens_override is not None:
        new_seqlens = new_seqlens_override.to(dtype=torch.int32, device=config.torch_device)
        assert new_seqlens.shape == (config.batch_size,)
        assert int(new_seqlens.min().item()) >= 0
        assert int(new_seqlens.max().item()) <= config.sequence_length
    else:
        new_seqlens = torch.randint(
            1,
            config.sequence_length + 1,
            (config.batch_size,),
            dtype=torch.int32,
            device=config.torch_device,
        )
    cum_seqlens = torch.cat(
        (torch.tensor([0], dtype=torch.int32, device=config.torch_device), torch.cumsum(new_seqlens, dim=0))
    ).type(torch.int32)
    total_seqlens = past_seqlens + new_seqlens
 
    q_unpad, k_unpad, v_unpad = unpad_qkv(config, q, k_new, v_new, cum_seqlens)
 
    # Generate kv cache and associated block-based data structures
    k_cache, v_cache, block_table, k_cache_paged, v_cache_paged = generate_block_kvcache(
        config, config.torch_device, torch.float16
    )
 
    # Optional per-head attention sink.
    head_sink = None
    if config.use_head_sink:
        # Spread over [-2, 6]: exp(sink) then ranges from negligible to far larger than a typical
        # softmax denominator, so a kernel that ignored the sink could not pass within tolerance.
        head_sink = (torch.rand(config.num_heads, device=config.torch_device) * 8.0 - 2.0).to(dtype=torch.float16)
 
    # Optional QK-Norm. The kernel applies RMSNorm to every Q and K head before rotary embedding,
    # so the reference has to normalize before computing q_ro / k_ro below, and the normalized +
    # rotated K is what must land in the KV cache.
    q_norm_weight = None
    k_norm_weight = None
    if config.use_qk_norm:
        q_norm_weight = torch.randn(config.head_size, device=config.torch_device, dtype=torch.float16)
        k_norm_weight = torch.randn(config.head_size, device=config.torch_device, dtype=torch.float16)
        q = rms_norm_ref(q, q_norm_weight, config.qk_norm_epsilon)
        k_new = rms_norm_ref(k_new, k_norm_weight, config.qk_norm_epsilon)
 
    # Optional explicit slot mapping. Reproducing exactly what the kernel derives from
    # past_seqlens / cumulative_sequence_length / block_table must give identical results.
    slot_mapping = None
    if config.use_slot_mapping:
        slot_mapping = derive_slot_mapping(config, past_seqlens, new_seqlens, cum_seqlens, block_table)
 
    # Set window size for local / causal
    is_causal = getattr(config, "is_causal", True)
    # A non-causal query block attends to everything on its right too, so the reference asks for a
    # right window wide enough to never mask (construct_local_mask clamps it to seqlen_k).
    right_window_size = 0 if is_causal else config.total_sequence_length
    window_size = (-1, -1)
    left_window_size = -1
    if config.local:
        left_window_size = (
            local_window_size_override
            if local_window_size_override is not None
            else getattr(config, "local_window_size", None)
        )
        if left_window_size is None:
            left_window_size = random.randint(1, config.total_sequence_length - 1)
        assert 0 < left_window_size < config.total_sequence_length
        window_size = (left_window_size, right_window_size)
    else:
        left_window_size = -1
        window_size = (-1, right_window_size) if is_causal else (-1, -1)
 
    # Apply rotary embedding for reference implementation
    if config.rotary:
        rotary_fraction = 1.0
        rotary_dim = math.floor(int(rotary_fraction * config.head_size) / 16) * 16
        angle = torch.rand(config.total_sequence_length, rotary_dim // 2, device=config.torch_device) * 2 * math.pi
        cos = torch.cos(angle).to(dtype=torch.float16)
        sin = torch.sin(angle).to(dtype=torch.float16)
        q_ro = rotary_embedding(q, cos, sin, seqlen_offsets=past_seqlens, interleaved=config.rotary_interleaved)
        k_ro = rotary_embedding(k_new, cos, sin, seqlen_offsets=past_seqlens, interleaved=config.rotary_interleaved)
    else:
        cos, sin = None, None
        q_ro, k_ro = q, k_new
 
    # Quantized paged KV cache. The pages the kernel reads back are the dequantized values, and the
    # new tokens it writes go through the same quantize step, so the reference models both. The scale
    # covers the existing pages *and* the incoming tokens so that nothing clips.
    k_scale = v_scale = None
    k_scale_b = v_scale_b = None
    if config.kv_cache_type != "float16":
        k_scale = compute_kv_scale(
            [k_cache_paged, k_ro], config.k_quant_type, config.kv_cache_type, config.kv_num_heads, config.head_size
        )
        if k_scale_max_override is not None:
            assert config.k_quant_type == "PER_CHANNEL"
            k_scale = (k_scale / k_scale.max()) * k_scale_max_override
            assert torch.isfinite(k_scale).all()
        v_scale = compute_kv_scale(
            [v_cache_paged, v_new], config.v_quant_type, config.kv_cache_type, config.kv_num_heads, config.head_size
        )
        k_scale_b = broadcast_kv_scale(k_scale, config.k_quant_type, config.kv_num_heads, config.head_size)
        v_scale_b = broadcast_kv_scale(v_scale, config.v_quant_type, config.kv_num_heads, config.head_size)
        k_cache_paged = quantize_kv(k_cache_paged, k_scale_b, config.kv_cache_type)
        v_cache_paged = quantize_kv(v_cache_paged, v_scale_b, config.kv_cache_type)
        k_cache = gather_paged_to_batch(config, dequantize_kv(k_cache_paged, k_scale_b), block_table)
        v_cache = gather_paged_to_batch(config, dequantize_kv(v_cache_paged, v_scale_b), block_table)
        k_ro = quantize_dequantize_kv(k_ro, k_scale_b, config.kv_cache_type)
        v_new = quantize_dequantize_kv(v_new, v_scale_b, config.kv_cache_type)
 
    # Update reference kv cache
    k_cache_ref = k_cache.clone()
    v_cache_ref = v_cache.clone()
    total_range = rearrange(torch.arange(config.total_sequence_length, device=config.torch_device), "s -> 1 s")
    past_seqlens_expanded = rearrange(past_seqlens, "b -> b 1")
    update_mask = torch.logical_and(
        past_seqlens_expanded <= total_range, total_range < past_seqlens_expanded + config.sequence_length
    )
    k_cache_ref[update_mask] = rearrange(k_ro, "b s ... -> (b s) ...")
    v_cache_ref[update_mask] = rearrange(v_new, "b s ... -> (b s) ...")
    k_cache_rep = repeat(k_cache_ref, "b s h d -> b s (h g) d", g=config.num_heads // config.kv_num_heads)
    v_cache_rep = repeat(v_cache_ref, "b s h d -> b s (h g) d", g=config.num_heads // config.kv_num_heads)
 
    # Create padding masks for reference implementation
    total_seqlens_expanded = rearrange(total_seqlens, "b -> b 1")
    key_padding_mask = total_range < total_seqlens_expanded
    query_range = rearrange(torch.arange(config.sequence_length, device=config.torch_device), "s -> 1 s")
    new_seqlens_expanded = rearrange(new_seqlens, "b -> b 1")
    query_padding_mask = query_range < new_seqlens_expanded
 
    # Run reference implementation of attention
    out_ref, _ = attention_ref(
        q_ro,
        k_cache_rep,
        v_cache_rep,
        query_padding_mask,
        key_padding_mask,
        0.0,
        None,
        causal=is_causal,
        window_size=window_size,
        softcap=config.softcap,
        head_sink=head_sink,
    )
    out_ref = out_ref.detach().cpu().numpy()
 
    if config.packed:
        q_unpad = torch.concatenate([q_unpad, k_unpad, v_unpad], dim=1)
        k_unpad = None
        v_unpad = None
    out, updated_k_cache_paged, updated_v_cache_paged = paged_attention_func(
        config,
        q_unpad,
        k_unpad,
        v_unpad,
        k_cache_paged,
        v_cache_paged,
        cum_seqlens,
        past_seqlens,
        block_table,
        cos,
        sin,
        left_window_size,
        sdpa_kernel=sdpa_kernel,
        slot_mapping=slot_mapping,
        head_sink=head_sink,
        q_norm_weight=q_norm_weight,
        k_norm_weight=k_norm_weight,
        k_scale=k_scale,
        v_scale=v_scale,
    )
    if config.kv_cache_type != "float16":
        updated_k_cache_paged = dequantize_kv(updated_k_cache_paged, k_scale_b).cpu().numpy()
        updated_v_cache_paged = dequantize_kv(updated_v_cache_paged, v_scale_b).cpu().numpy()
    num_tokens = q_unpad.shape[0]
    out = torch.reshape(out, (num_tokens, config.num_heads, config.head_size))
    out = out.detach().cpu().numpy()
 
    if k_scale_max_override is not None:
        assert numpy.isfinite(out_ref).all()
        assert numpy.isfinite(out).all()
 
    err_msg = f" with {config}"
    # The updated cache is compared to the reference at one quantization step of slack: the host
    # computes rotary / RMSNorm slightly differently from the kernel, and a 1-ULP fp16 difference in
    # the pre-quantization value is enough to move the rounded result by a whole step.
    cache_rtol, cache_atol = rtol, atol
    if config.kv_cache_type == "int8":
        cache_atol = atol + max(float(k_scale.max().item()), float(v_scale.max().item()))
    elif config.kv_cache_type == "fp8":
        cache_rtol = rtol + 2.0**-3  # float8e4m3fn has 3 mantissa bits
 
    # Make sure past-present buffer updating correctly
    present_k = rearrange(
        updated_k_cache_paged[block_table.to(dtype=torch.long).flatten().cpu()],
        "(b nblocks) block_size ... -> b (nblocks block_size) ...",
        b=config.batch_size,
    )[:, : config.total_sequence_length]
    present_v = rearrange(
        updated_v_cache_paged[block_table.to(dtype=torch.long).flatten().cpu()],
        "(b nblocks) block_size ... -> b (nblocks block_size) ...",
        b=config.batch_size,
    )[:, : config.total_sequence_length]
    for i in range(config.batch_size):
        numpy.testing.assert_allclose(
            present_k[i, : total_seqlens[i]],
            k_cache_ref[i, : total_seqlens[i]].detach().cpu().numpy(),
            rtol=cache_rtol,
            atol=cache_atol,
            equal_nan=k_scale_max_override is None,
            err_msg=err_msg,
        )
        numpy.testing.assert_allclose(
            present_v[i, : total_seqlens[i]],
            v_cache_ref[i, : total_seqlens[i]].detach().cpu().numpy(),
            rtol=cache_rtol,
            atol=cache_atol,
            equal_nan=k_scale_max_override is None,
            err_msg=err_msg,
        )
        new_seqlen = cum_seqlens[i + 1] - cum_seqlens[i]
        out_i = out[cum_seqlens[i] : cum_seqlens[i + 1]]
        out_ref_i = out_ref[i, :new_seqlen]
        numpy.testing.assert_allclose(
            out_i, out_ref_i, rtol=rtol, atol=atol, equal_nan=k_scale_max_override is None, err_msg=err_msg
        )
 
 
def capture_native_stdout(run_func):
    """Capture output written by the native runtime directly to file descriptor 1."""
    sys.stdout.flush()
    saved_fd = os.dup(1)
    try:
        with tempfile.TemporaryFile() as tmp:
            os.dup2(tmp.fileno(), 1)
            try:
                run_func()
            finally:
                try:
                    sys.stdout.flush()
                finally:
                    os.dup2(saved_fd, 1)
            tmp.seek(0)
            return tmp.read().decode(errors="replace")
    finally:
        os.close(saved_fd)
 
 
def capture_native_stdout_and_result(run_func):
    """Capture native stdout while preserving a callable's return value."""
    result = []
 
    def save_result():
        result.append(run_func())
 
    output = capture_native_stdout(save_result)
    return output, result[0]
 
 
def has_cuda_device():
    """Every test in this file allocates torch tensors on "cuda" and runs the CUDA EP.
 
    Some pipelines install a CPU-only torch wheel, where any `device="cuda"` allocation raises
    "AssertionError: Torch not compiled with CUDA enabled". Gate every test class on this so those
    runs skip instead of erroring."""
    return torch.cuda.is_available() and "CUDAExecutionProvider" in get_available_providers()
 
 
def has_flash_attention():
    if not has_cuda_device():
        return False
    major, _ = torch.cuda.get_device_capability()
    return major >= 8 and (
        platform.system() == "Linux"
        or (platform.system() == "Windows" and version.parse(torch.version.cuda) >= version.parse("12.0"))
    )
 
 
def has_xqa():
    if not has_cuda_device():
        return False
    major, minor = torch.cuda.get_device_capability()
    return major * 10 + minor >= 80
 
 
def has_fp8_xqa():
    if not has_cuda_device():
        return False
    major, minor = torch.cuda.get_device_capability()
    return major * 10 + minor >= 89
 
 
def has_memory_efficient_attention():
    # CUTLASS fMHA (MemoryEfficientAttention) gate — these tests are fp16-only,
    # so sm>=53 is sufficient. bf16 MEA would require sm>=80 but is not covered here.
    if not has_cuda_device():
        return False
    major, minor = torch.cuda.get_device_capability()
    return (major * 10 + minor) >= 53
 
 
def has_webgpu_ep() -> bool:
    return "WebGpuExecutionProvider" in get_available_providers()
 
 
def _webgpu_supports_config(config: Config) -> bool:
    """Feature guard for the WebGPU PagedAttention op.
 
    The WebGPU kernel is fp16-only and does not yet implement softcap. Local
    attention, rotary (interleaved and non-interleaved), packed QKV, GQA, and
    learned attention sinks are supported.
    """
    if config.softcap != 0.0:
        return False
    return True
 
 
# Bit value matching AttentionBackend::EFFICIENT_ATTENTION in
# onnxruntime/contrib_ops/cpu/bert/attention_common.h. Passing this as the
# CUDA provider option `sdpa_kernel` forces the PagedAttention kernel to
# select the MemoryEfficientAttention (CUTLASS fMHA) fallback even on SM>=80
# where FlashAttention would otherwise be preferred.
SDPA_KERNEL_EFFICIENT_ATTENTION = 2
 
# Bit value matching AttentionBackend::DECODER_ATTENTION in
# onnxruntime/contrib_ops/cpu/bert/attention_common.h. Passing this as the CUDA provider option
# `sdpa_kernel` leaves the paged decode kernel as the only enabled backend, which is how the
# unquantized decode path is reached (it is otherwise only auto-selected for a quantized cache or
# when FlashAttention is unavailable).
SDPA_KERNEL_DECODER_ATTENTION = 512
 
 
def paged_attention_test_cases():
    batches = [4] if pipeline_mode else [1, 3, 5]
    seqs = (
        [(1025, 2047)]
        if pipeline_mode
        else [
            (3, 1024),
            (1, 339),
            (408, 800),
            (333, 799),
            (64, 2048),
            (837, 4000),
            (17, 49),
            (257, 257),
            (459, 459),
        ]
    )
    num_h = [(32, 8)] if pipeline_mode else [(6, 6), (6, 3), (9, 9), (9, 3)]
    h_sizes = [256] if pipeline_mode else [32, 40, 64, 80, 96, 128, 160, 192, 224, 256]
    block_sizes = [256] if pipeline_mode else [256, 512]
 
    for b in batches:
        for s, s2 in seqs:
            for n, n2 in num_h:
                for h in h_sizes:
                    for block_size in block_sizes:
                        for local in [False, True]:
                            for rotary, rotary_interleaved in rotary_options_for_current_os():
                                for packed in [False, True]:
                                    for softcap in [0.0, 50.0]:
                                        if rotary and h % 16 > 0:
                                            continue
 
                                        config = Config(
                                            b,
                                            s,
                                            s2,
                                            n,
                                            n2,
                                            h,
                                            block_size,
                                            local,
                                            rotary,
                                            rotary_interleaved,
                                            packed,
                                            softcap,
                                        )
                                        yield (
                                            str(config),
                                            config,
                                        )
 
 
@unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available, skipping tests.")
class TestPagedAttention(unittest.TestCase):
    @parameterized.expand(paged_attention_test_cases())
    def test_paged_attention(self, _, config):
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
 
@unittest.skipIf(
    not has_memory_efficient_attention(),
    reason="MemoryEfficientAttention (fp16) requires sm>=53; skipping.",
)
class TestPagedAttentionMEA(unittest.TestCase):
    """Runs the same parity matrix as TestPagedAttention but forces the CUTLASS
    memory-efficient attention fallback via the `sdpa_kernel` CUDA provider option.
    This is the only coverage for the SM<80 fallback path introduced for PagedAttention;
    on SM>=80 the class still runs to exercise the MEA dispatch end-to-end."""
 
    @parameterized.expand(paged_attention_test_cases())
    def test_paged_attention_mea(self, _, config):
        parity_check_paged_attention(
            config,
            rtol=5e-3,
            atol=5e-3,
            sdpa_kernel=SDPA_KERNEL_EFFICIENT_ATTENTION,
        )
 
 
@unittest.skipIf(not has_cuda_device(), reason="CUDA is not available, skipping tests.")
class TestPagedAttentionFeatures(unittest.TestCase):
    """Coverage for the optional inputs and attributes added on top of the original schema:
    slot_mapping, head_sink and QK-Norm, plus the block_size and batch_size
    limits that were lifted at the same time."""
 
    def _config(self, **overrides):
        kwargs = {
            "batch_size": 4,
            "sequence_length": 33,
            "total_sequence_length": 128,
            "num_heads": 8,
            "kv_num_heads": 2,
            "head_size": 64,
            "paged_kv_block_size": 256,
            "local": False,
            "rotary": False,
            "rotary_interleaved": False,
            "packed": False,
            "softcap": 0.0,
        }
        feature_overrides = {k: overrides.pop(k) for k in list(overrides) if k not in kwargs}
        kwargs.update(overrides)
        config = Config(**kwargs)
        for key, value in feature_overrides.items():
            setattr(config, key, value)
        return config
 
    # ---- slot_mapping -------------------------------------------------------------------
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_slot_mapping_matches_derived_mapping(self):
        # An explicit slot_mapping that reproduces the derived mapping must be a no-op.
        parity_check_paged_attention(self._config(use_slot_mapping=True), rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_slot_mapping_with_rotary_and_packed(self):
        config = self._config(use_slot_mapping=True, rotary=True, packed=True)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(
        not has_memory_efficient_attention(),
        reason="MemoryEfficientAttention (fp16) requires sm>=53",
    )
    def test_slot_mapping_mea(self):
        parity_check_paged_attention(
            self._config(use_slot_mapping=True),
            rtol=5e-3,
            atol=5e-3,
            sdpa_kernel=SDPA_KERNEL_EFFICIENT_ATTENTION,
        )
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_slot_mapping_negative_one_skips_cache_write(self):
        # -1 tells the kernel not to store this token's K/V, which is how a scheduler suppresses
        # writes for prefix-cache hits or rejected speculative tokens. The cache must be
        # bit-identical to its pre-run contents at those slots.
        config = self._config(use_slot_mapping=True)
        token_count = 2
        num_blocks = 4
        block_size = config.paged_kv_block_size
        query = torch.randn(token_count, config.num_heads * config.head_size, device="cuda", dtype=torch.float16)
        key = torch.randn(token_count, config.kv_num_heads * config.head_size, device="cuda", dtype=torch.float16)
        value = torch.randn(token_count, config.kv_num_heads * config.head_size, device="cuda", dtype=torch.float16)
        key_cache = torch.randn(
            num_blocks, block_size, config.kv_num_heads, config.head_size, device="cuda", dtype=torch.float16
        )
        value_cache = torch.randn_like(key_cache)
        key_cache_before = key_cache.clone().cpu().numpy()
        value_cache_before = value_cache.clone().cpu().numpy()
 
        # One sequence of 2 new tokens on top of 1 cached token.
        config.batch_size = 1
        cum_seqlens = torch.tensor([0, token_count], dtype=torch.int32, device="cuda")
        past_seqlens = torch.tensor([1], dtype=torch.int32, device="cuda")
        block_table = torch.tensor([[0, 1]], dtype=torch.int32, device="cuda")
        # Store the first token at slot 1 of block 0; skip the second one entirely.
        slot_mapping = torch.tensor([1, -1], dtype=torch.int32, device="cuda")
 
        _, key_cache_out, value_cache_out = paged_attention_func(
            config,
            query,
            key,
            value,
            key_cache,
            value_cache,
            cum_seqlens,
            past_seqlens,
            block_table,
            slot_mapping=slot_mapping,
        )
        key_cache_out = numpy.array(key_cache_out)
        value_cache_out = numpy.array(value_cache_out)
 
        # Slot 1 of block 0 holds the first token's K/V.
        numpy.testing.assert_allclose(
            key_cache_out[0, 1], key[0].reshape(config.kv_num_heads, config.head_size).cpu().numpy()
        )
        numpy.testing.assert_allclose(
            value_cache_out[0, 1], value[0].reshape(config.kv_num_heads, config.head_size).cpu().numpy()
        )
        # Everything else, including the slot the second token would have used, is untouched.
        key_cache_before[0, 1] = key_cache_out[0, 1]
        value_cache_before[0, 1] = value_cache_out[0, 1]
        numpy.testing.assert_array_equal(key_cache_out, key_cache_before)
        numpy.testing.assert_array_equal(value_cache_out, value_cache_before)
 
    # ---- head_sink ---------------------------------------------------------------------
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_head_sink(self):
        parity_check_paged_attention(self._config(use_head_sink=True), rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_head_sink_local_and_softcap(self):
        # The LSE epilogue must compose with sliding window and softcap, both of which are already
        # baked into the log-sum-exp that FlashAttention returns.
        config = self._config(use_head_sink=True, local=True, softcap=50.0)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_head_sink_with_rotary(self):
        parity_check_paged_attention(self._config(use_head_sink=True, rotary=True), rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(
        not has_memory_efficient_attention(),
        reason="MemoryEfficientAttention (fp16) requires sm>=53",
    )
    def test_head_sink_rejected_on_memory_efficient_path(self):
        # The CUTLASS kernel does not expose a log-sum-exp, so the sink cannot be applied. The op
        # must fail loudly rather than silently ignore the input.
        with self.assertRaises(Exception) as ctx:
            parity_check_paged_attention(
                self._config(use_head_sink=True),
                rtol=5e-3,
                atol=5e-3,
                sdpa_kernel=SDPA_KERNEL_EFFICIENT_ATTENTION,
            )
        self.assertIn("head_sink", str(ctx.exception))
 
    # ---- QK-Norm -----------------------------------------------------------------------
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_qk_norm(self):
        parity_check_paged_attention(self._config(use_qk_norm=True), rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_qk_norm_with_rotary(self):
        # QK-Norm is applied before rotary, and the normalized+rotated K is what lands in the cache.
        # The cache parity assertions in parity_check_paged_attention cover that ordering.
        parity_check_paged_attention(self._config(use_qk_norm=True, rotary=True), rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_qk_norm_with_rotary_interleaved_and_packed(self):
        config = self._config(use_qk_norm=True, rotary=True, rotary_interleaved=True, packed=True)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_qk_norm_non_power_of_two_head_size(self):
        # head_size=80 rounds up to a 128-thread block in the fused prologue, so the lanes past
        # head_size must contribute zero to the RMS reduction and skip all global accesses.
        parity_check_paged_attention(self._config(use_qk_norm=True, head_size=80), rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(
        not has_memory_efficient_attention(),
        reason="MemoryEfficientAttention (fp16) requires sm>=53",
    )
    def test_qk_norm_mea(self):
        parity_check_paged_attention(
            self._config(use_qk_norm=True),
            rtol=5e-3,
            atol=5e-3,
            sdpa_kernel=SDPA_KERNEL_EFFICIENT_ATTENTION,
        )
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_qk_norm_and_head_sink_together(self):
        parity_check_paged_attention(
            self._config(use_qk_norm=True, use_head_sink=True, rotary=True, use_slot_mapping=True),
            rtol=5e-3,
            atol=5e-3,
        )
 
    # ---- lifted limits -----------------------------------------------------------------
 
    @parameterized.expand([(16,), (32,), (64,), (128,)])
    @unittest.skipIf(
        not has_memory_efficient_attention(),
        reason="MemoryEfficientAttention (fp16) requires sm>=53",
    )
    def test_small_block_size(self, block_size):
        # block_size used to be required to be a multiple of 256. Smaller pages are now accepted;
        # FlashAttention cannot address them (a kBlockN tile would straddle a page), so the kernel
        # transparently falls back to the gather-based memory-efficient backend.
        config = self._config(paged_kv_block_size=block_size, total_sequence_length=128)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_large_batch_size(self):
        # cumulative_seqlens_kv used to be produced by independent 256-thread cub::BlockScan blocks,
        # so any batch beyond 256 sequences got silently wrong KV offsets.
        config = self._config(batch_size=300, sequence_length=4, total_sequence_length=64)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    # ---- is_causal ---------------------------------------------------------------------
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_non_causal(self):
        # A block drafter submits its whole query block at once and every row must see the rest of
        # the block, so the mask is unbounded on the right.
        parity_check_paged_attention(self._config(is_causal=False), rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_non_causal_local_window(self):
        # local_window_size still bounds the mask on the left when the causal bound is removed.
        config = self._config(is_causal=False, local=True)
        parity_check_paged_attention(
            config,
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.full((config.batch_size,), config.sequence_length, dtype=torch.int32),
            local_window_size_override=4,
        )
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_non_causal_with_rotary_and_packed(self):
        config = self._config(is_causal=False, rotary=True, packed=True)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @parameterized.expand(
        [
            (f"page{block_size}_{backend}_{step}_{mask}", block_size, sdpa_kernel, cached, local)
            for block_size, backend, sdpa_kernel in [
                (16, "mea", SDPA_KERNEL_EFFICIENT_ATTENTION),
                (32, "mea", SDPA_KERNEL_EFFICIENT_ATTENTION),
                (64, "mea", SDPA_KERNEL_EFFICIENT_ATTENTION),
                (64, "default", 0),
            ]
            for step, cached in [("prefill", False), ("cached", True)]
            for mask, local in [("full", False), ("local", True)]
        ]
    )
    @unittest.skipIf(
        not has_memory_efficient_attention(),
        reason="MemoryEfficientAttention (fp16) requires sm>=53",
    )
    def test_non_causal_mea(self, _, block_size, sdpa_kernel, cached, local):
        # Multiple query tiles must retain the left bound at past + query_pos - W + 1,
        # while every row can still see the rest of its sequence on the right.
        config = self._config(
            sequence_length=137,
            total_sequence_length=384,
            num_heads=4,
            head_size=128,
            paged_kv_block_size=block_size,
            is_causal=False,
            local=local,
        )
        parity_check_paged_attention(
            config,
            rtol=5e-3,
            atol=5e-3,
            sdpa_kernel=sdpa_kernel,
            new_seqlens_override=torch.tensor([137, 67, 0, 9], dtype=torch.int32),
            past_seqlens_override=torch.tensor([97, 31, 0, 15] if cached else [0, 0, 0, 0], dtype=torch.int32),
            local_window_size_override=4 if local else None,
        )
 
 
# -----------------------------------------------------------------------------
# WebGPU EP parity tests
#
# Reuses the CUDA parity harness (parity_check_paged_attention, attention_ref,
# unpad_qkv, generate_block_kvcache) with Config.ep = "WebGpuExecutionProvider".
# Config matrix is deliberately small (per-op session-create through Dawn is
# heavier than CUDA). 5e-3 abs/rel tolerance matches CUDA at head_size=128.
# -----------------------------------------------------------------------------
def paged_attention_test_cases_webgpu():
    """Hand-picked config matrix for the WebGPU EP. Kept small because the
    WebGPU EP dispatches per-op through Dawn and each session-create is
    heavier than under CUDA.
    """
    batches = [1, 2]
    seqs = [
        (1, 32),  # decode, short past
        (4, 32),  # short prefill, short past
        (16, 64),  # medium prefill
        (1, 64),  # decode, medium past
    ]
    num_h = [(8, 8), (8, 4)]  # MHA + GQA
    h_sizes = [128]  # WebGPU FA requires head_size % 4 == 0
    block_sizes = [256]
 
    for b in batches:
        for s, s2 in seqs:
            for n, n2 in num_h:
                for h in h_sizes:
                    for block_size in block_sizes:
                        for rotary, rotary_interleaved in rotary_options_for_current_os():
                            for packed in [False, True]:
                                # Rotary requires head_size % 16 == 0 (matches CUDA harness).
                                if rotary and h % 16 > 0:
                                    continue
 
                                config = Config(
                                    b,
                                    s,
                                    s2,
                                    n,
                                    n2,
                                    h,
                                    block_size,
                                    False,
                                    rotary,
                                    rotary_interleaved,
                                    packed,
                                    0.0,  # softcap - not supported on WebGPU
                                    ep="WebGpuExecutionProvider",
                                )
                                if _webgpu_supports_config(config):
                                    yield (str(config), config)
 
 
@unittest.skipIf(not has_webgpu_ep(), reason="WebGpuExecutionProvider is not available.")
class TestPagedAttentionWebGpu(unittest.TestCase):
    """Parity tests against the WebGPU PagedAttention kernel.
 
    Runs the same PyTorch reference (attention_ref) as the CUDA classes over a
    smaller config matrix filtered to the features WebGPU supports.
    """
 
    @parameterized.expand(paged_attention_test_cases_webgpu())
    def test_paged_attention_webgpu(self, _, config):
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_non_causal(self):
        config = Config(1, 4, 32, 2, 1, 32, 16, False, False, False, False, 0.0, ep="WebGpuExecutionProvider")
        config.is_causal = False
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @parameterized.expand(
        [
            (f"{name}_{rotary}_{interleaved}", lengths, past, kv_heads, head_size, local, rotary, interleaved)
            for name, lengths, past, kv_heads, head_size, local in [
                ("decode_mha", [1, 1], [15, 63], 4, 64, False),
                ("decode_gqa", [1, 1], [16, 65], 2, 80, False),
                ("prefill_gqa", [65, 33, 0], [0, 7, 0], 1, 128, False),
                ("dflash", [7, 2, 0], [31, 1, 0], 2, 64, True),
                ("local_prefill", [65, 33, 1], [17, 0, 3], 2, 64, True),
            ]
            for rotary, interleaved in rotary_options_for_current_os()
        ]
    )
    def test_qk_norm_parity(self, _, lengths, past, kv_heads, head_size, local, rotary, interleaved):
        config = Config(
            len(lengths),
            max(lengths),
            128,
            4,
            kv_heads,
            head_size,
            16,
            local,
            rotary,
            interleaved,
            rotary,
            0.0,
            ep="WebGpuExecutionProvider",
        )
        config.use_qk_norm = True
        config.is_causal = not local
        config.use_attention_metadata = local
        if local:
            config.attention_metadata_override = numpy.array([max(lengths), 128], dtype=numpy.int32)
        parity_check_paged_attention(
            config,
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor(lengths, dtype=torch.int32),
            past_seqlens_override=torch.tensor(past, dtype=torch.int32),
            local_window_size_override=4 if local else -1,
        )
 
    def _check_qk_norm_qwen38_cpu_reference(self, query_length, window, block_ids):
        past_length, block_size = 15, 16
        total_length = past_length + query_length
        config = Config(
            1,
            query_length,
            total_length,
            24,
            4,
            256,
            block_size,
            True,
            True,
            False,
            False,
            0.0,
            ep="WebGpuExecutionProvider",
        )
        config.use_qk_norm = True
        config.is_causal = False
        generator = torch.Generator(device="cpu").manual_seed(0)
 
        def randn(*shape):
            return torch.randn(*shape, generator=generator, device="cpu", dtype=torch.float32)
 
        query = (
            randn(query_length, config.num_heads, config.head_size)
            * torch.linspace(0.1, 2.4, config.num_heads, device="cpu").reshape(1, -1, 1)
        ).half()
        key = (
            randn(query_length, config.kv_num_heads, config.head_size)
            * torch.linspace(0.2, 1.7, config.kv_num_heads, device="cpu").reshape(1, -1, 1)
        ).half()
        value = randn(query_length, config.kv_num_heads, config.head_size).half()
        q_weight = torch.linspace(0.2, 1.7, config.head_size, device="cpu").half()
        k_weight = torch.linspace(1.3, -0.7, config.head_size, device="cpu").half()
        # One physical page is unused, in addition to unused slots on the last logical page.
        num_blocks = len(block_ids) + 1
        key_cache = randn(num_blocks, block_size, config.kv_num_heads, config.head_size).half()
        value_cache = randn(num_blocks, block_size, config.kv_num_heads, config.head_size).half()
        block_table = torch.tensor([block_ids], dtype=torch.int32, device="cpu")
 
        frequencies = 10000.0 ** (-torch.arange(0, config.head_size, 2, device="cpu").float() / config.head_size)
        angles = torch.arange(total_length, device="cpu").float()[:, None] * frequencies
        cos, sin = angles.cos().half(), angles.sin().half()
 
        def normalize_and_rotate(x, weight):
            # Materialize FP16 RMSNorm before FP32 split-half RoPE, then round to FP16 again.
            normalized = rms_norm_ref(x, weight, config.qk_norm_epsilon).float()
            x0, x1 = normalized.chunk(2, dim=-1)
            c, s = cos[past_length:, None, :].float(), sin[past_length:, None, :].float()
            return torch.cat((x0 * c - x1 * s, x0 * s + x1 * c), dim=-1).half()
 
        q_ref = normalize_and_rotate(query, q_weight)
        k_ref = normalize_and_rotate(key, k_weight)
        expected_k, expected_v = key_cache.clone(), value_cache.clone()
        unchanged = numpy.ones((num_blocks, block_size), dtype=bool)
        for row in range(query_length):
            position = past_length + row
            block, slot = block_ids[position // block_size], position % block_size
            expected_k[block, slot] = k_ref[row]
            expected_v[block, slot] = value[row]
            unchanged[block, slot] = False
 
        dense_k = expected_k[block_table[0].long()].flatten(0, 1)[:total_length]
        dense_v = expected_v[block_table[0].long()].flatten(0, 1)[:total_length]
        reference, _ = attention_ref(
            q_ref.unsqueeze(0),
            dense_k.unsqueeze(0),
            dense_v.unsqueeze(0),
            causal=False,
            window_size=(window, total_length),
        )
        output, actual_k, actual_v = paged_attention_func(
            config,
            query.flatten(1),
            key.flatten(1),
            value.flatten(1),
            key_cache,
            value_cache,
            torch.tensor([0, query_length], dtype=torch.int32, device="cpu"),
            torch.tensor([past_length], dtype=torch.int32, device="cpu"),
            block_table,
            cos,
            sin,
            window_size=window,
            q_norm_weight=q_weight,
            k_norm_weight=k_weight,
        )
        numpy.testing.assert_allclose(
            output.numpy(), reference.reshape(output.shape).numpy(), rtol=5e-3, atol=5e-3, equal_nan=False
        )
        numpy.testing.assert_allclose(actual_k, expected_k.numpy(), rtol=5e-3, atol=5e-3, equal_nan=False)
        numpy.testing.assert_array_equal(actual_v, expected_v.numpy())
        # Cached K must not be normalized/rotated again; old and unused slots stay bit-identical.
        numpy.testing.assert_array_equal(actual_k[unchanged], key_cache.numpy()[unchanged])
        numpy.testing.assert_array_equal(actual_v[unchanged], value_cache.numpy()[unchanged])
 
    def test_qk_norm_qwen38_non_causal_local_window_prefill(self):
        # Two queries select split-reduce with 256-wide heads and 6:1 GQA.
        # Positions 15/16 cross a page; non-causal visible keys are [14, 17) and [15, 17).
        self._check_qk_norm_qwen38_cpu_reference(query_length=2, window=2, block_ids=[1, 0])
 
    def test_qk_norm_qwen38_non_causal_local_window_dense_prefill(self):
        # Q=32 selects dense prefill's 16-key tiles. Appends cross positions 15/16 and 31/32.
        # Window=4 partially masks the first tile for early queries and fully masks it for later ones.
        self._check_qk_norm_qwen38_cpu_reference(query_length=32, window=4, block_ids=[2, 0, 1])
 
    def test_qk_norm_split_norm_dimension(self):
        # A single 512-channel head selects the normalization helper's split-dimension shader.
        config = Config(1, 1, 32, 1, 1, 512, 16, False, False, False, False, 0.0, ep="WebGpuExecutionProvider")
        config.use_qk_norm = True
        parity_check_paged_attention(
            config,
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor([1]),
            past_seqlens_override=torch.tensor([15]),
        )
 
    @parameterized.expand(
        [("per_head", 1.0, 0.25), ("zero", 0.0, 1e-12), ("small", 1e-6, 1e-12), ("large", 1000.0, 1e-6)]
    )
    def test_qk_norm_cpu_reference_and_cache_reuse(self, _, magnitude, epsilon):
        config = Config(1, 1, 32, 4, 2, 64, 16, False, False, False, False, 0.0, ep="WebGpuExecutionProvider")
        config.use_qk_norm = True
        config.qk_norm_epsilon = epsilon
        generator = torch.Generator(device="cpu").manual_seed(43)
        key_cache = torch.randn(2, 16, 2, 64, generator=generator, dtype=torch.float16)
        value_cache = torch.randn(2, 16, 2, 64, generator=generator, dtype=torch.float16)
        block_table = torch.tensor([[1, 0]], dtype=torch.int32)
        channels = torch.linspace(-1.0, 1.0, 64)
        # Gains are per channel and shared across heads; Q and K have different learned gains.
        q_weight = torch.linspace(0.2, 1.7, 64).half()
        k_weight = torch.linspace(1.3, -0.7, 64).half()
        query = (magnitude * torch.tensor([0.01, 0.3, 2.0, 20.0])[:, None] * channels).half().unsqueeze(0)
        key = (magnitude * torch.tensor([0.1, 3.0])[:, None] * channels.flip(0)).half().unsqueeze(0)
        value = torch.randn(1, 2, 64, generator=generator, dtype=torch.float16)
        q_ref = rms_norm_ref(query, q_weight, epsilon)
        k_ref = rms_norm_ref(key, k_weight, epsilon)
 
        def attend(q, dense_k, dense_v):
            logits = torch.einsum("qnh,knh->nqk", q.float(), dense_k.float()) / math.sqrt(64)
            return torch.einsum("nqk,knh->qnh", logits.softmax(-1), dense_v.float()).reshape(1, -1)
 
        for past in (15, 16):
            expected_k = key_cache.clone()
            expected_v = value_cache.clone()
            block, slot = block_table[0, past // 16], past % 16
            expected_k[block, slot] = k_ref[0]
            expected_v[block, slot] = value[0]
            dense_k = expected_k[block_table[0].long()].flatten(0, 1)[: past + 1].repeat_interleave(2, dim=1)
            dense_v = expected_v[block_table[0].long()].flatten(0, 1)[: past + 1].repeat_interleave(2, dim=1)
 
            expected_output = attend(q_ref, dense_k, dense_v)
            if magnitude == 1.0:
                wrong_q = rms_norm_ref(query.flatten(1), q_weight.repeat(4), epsilon).reshape_as(query)
                self.assertGreater((attend(wrong_q, dense_k, dense_v) - expected_output).abs().max().item(), 0.02)
                wrong_k = rms_norm_ref(key.flatten(1), k_weight.repeat(2), epsilon).reshape_as(key)
                self.assertGreater((wrong_k - k_ref).abs().max().item(), 0.1)
 
            output, actual_k, actual_v = paged_attention_func(
                config,
                query.flatten(1),
                key.flatten(1),
                value.flatten(1),
                key_cache,
                value_cache,
                torch.tensor([0, 1], dtype=torch.int32),
                torch.tensor([past], dtype=torch.int32),
                block_table,
                q_norm_weight=q_weight,
                k_norm_weight=k_weight,
            )
            self.assertTrue(numpy.isfinite(output.numpy()).all())
            self.assertTrue(numpy.isfinite(actual_k).all())
            numpy.testing.assert_allclose(output.numpy(), expected_output.numpy(), rtol=5e-3, atol=5e-3)
            numpy.testing.assert_allclose(actual_k, expected_k.numpy(), rtol=1e-3, atol=1e-3)
            numpy.testing.assert_array_equal(actual_v, expected_v.numpy())
            # All old and unused cache slots must be untouched, including K appended on the previous call.
            unchanged = numpy.ones((2, 16), dtype=bool)
            unchanged[block, slot] = False
            numpy.testing.assert_array_equal(actual_k[unchanged], key_cache.numpy()[unchanged])
            key_cache, value_cache = torch.from_numpy(actual_k.copy()), torch.from_numpy(actual_v.copy())
 
    @parameterized.expand([("zero", 0.0), ("negative", -1.0), ("nan", float("nan")), ("infinite", float("inf"))])
    def test_qk_norm_invalid_epsilon(self, _, epsilon):
        config = Config(1, 1, 32, 4, 2, 64, 16, False, False, False, False, 0.0, ep="WebGpuExecutionProvider")
        config.use_qk_norm = True
        config.qk_norm_epsilon = epsilon
        with self.assertRaisesRegex(Exception, "qk_norm_epsilon"):
            parity_check_paged_attention(config)
 
    @parameterized.expand(
        [
            (f"{name}_{causal}_{metadata}", new_lengths, past_lengths, window, kv_heads, causal, metadata)
            for name, new_lengths, past_lengths, window, kv_heads in [
                ("decode", [1, 1, 1], [0, 3, 65], 4, 4),
                ("short_prefill", [4, 2, 0], [15, 1, 0], 4, 2),
                ("unit_window", [8, 3, 1], [63, 0, 17], 1, 1),
                ("wide_window", [4, 2, 1], [0, 1, 3], 16, 2),
                ("split_boundary", [31, 9, 0], [63, 4, 0], 7, 2),
                ("prefill_boundary", [32, 17, 1], [31, 0, 3], 4, 2),
                ("prefill_no_past", [65, 33, 0, 2], [0, 0, 0, 0], 4, 2),
                ("prefill", [137, 67, 0, 9], [97, 31, 0, 15], 4, 1),
            ]
            for causal in [False, True]
            for metadata in [False, True]
        ]
    )
    def test_local_window_parity(self, _, new_lengths, past_lengths, window, kv_heads, causal, metadata):
        config = Config(
            len(new_lengths),
            max(new_lengths),
            384,
            4,
            kv_heads,
            64,
            16,
            True,
            False,
            False,
            True,
            0.0,
            ep="WebGpuExecutionProvider",
        )
        config.is_causal = causal
        config.use_attention_metadata = metadata
        parity_check_paged_attention(
            config,
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor(new_lengths, dtype=torch.int32),
            past_seqlens_override=torch.tensor(past_lengths, dtype=torch.int32),
            local_window_size_override=window,
        )
 
    @parameterized.expand([("decode", 1, 65), ("multi_query_prefill", 4, 33)])
    def test_qwen38_non_causal_local_window(self, _, query_length, past_length):
        # The 256-wide heads select the Qwen3.8 split-reduce workgroup-storage
        # specialization for both single-token decode and multi-row prefill.
        config = Config(
            1,
            query_length,
            128,
            24,
            4,
            256,
            16,
            True,
            False,
            False,
            False,
            0.0,
            ep="WebGpuExecutionProvider",
        )
        config.is_causal = False
        with torch.random.fork_rng(devices=[torch.cuda.current_device()] if torch.cuda.is_available() else []):
            torch.manual_seed(0)
            parity_check_paged_attention(
                config,
                rtol=5e-3,
                atol=5e-3,
                new_seqlens_override=torch.tensor([query_length], dtype=torch.int32),
                past_seqlens_override=torch.tensor([past_length], dtype=torch.int32),
                local_window_size_override=4,
            )
 
    def test_qwen38_non_causal_local_window_dense_prefill(self):
        # Q=32 reaches dense prefill; fp16 head_size=256 selects 16-key tiles.
        # The query-relative window partially masks the first tile for early
        # rows and fully masks it for later rows in the same workgroup.
        query_length, past_length, window = 32, 33, 4
        total_length = past_length + query_length
        config = Config(
            1, query_length, total_length, 24, 4, 256, 16, True, False, False, False, 0.0, ep="WebGpuExecutionProvider"
        )
        config.is_causal = False
        query = torch.zeros(query_length, config.num_heads * config.head_size, dtype=torch.float16)
        dense_key = torch.zeros(total_length, config.kv_num_heads, config.head_size, dtype=torch.float16)
        # Equal logits make the output depend only on which distinct values are visible.
        dense_value = (
            torch.arange(1, total_length + 1, dtype=torch.float16).reshape(-1, 1, 1).expand_as(dense_key).contiguous()
        )
        num_blocks = math.ceil(total_length / config.paged_kv_block_size)
        block_table = torch.arange(num_blocks - 1, -1, -1, dtype=torch.int32).reshape(1, num_blocks)
        key_cache = torch.zeros(
            num_blocks, config.paged_kv_block_size, config.kv_num_heads, config.head_size, dtype=torch.float16
        )
        value_cache = torch.zeros_like(key_cache)
        for position in range(past_length):
            block = block_table[0, position // config.paged_kv_block_size]
            value_cache[block, position % config.paged_kv_block_size] = dense_value[position]
 
        reference, _ = attention_ref(
            query.reshape(1, query_length, config.num_heads, config.head_size),
            dense_key.unsqueeze(0),
            dense_value.unsqueeze(0),
            causal=False,
            window_size=(window, total_length),
        )
        output, _, _ = paged_attention_func(
            config,
            query,
            dense_key[past_length:].reshape(query_length, -1),
            dense_value[past_length:].reshape(query_length, -1),
            key_cache,
            value_cache,
            torch.tensor([0, query_length], dtype=torch.int32),
            torch.tensor([past_length], dtype=torch.int32),
            block_table,
            window_size=window,
        )
        numpy.testing.assert_allclose(output.numpy(), reference.reshape(output.shape).numpy(), rtol=5e-3, atol=5e-3)
 
    @parameterized.expand([("split", 4), ("prefill", 65)])
    def test_non_causal_local_window_query_bounds(self, _, query_length):
        # Equal logits make each output the mean of the visible key positions.
        # Unequal Q/KV lengths distinguish query-relative masking from causal,
        # trailing-window, unwindowed, and batch-max-length masking.
        config = Config(
            2,
            query_length,
            128,
            4,
            2,
            64,
            16,
            True,
            False,
            False,
            False,
            0.0,
            ep="WebGpuExecutionProvider",
        )
        config.is_causal = False
        config.use_attention_metadata = True
        config.attention_metadata_override = numpy.array([query_length, 128], dtype=numpy.int32)
        new_lengths = [query_length, 2]
        past_lengths = [5, 0]
        cumulative = torch.tensor([0, query_length, query_length + 2], dtype=torch.int32)
        block_table = torch.arange(15, -1, -1, dtype=torch.int32).reshape(2, 8)
        key_cache = torch.zeros(16, 16, 2, 64, dtype=torch.float16)
        value_cache = torch.zeros_like(key_cache)
        query = torch.zeros(query_length + 2, 4 * 64, dtype=torch.float16)
        key = torch.zeros(query_length + 2, 2 * 64, dtype=torch.float16)
        value = torch.zeros_like(key)
        expected = []
        for b, (past, length) in enumerate(zip(past_lengths, new_lengths, strict=True)):
            for position in range(past):
                value_cache[block_table[b, position // 16], position % 16] = position + 1
            for q in range(length):
                position = past + q
                value[cumulative[b] + q] = position + 1
                left = max(0, position + 1 - 4)
                right = past + length
                expected.append((left + 1 + right) / 2)
 
        output, _, _ = paged_attention_func(
            config,
            query,
            key,
            value,
            key_cache,
            value_cache,
            cumulative,
            torch.tensor(past_lengths, dtype=torch.int32),
            block_table,
            window_size=4,
        )
        expected = numpy.broadcast_to(numpy.array(expected)[:, None], output.shape)
        numpy.testing.assert_allclose(output.numpy(), expected, rtol=5e-3, atol=5e-3)
 
    @parameterized.expand([("causal", True), ("non_causal", False)])
    def test_local_window_fully_masked_leading_tile(self, _, causal):
        # With 65 queries in one prefill workgroup, the first 32-key tile is
        # entirely outside later rows' two-key window.
        query_length = 65
        config = Config(
            1, query_length, 128, 2, 1, 64, 16, True, False, False, False, 0.0, ep="WebGpuExecutionProvider"
        )
        config.is_causal = causal
        config.use_attention_metadata = True
        config.attention_metadata_override = numpy.array([query_length, 128], dtype=numpy.int32)
        query = torch.zeros(query_length, 2 * 64, dtype=torch.float16)
        key = torch.zeros(query_length, 64, dtype=torch.float16)
        value = torch.ones_like(key)
        value[:32] = (100 + torch.arange(32, dtype=torch.float16)).unsqueeze(1)
 
        reference, _ = attention_ref(
            query.reshape(1, query_length, 2, 64),
            key.reshape(1, query_length, 1, 64),
            value.reshape(1, query_length, 1, 64),
            causal=causal,
            window_size=(2, 0 if causal else 128),
        )
        output, _, _ = paged_attention_func(
            config,
            query,
            key,
            value,
            torch.zeros(8, 16, 1, 64, dtype=torch.float16),
            torch.zeros(8, 16, 1, 64, dtype=torch.float16),
            torch.tensor([0, query_length], dtype=torch.int32),
            torch.tensor([0], dtype=torch.int32),
            torch.arange(7, -1, -1, dtype=torch.int32).reshape(1, 8),
            window_size=2,
        )
        numpy.testing.assert_allclose(
            output.numpy()[33:], reference.reshape(query_length, -1).numpy()[33:], rtol=5e-3, atol=5e-3
        )
 
    def test_flash_attention_fully_masked_tile_with_bias(self):
        # GQA shares the dense FlashAttention shader and accepts attention_bias.
        # Keeping visible scores at qk_min_value makes an all-masked leading
        # tile observable instead of letting later tiles erase its contribution.
        query_length, past_length, head_size = 64, 32, 64
        total_length = query_length + past_length
        shapes = {
            "query": [1, query_length, 2 * head_size],
            "key": [1, query_length, head_size],
            "value": [1, query_length, head_size],
            "past_key": [1, 1, past_length, head_size],
            "past_value": [1, 1, past_length, head_size],
            "seqlens_k": [1],
            "total_sequence_length": [1],
            "attention_bias": [1, 1, query_length, total_length],
        }
        inputs = [
            helper.make_tensor_value_info(
                name, TensorProto.INT32 if name in ("seqlens_k", "total_sequence_length") else TensorProto.FLOAT, shape
            )
            for name, shape in shapes.items()
        ]
        node = helper.make_node(
            "GroupQueryAttention",
            [*list(shapes)[:7], "", "", "", "attention_bias"],
            ["output", "present_key", "present_value"],
            domain="com.microsoft",
            num_heads=2,
            kv_num_heads=1,
            local_window_size=2,
            causal=1,
        )
        graph = helper.make_graph(
            [node],
            "flash_attention_local_window",
            inputs,
            [helper.make_tensor_value_info("output", TensorProto.FLOAT, [1, query_length, 2 * head_size])],
        )
        model = helper.make_model(
            graph,
            opset_imports=[helper.make_opsetid("", 23), helper.make_opsetid("com.microsoft", 1)],
            ir_version=10,
        )
        feed = {name: numpy.zeros(shape, dtype=numpy.float32) for name, shape in shapes.items()}
        feed["value"][:] = 1
        feed["past_value"][0, 0] = numpy.arange(100, 100 + past_length, dtype=numpy.float32)[:, None]
        feed["seqlens_k"] = numpy.array([total_length - 1], dtype=numpy.int32)
        feed["total_sequence_length"] = numpy.array([total_length], dtype=numpy.int32)
        feed["attention_bias"][:] = numpy.finfo(numpy.float32).min
 
        options = SessionOptions()
        options.add_session_config_entry("session.disable_cpu_ep_fallback", "1")
        session = create_webgpu_session(model.SerializeToString(), options)
        output = session.run(["output"], feed)[0]
        values = torch.ones(1, total_length, 1, head_size)
        values[0, :past_length] = torch.arange(100, 100 + past_length).reshape(-1, 1, 1)
        reference, _ = attention_ref(
            torch.zeros(1, query_length, 2, head_size),
            torch.zeros_like(values),
            values,
            causal=True,
            window_size=(2, 0),
        )
        numpy.testing.assert_allclose(output, reference.reshape(output.shape).numpy(), rtol=5e-3, atol=5e-3)
 
    def test_paged_attention_webgpu_attention_metadata(self):
        config = Config(
            batch_size=2,
            sequence_length=1,
            total_sequence_length=64,
            num_heads=8,
            kv_num_heads=4,
            head_size=128,
            paged_kv_block_size=256,
            local=False,
            rotary=False,
            rotary_interleaved=False,
            packed=False,
            softcap=0.0,
            ep="WebGpuExecutionProvider",
        )
        config.use_attention_metadata = True
        config.attention_metadata_shape = [3]
        config.attention_metadata_override = numpy.array([1, 64, 1], dtype=numpy.int32)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
        ragged_config = Config(
            batch_size=2,
            sequence_length=2,
            total_sequence_length=64,
            num_heads=8,
            kv_num_heads=4,
            head_size=128,
            paged_kv_block_size=256,
            local=False,
            rotary=False,
            rotary_interleaved=False,
            packed=False,
            softcap=0.0,
            ep="WebGpuExecutionProvider",
        )
        ragged_config.use_attention_metadata = True
        ragged_config.attention_metadata_shape = [3]
        ragged_config.attention_metadata_override = numpy.array([2, 2, 0], dtype=numpy.int32)
        parity_check_paged_attention(
            ragged_config,
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor([2, 0], dtype=torch.int32),
            past_seqlens_override=torch.tensor([0, 0], dtype=torch.int32),
        )
        parity_check_paged_attention(
            ragged_config,
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor([1, 2], dtype=torch.int32),
            past_seqlens_override=torch.tensor([0, 0], dtype=torch.int32),
        )
 
    def _gptoss_config(self, sequence_length, *, local=True, use_head_sink=True):
        config = Config(
            batch_size=2,
            sequence_length=sequence_length,
            total_sequence_length=256,
            num_heads=64,
            kv_num_heads=8,
            head_size=64,
            paged_kv_block_size=256,
            local=local,
            rotary=True,
            rotary_interleaved=False,
            packed=True,
            softcap=0.0,
            ep="WebGpuExecutionProvider",
        )
        config.local_window_size = 128
        config.use_head_sink = use_head_sink
        return config
 
    def test_gptoss_local_window_head_sink_prefill(self):
        parity_check_paged_attention(
            self._gptoss_config(sequence_length=16),
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor([16, 9], dtype=torch.int32),
            past_seqlens_override=torch.tensor([240, 192], dtype=torch.int32),
        )
 
    def test_gptoss_local_window_head_sink_decode(self):
        parity_check_paged_attention(
            self._gptoss_config(sequence_length=1),
            rtol=5e-3,
            atol=5e-3,
            past_seqlens_override=torch.tensor([255, 192], dtype=torch.int32),
        )
 
    def test_local_window_short_history(self):
        parity_check_paged_attention(
            self._gptoss_config(sequence_length=4, use_head_sink=False),
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor([4, 2], dtype=torch.int32),
            past_seqlens_override=torch.tensor([0, 4], dtype=torch.int32),
        )
 
    def test_head_sink_prefill_without_local_window(self):
        parity_check_paged_attention(
            self._gptoss_config(sequence_length=32, local=False),
            rtol=5e-3,
            atol=5e-3,
            new_seqlens_override=torch.tensor([32, 17], dtype=torch.int32),
            past_seqlens_override=torch.tensor([224, 100], dtype=torch.int32),
        )
 
    def test_head_sink_decode_without_local_window(self):
        parity_check_paged_attention(
            self._gptoss_config(sequence_length=1, local=False),
            rtol=5e-3,
            atol=5e-3,
            past_seqlens_override=torch.tensor([255, 192], dtype=torch.int32),
        )
 
 
@unittest.skipIf(not has_cuda_device(), reason="CUDA is not available, skipping tests.")
class TestPagedAttentionRotaryZeroTokenRegression(unittest.TestCase):
    """Regression tests for the FA `max_query_len` heuristic when one or more
    batches have zero new tokens.
 
    The old FA path used `token_count - batch_size + 1` as both the rotary
    grid size and the `mha_varlen_fwd` max query length. This assumes every
    batch has at least one new token. With zero-token batches, the value can be
    smaller than the real per-batch maximum, or even non-positive. Then rotary
    can skip Q/K tokens, FA can under-launch at the kBlockM boundary, or FA can
    fail with an invalid launch grid. The MEA path was fixed in PR #28200; this
    class covers the FA regressions fixed by the current PR.
    """
 
    def _config(self, batch_size=4, sequence_length=10, total_sequence_length=64, rotary=True):
        return Config(
            batch_size=batch_size,
            sequence_length=sequence_length,
            total_sequence_length=total_sequence_length,
            num_heads=8,
            kv_num_heads=2,
            head_size=64,
            paged_kv_block_size=256,
            local=False,
            rotary=rotary,
            rotary_interleaved=False,
            packed=False,
            softcap=0.0,
        )
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_fa_rotary_zero_token_first_batch(self):
        # lens = [10, 0, 0, 0]. heuristic = 10 - 4 + 1 = 7. true max = 10.
        # Tokens at positions s=7,8,9 in batch 0 do not get rotary applied.
        new_seqlens = torch.tensor([10, 0, 0, 0], dtype=torch.int32, device="cuda")
        parity_check_paged_attention(self._config(), rtol=5e-3, atol=5e-3, new_seqlens_override=new_seqlens)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_fa_rotary_zero_token_mixed(self):
        # lens = [0, 7, 0, 3]. heuristic = 10 - 4 + 1 = 7. true max = 7.
        # In this case the heuristic happens to equal the true max, but the
        # input still has a zero-token batch and exercises the grid-launch path.
        new_seqlens = torch.tensor([0, 7, 0, 3], dtype=torch.int32, device="cuda")
        parity_check_paged_attention(self._config(), rtol=5e-3, atol=5e-3, new_seqlens_override=new_seqlens)
 
    @unittest.skipIf(
        not has_memory_efficient_attention(),
        reason="MemoryEfficientAttention (fp16) requires sm>=53",
    )
    def test_mea_rotary_zero_token_no_regression(self):
        # PR #28200 fixed the MEA path on this input. This test guards against
        # a regression of that fix.
        new_seqlens = torch.tensor([10, 0, 0, 0], dtype=torch.int32, device="cuda")
        parity_check_paged_attention(
            self._config(),
            rtol=5e-3,
            atol=5e-3,
            sdpa_kernel=SDPA_KERNEL_EFFICIENT_ATTENTION,
            new_seqlens_override=new_seqlens,
        )
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_fa_rotary_zero_token_large_batch(self):
        # 16 batches, only batch 0 has new tokens. token_count = 10, so the
        # heuristic max_query_len_hint = 10 - 16 + 1 = -5 (negative). The
        # value reaches mha_varlen_fwd as params.seqlen_q. Without the exact
        # max_query_len fix added in this PR, FA launches with an invalid grid
        # and fails with CUDA error 9 (invalid configuration argument).
        config = self._config(batch_size=16)
        new_seqlens = torch.tensor([10] + [0] * 15, dtype=torch.int32, device="cuda")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3, new_seqlens_override=new_seqlens)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_fa_no_rotary_zero_token_sanity(self):
        # With rotary off, the rotary kernel is not launched, so this input
        # only checks that ordinary zero-token batches still work on the FA
        # path. The max query length stays below the kBlockM=64 boundary here.
        new_seqlens = torch.tensor([10, 0, 0, 0], dtype=torch.int32, device="cuda")
        parity_check_paged_attention(self._config(rotary=False), rtol=5e-3, atol=5e-3, new_seqlens_override=new_seqlens)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_fa_kblockm_boundary_zero_token(self):
        # batch_size=2, lens=[65, 0]. The true max new-query length is 65,
        # which crosses the FA kBlockM=64 boundary. With the older
        # `token_count - batch_size + 1` heuristic, mha_varlen_fwd would see
        # seqlen_q=64 and launch grid.x=1, dropping the 65th query token.
        # This test exercises FA grid sizing with rotary on.
        config = self._config(batch_size=2, sequence_length=65, total_sequence_length=128)
        new_seqlens = torch.tensor([65, 0], dtype=torch.int32, device="cuda")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3, new_seqlens_override=new_seqlens)
 
    @unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available")
    def test_fa_kblockm_boundary_zero_token_no_rotary(self):
        # Same kBlockM=64 boundary case as above with rotary off. This isolates
        # the FA grid silent-drop from the rotary grid silent-drop.
        config = self._config(batch_size=2, sequence_length=65, total_sequence_length=128, rotary=False)
        new_seqlens = torch.tensor([65, 0], dtype=torch.int32, device="cuda")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3, new_seqlens_override=new_seqlens)
 
 
def has_fp8_kv_cache():
    """The float8e4m3fn PagedAttention kernels are only built when onnxruntime_USE_FP8_KV_CACHE is on."""
    if not hasattr(torch, "float8_e4m3fn") or not hasattr(TensorProto, "FLOAT8E4M3FN"):
        return False
    if not has_flash_attention():
        return False
    config = Config(1, 1, 16, 1, 1, 64, 16, False, False, False, False, 0.0)
    config.kv_cache_type = "fp8"
    config.k_quant_type = "PER_TENSOR"
    config.v_quant_type = "PER_TENSOR"
    try:
        InferenceSession(
            create_paged_attention_graph(config, 1, 1, 1),
            SessionOptions(),
            providers=[config.ep],
        )
    except Exception:
        return False
    return True
 
 
@unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available, skipping tests.")
class TestPagedAttentionQuantizedCache(unittest.TestCase):
    """Coverage for the quantized paged KV cache (int8 / float8e4m3fn, PER_TENSOR / PER_CHANNEL).
 
    Both backends read a quantized cache through the dequantize-on-gather path, so these tests also
    cover FlashAttention's non-paged varlen entry point, which is only reachable this way."""
 
    def setUp(self):
        # Quantization amplifies host/device rounding differences, so the inputs are re-seeded here
        # to keep these tests independent of the order the rest of the module ran in.
        torch.manual_seed(0)
 
    def _config(self, **overrides):
        kwargs = {
            "batch_size": 4,
            "sequence_length": 33,
            "total_sequence_length": 128,
            "num_heads": 8,
            "kv_num_heads": 2,
            "head_size": 64,
            "paged_kv_block_size": 256,
            "local": False,
            "rotary": False,
            "rotary_interleaved": False,
            "packed": False,
            "softcap": 0.0,
        }
        feature_overrides = {k: overrides.pop(k) for k in list(overrides) if k not in kwargs}
        kwargs.update(overrides)
        config = Config(**kwargs)
        for key, value in feature_overrides.items():
            setattr(config, key, value)
        return config
 
    def _int8_config(self, quant_type="PER_TENSOR", **overrides):
        return self._config(kv_cache_type="int8", k_quant_type=quant_type, v_quant_type=quant_type, **overrides)
 
    # ---- int8 ---------------------------------------------------------------------------
 
    @parameterized.expand([("per_tensor", "PER_TENSOR"), ("per_channel", "PER_CHANNEL")])
    def test_int8_cache(self, _, quant_type):
        parity_check_paged_attention(self._int8_config(quant_type), rtol=5e-3, atol=5e-3)
 
    @parameterized.expand([("per_tensor", "PER_TENSOR"), ("per_channel", "PER_CHANNEL")])
    def test_int8_cache_with_rotary_and_packed(self, _, quant_type):
        config = self._int8_config(quant_type, rotary=True, packed=True)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_int8_cache_with_qk_norm_and_slot_mapping(self):
        # QK-Norm rescales K before it is written, and slot_mapping changes where it is written;
        # both happen upstream of the quantization step in ReshapeAndCache.
        config = self._int8_config("PER_CHANNEL", use_qk_norm=True, use_slot_mapping=True, rotary=True)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_int8_cache_local_and_softcap(self):
        config = self._int8_config("PER_TENSOR", local=True, softcap=50.0)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_int8_cache_mixed_granularity(self):
        # k_quant_type and v_quant_type are independent attributes.
        config = self._config(kv_cache_type="int8", k_quant_type="PER_CHANNEL", v_quant_type="PER_TENSOR")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @parameterized.expand([("16", 16), ("32", 32), ("64", 64)])
    def test_int8_cache_small_block_size(self, _, block_size):
        # A quantized cache never reaches FlashAttention's paged kernel, so the page-alignment
        # constraint that forces small block sizes onto the MEA fallback does not apply here.
        config = self._int8_config("PER_CHANNEL", paged_kv_block_size=block_size)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(
        not has_memory_efficient_attention(),
        reason="MemoryEfficientAttention (fp16) requires sm>=53",
    )
    def test_int8_cache_mea(self):
        parity_check_paged_attention(
            self._int8_config("PER_CHANNEL"),
            rtol=5e-3,
            atol=5e-3,
            sdpa_kernel=SDPA_KERNEL_EFFICIENT_ATTENTION,
        )
 
    # ---- float8e4m3fn -------------------------------------------------------------------
 
    @parameterized.expand([("per_tensor", "PER_TENSOR"), ("per_channel", "PER_CHANNEL")])
    @unittest.skipIf(not has_fp8_kv_cache(), reason="FP8 KV cache kernels are not built")
    def test_fp8_cache(self, _, quant_type):
        config = self._config(kv_cache_type="fp8", k_quant_type=quant_type, v_quant_type=quant_type)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_fp8_kv_cache(), reason="FP8 KV cache kernels are not built")
    def test_fp8_cache_with_rotary_and_qk_norm(self):
        config = self._config(
            kv_cache_type="fp8",
            k_quant_type="PER_CHANNEL",
            v_quant_type="PER_CHANNEL",
            rotary=True,
            use_qk_norm=True,
        )
        # Rotary and QK-Norm both diverge from the kernel by ~1 fp16 ULP, which is enough to move a
        # value across an e4m3 rounding boundary; one such step is a ~12% change in a K element.
        parity_check_paged_attention(config, rtol=5e-3, atol=2e-2)
 
    # ---- validation ---------------------------------------------------------------------
 
    def _run_minimal(self, config, k_scale=None, v_scale=None):
        """Run PagedAttention on a trivially small input, bypassing the parity reference. Used to
        check that invalid quantization configurations are rejected."""
        cache_torch_dtype = {
            "float16": torch.float16,
            "int8": torch.int8,
            "fp8": getattr(torch, "float8_e4m3fn", None),
        }[config.kv_cache_type]
        cache_shape = (1, config.paged_kv_block_size, config.kv_num_heads, config.head_size)
        key_cache = torch.zeros(cache_shape, dtype=torch.float16, device="cuda").to(cache_torch_dtype)
        value_cache = torch.zeros(cache_shape, dtype=torch.float16, device="cuda").to(cache_torch_dtype)
        num_tokens = config.sequence_length
        query = torch.zeros((num_tokens, config.num_heads * config.head_size), dtype=torch.float16, device="cuda")
        key = torch.zeros((num_tokens, config.kv_num_heads * config.head_size), dtype=torch.float16, device="cuda")
        paged_attention_func(
            config,
            query,
            key,
            key.clone(),
            key_cache,
            value_cache,
            torch.tensor([0, num_tokens], dtype=torch.int32, device="cuda"),
            torch.zeros(config.batch_size, dtype=torch.int32, device="cuda"),
            torch.zeros((config.batch_size, 1), dtype=torch.int32, device="cuda"),
            k_scale=k_scale,
            v_scale=v_scale,
        )
 
    def _minimal_config(self, **overrides):
        return self._config(
            batch_size=1, sequence_length=4, total_sequence_length=16, paged_kv_block_size=16, **overrides
        )
 
    def test_quantized_cache_without_quant_type_is_rejected(self):
        config = self._minimal_config(kv_cache_type="int8")
        with self.assertRaises(Exception) as ctx:
            self._run_minimal(config)
        self.assertIn("k_quant_type", str(ctx.exception))
 
    def test_quant_type_without_quantized_cache_is_rejected(self):
        config = self._minimal_config(k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        scale = torch.ones(1, dtype=torch.float32, device="cuda")
        with self.assertRaises(Exception) as ctx:
            self._run_minimal(config, k_scale=scale, v_scale=scale)
        self.assertIn("not quantized", str(ctx.exception))
 
    @parameterized.expand([("key", "k_cache_dtype"), ("value", "v_cache_dtype")])
    def test_unsupported_cache_dtype_is_rejected(self, _, attribute_name):
        config = self._minimal_config(kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        setattr(config, attribute_name, "int4")
        scale = torch.ones(1, dtype=torch.float32, device="cuda")
        with self.assertRaises(Exception) as ctx:
            self._run_minimal(config, k_scale=scale, v_scale=scale)
        self.assertIn(attribute_name, str(ctx.exception))
 
    @parameterized.expand([("key", "k_cache_dtype"), ("value", "v_cache_dtype")])
    def test_cache_dtype_disagreeing_with_cache_tensor_is_rejected(self, _, attribute_name):
        config = self._minimal_config(kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        setattr(config, attribute_name, "float16")
        scale = torch.ones(1, dtype=torch.float32, device="cuda")
        with self.assertRaises(Exception) as ctx:
            self._run_minimal(config, k_scale=scale, v_scale=scale)
        self.assertIn(attribute_name, str(ctx.exception))
 
    def test_cache_dtype_naming_the_cache_tensor_type_is_accepted(self):
        # '' and an explicit spelling of the tensor's own element type mean the same thing.
        config = self._minimal_config(
            kv_cache_type="int8",
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_TENSOR",
            k_cache_dtype="int8",
            v_cache_dtype="int8",
        )
        scale = torch.ones(1, dtype=torch.float32, device="cuda")
        self._run_minimal(config, k_scale=scale, v_scale=scale)
 
    @parameterized.expand([("key", "k_cache_dtype"), ("value", "v_cache_dtype")])
    def test_unknown_cache_dtype_is_rejected(self, _, attribute_name):
        # "uint4" is deliberately not in the vocabulary: an unsigned logical type implies a zero
        # point of 8, and this operator quantizes symmetrically with a scale only.
        config = self._minimal_config(kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        setattr(config, attribute_name, "uint4")
        scale = torch.ones(1, dtype=torch.float32, device="cuda")
        with self.assertRaises(Exception) as ctx:
            self._run_minimal(config, k_scale=scale, v_scale=scale)
        self.assertIn("Invalid KV cache data type", str(ctx.exception))
 
 
@unittest.skipIf(not has_flash_attention(), reason="Flash Attention is not available, skipping tests.")
class TestPagedAttentionPagedDecode(unittest.TestCase):
    """Coverage for the paged decode backend: a flash-decoding style kernel that scores the paged
    KV cache in place (dequantizing in registers) instead of gathering it into a dense buffer.
 
    It is selected by the static shape test `token_count == batch_size`, which is a heuristic for
    "one new token per sequence" rather than a proof, so the kernel has to stay correct for ragged
    steps too (see the ragged cases below). The unquantized cases pin the backend with
    `sdpa_kernel`; the quantized cases reach it through the normal auto-selection."""
 
    def setUp(self):
        torch.manual_seed(0)
 
    def _config(self, **overrides):
        kwargs = {
            "batch_size": 4,
            "sequence_length": 1,
            "total_sequence_length": 128,
            "num_heads": 8,
            "kv_num_heads": 2,
            "head_size": 64,
            "paged_kv_block_size": 256,
            "local": False,
            "rotary": False,
            "rotary_interleaved": False,
            "packed": False,
            "softcap": 0.0,
        }
        feature_overrides = {k: overrides.pop(k) for k in list(overrides) if k not in kwargs}
        kwargs.update(overrides)
        config = Config(**kwargs)
        for key, value in feature_overrides.items():
            setattr(config, key, value)
        return config
 
    def _check_decode(self, config, rtol=5e-3, atol=5e-3, new_seqlens_override=None):
        parity_check_paged_attention(
            config,
            rtol=rtol,
            atol=atol,
            sdpa_kernel=SDPA_KERNEL_DECODER_ATTENTION,
            new_seqlens_override=new_seqlens_override,
        )
 
    # ---- shapes -------------------------------------------------------------------------
 
    @parameterized.expand([("32", 32), ("64", 64), ("80", 80), ("96", 96), ("128", 128), ("256", 256)])
    def test_decode_head_size(self, _, head_size):
        # head_size straddles the two PV thread mappings: one channel group when head_size >= 128
        # (the CTA width), several groups of head_size threads below it.
        self._check_decode(self._config(head_size=head_size))
 
    @parameterized.expand([("mha", 8, 8), ("gqa_4x", 8, 2), ("gqa_2x", 6, 3), ("mqa", 9, 1)])
    def test_decode_head_grouping(self, _, num_heads, kv_num_heads):
        self._check_decode(self._config(num_heads=num_heads, kv_num_heads=kv_num_heads))
 
    @parameterized.expand([("16", 16), ("32", 32), ("64", 64), ("256", 256), ("512", 512)])
    def test_decode_block_size(self, _, block_size):
        # The decode kernel resolves a page per KV token, so unlike FlashAttention's paged kernel it
        # has no page-alignment constraint and a KV tile may straddle any number of pages.
        self._check_decode(self._config(paged_kv_block_size=block_size))
 
    def test_decode_long_context_multi_tile(self):
        # Far more than one 128-token tile per split, so the online-softmax rescaling across tiles
        # is exercised rather than a single-shot tile.
        self._check_decode(self._config(total_sequence_length=4000, paged_kv_block_size=256))
 
    def test_decode_multi_split(self):
        # One sequence and few heads leaves the GPU mostly idle, so the host picks num_splits > 1
        # and the cross-split reduction (rather than a single partial) produces the output.
        self._check_decode(self._config(batch_size=1, num_heads=2, kv_num_heads=1, total_sequence_length=4000))
 
    def test_decode_short_context(self):
        # Fewer KV tokens than a tile, and short enough that some splits are empty.
        self._check_decode(self._config(batch_size=1, num_heads=2, kv_num_heads=1, total_sequence_length=8))
 
    def test_decode_zero_new_tokens(self):
        # Sequences with no new token contribute no output row; the kernel must skip them without
        # disturbing the rows of the sequences that do have one.
        new_seqlens = torch.tensor([0, 1, 0, 1], dtype=torch.int32)
        self._check_decode(self._config(), new_seqlens_override=new_seqlens)
 
    # ---- ragged steps -------------------------------------------------------------------
    #
    # The host selects this backend from `token_count <= batch_size` alone, which does not prove one
    # token per sequence. Every CTA therefore resolves its own sequence and in-sequence position
    # from cumulative_sequence_length on device and masks against that token's own causal length.
    # These cases are the ones a wrong implementation passes only by accident.
 
    def test_decode_ragged_shape_test_holds(self):
        # token_count == batch_size == 4, but the tokens are distributed 3 / 0 / 0 / 1.
        new_seqlens = torch.tensor([3, 0, 0, 1], dtype=torch.int32)
        self._check_decode(self._config(sequence_length=3), new_seqlens_override=new_seqlens)
 
    def test_decode_ragged_all_tokens_in_one_sequence(self):
        # The extreme case: one sequence owns the whole step, so per-token causal masking is the
        # only thing that can produce the right answer.
        new_seqlens = torch.tensor([4, 0, 0, 0], dtype=torch.int32)
        self._check_decode(self._config(sequence_length=4), new_seqlens_override=new_seqlens)
 
    def test_decode_ragged_local_window(self):
        new_seqlens = torch.tensor([3, 0, 0, 1], dtype=torch.int32)
        self._check_decode(self._config(sequence_length=3, local=True), new_seqlens_override=new_seqlens)
 
    def test_decode_ragged_multi_split(self):
        # Few (token, head) pairs and a long context force num_splits > 1, so the per-token split
        # boundaries and the cross-split reduction are exercised on a ragged step.
        new_seqlens = torch.tensor([2, 0], dtype=torch.int32)
        self._check_decode(
            self._config(batch_size=2, sequence_length=2, num_heads=2, kv_num_heads=1, total_sequence_length=4000),
            new_seqlens_override=new_seqlens,
        )
 
    @parameterized.expand(
        [
            (f"{name}_page{block_size}", new_seqlens, total_length, local, score_transforms, block_size)
            for name, new_seqlens, total_length, local, score_transforms in [
                ("ragged", [3, 0, 0, 1], 128, False, False),
                ("sparse_local", [3, 0, 0, 0], 128, True, False),
                ("multi_split", [2, 0], 4096, False, False),
                ("multi_split_local_sink_softcap", [2, 0], 4096, True, True),
            ]
            for block_size in [16, 32, 64]
        ]
    )
    def test_decode_non_causal_ragged(self, _, new_seqlens, total_length, local, score_transforms, block_size):
        # token_count <= batch_size selects portable decode despite multiple queries in a sequence.
        config = self._config(
            batch_size=len(new_seqlens),
            sequence_length=max(new_seqlens),
            total_sequence_length=total_length,
            num_heads=2,
            kv_num_heads=1,
            head_size=128,
            paged_kv_block_size=block_size,
            is_causal=False,
            local=local,
            use_head_sink=score_transforms,
            softcap=2.0 if score_transforms else 0.0,
        )
        past_seqlens = [total_length - config.sequence_length - 17 * b for b in range(config.batch_size)]
        parity_check_paged_attention(
            config,
            rtol=5e-3,
            atol=5e-3,
            sdpa_kernel=SDPA_KERNEL_DECODER_ATTENTION,
            new_seqlens_override=torch.tensor(new_seqlens, dtype=torch.int32),
            past_seqlens_override=torch.tensor(past_seqlens, dtype=torch.int32),
            local_window_size_override=4 if local else None,
        )
 
    def test_decode_ragged_int8_cache(self):
        # Auto-selected: a quantized decode-shaped step. XQA cannot serve it (its output layout is
        # one row per batch index), so it must fall through to this kernel and still be correct.
        new_seqlens = torch.tensor([3, 0, 0, 1], dtype=torch.int32)
        config = self._config(
            sequence_length=3, kv_cache_type="int8", k_quant_type="PER_CHANNEL", v_quant_type="PER_CHANNEL"
        )
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3, new_seqlens_override=new_seqlens)
 
    # ---- masking and score transforms ---------------------------------------------------
 
    def test_decode_local_window(self):
        self._check_decode(self._config(local=True))
 
    def test_decode_softcap(self):
        self._check_decode(self._config(softcap=50.0))
 
    def test_decode_local_and_softcap(self):
        self._check_decode(self._config(local=True, softcap=50.0))
 
    def test_decode_head_sink(self):
        self._check_decode(self._config(use_head_sink=True))
 
    def test_decode_head_sink_local_and_softcap(self):
        self._check_decode(self._config(use_head_sink=True, local=True, softcap=50.0))
 
    # ---- prologue interaction -----------------------------------------------------------
 
    def test_decode_rotary(self):
        self._check_decode(self._config(rotary=True))
 
    def test_decode_rotary_interleaved_and_packed(self):
        self._check_decode(self._config(rotary=True, rotary_interleaved=True, packed=True))
 
    def test_decode_qk_norm_and_slot_mapping(self):
        self._check_decode(self._config(use_qk_norm=True, use_slot_mapping=True, rotary=True))
 
    # ---- quantized cache (auto-selected, no sdpa_kernel override) ------------------------
 
    @parameterized.expand([("per_tensor", "PER_TENSOR"), ("per_channel", "PER_CHANNEL")])
    def test_decode_int8_cache(self, _, quant_type):
        # A quantized cache auto-selects the decode backend at sequence_length 1: the scales fold
        # into Q and into the output, so the pages are read once at int8 width.
        config = self._config(kv_cache_type="int8", k_quant_type=quant_type, v_quant_type=quant_type)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_decode_int8_cache_mixed_granularity(self):
        config = self._config(kv_cache_type="int8", k_quant_type="PER_CHANNEL", v_quant_type="PER_TENSOR")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_decode_int8_cache_local_softcap_and_sink(self):
        config = self._config(
            kv_cache_type="int8",
            k_quant_type="PER_CHANNEL",
            v_quant_type="PER_CHANNEL",
            local=True,
            softcap=50.0,
            use_head_sink=True,
        )
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @parameterized.expand([("per_tensor", "PER_TENSOR"), ("per_channel", "PER_CHANNEL")])
    @unittest.skipIf(not has_fp8_kv_cache(), reason="FP8 KV cache kernels are not built")
    def test_decode_fp8_cache(self, _, quant_type):
        config = self._config(kv_cache_type="fp8", k_quant_type=quant_type, v_quant_type=quant_type)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_fp8_kv_cache(), reason="FP8 KV cache kernels are not built")
    def test_decode_fp8_cache_with_rotary(self):
        config = self._config(kv_cache_type="fp8", k_quant_type="PER_CHANNEL", v_quant_type="PER_CHANNEL", rotary=True)
        parity_check_paged_attention(config, rtol=5e-3, atol=2e-2)
 
 
@unittest.skipIf(not has_xqa(), reason="XQA requires an SM80 or newer GPU")
class TestPagedAttentionXqaDecode(unittest.TestCase):
    """Coverage for the XQA decode backend.
 
    XQA is the tensor-core decode kernel (shared with GroupQueryAttention) reading the paged cache
    in place. It is auto-selected ahead of the portable decode kernel when the cache is quantized
    and the step fits its constraints: exactly one new token per sequence, head_size in {64, 128},
    a query/KV group size in {4, 6, 8, 16, 32}, no softcap, and block_size a multiple of 128 (a block
    is presented to the kernel as several 128-token pages). Anything outside that falls back, which
    is what the ORT_ENABLE_XQA=0 comparison below pins down.
 
    Every case here is also run through the fallback so a bug in XQA shows up as a parity failure
    rather than being masked by both paths sharing the reference."""
 
    def setUp(self):
        torch.manual_seed(0)
 
    def _config(self, **overrides):
        kwargs = {
            "batch_size": 4,
            "sequence_length": 1,
            "total_sequence_length": 1024,
            "num_heads": 8,
            "kv_num_heads": 2,
            "head_size": 64,
            "paged_kv_block_size": 256,
            "local": False,
            "rotary": False,
            "rotary_interleaved": False,
            "packed": False,
            "softcap": 0.0,
        }
        feature_overrides = {k: overrides.pop(k) for k in list(overrides) if k not in kwargs}
        kwargs.update(overrides)
        config = Config(**kwargs)
        for key, value in feature_overrides.items():
            setattr(config, key, value)
        return config
 
    def _check_xqa(
        self,
        quant_type="PER_TENSOR",
        kv_cache_type="int8",
        rtol=5e-3,
        atol=5e-3,
        k_scale_max_override=None,
        expect_xqa=None,
        per_channel_xqa=None,
        past_seqlens_override=None,
        **overrides,
    ):
        if kv_cache_type == "fp8":
            if not has_fp8_kv_cache():
                self.skipTest("FP8 KV cache kernels are not built")
            if not has_fp8_xqa():
                self.skipTest("FP8 XQA requires an SM89 or newer GPU")
 
        config = self._config(
            kv_cache_type=kv_cache_type,
            k_quant_type=quant_type,
            v_quant_type=quant_type,
            **overrides,
        )
 
        def run():
            parity_check_paged_attention(
                config,
                rtol=rtol,
                atol=atol,
                k_scale_max_override=k_scale_max_override,
                past_seqlens_override=past_seqlens_override,
            )
 
        if expect_xqa is None:
            run()
            return
        with patch.dict(
            os.environ,
            {"ORT_ENABLE_ATTENTION_KERNEL_DEBUG_INFO": "1", "ORT_ENABLE_XQA": "1"},
        ):
            debug_output = capture_native_stdout(run)
        if expect_xqa:
            self.assertIn("SdpaKernel=XQA", debug_output)
        else:
            self.assertNotIn("SdpaKernel=XQA", debug_output)
 
    def _capture_xqa_debug(self, config):
        with patch.dict(
            os.environ,
            {"ORT_ENABLE_ATTENTION_KERNEL_DEBUG_INFO": "1", "ORT_ENABLE_XQA": "1"},
        ):
            return capture_native_stdout(lambda: parity_check_paged_attention(config, rtol=5e-3, atol=5e-3))
 
    # ---- shapes -------------------------------------------------------------------------
 
    @parameterized.expand([("64", 64), ("128", 128)])
    def test_xqa_head_size(self, _, head_size):
        self._check_xqa(head_size=head_size)
 
    @parameterized.expand([("grp4", 8, 2), ("grp6", 12, 2), ("grp8", 8, 1), ("grp16", 16, 1), ("grp32", 32, 1)])
    def test_xqa_head_grouping(self, _, num_heads, kv_num_heads):
        self._check_xqa(num_heads=num_heads, kv_num_heads=kv_num_heads)
 
    @parameterized.expand([("head64_per_tensor", 64, "PER_TENSOR"), ("head128_per_channel", 128, "PER_CHANNEL")])
    def test_xqa_group_size_six_dispatch(self, _, head_size, quant_type):
        # Six query heads exercise XQA's padded query-row path. Parity checks the visible rows,
        # while debug telemetry proves the result did not come from the fallback kernel.
        baseline_config = self._config(
            num_heads=32,
            kv_num_heads=8,
            head_size=head_size,
            kv_cache_type="int8",
            k_quant_type=quant_type,
            v_quant_type=quant_type,
        )
        baseline_debug_output = self._capture_xqa_debug(baseline_config)
        if "SdpaKernel=XQA" not in baseline_debug_output:
            self.skipTest("Paged XQA is not runnable for this head size and quantization configuration")
 
        config = self._config(
            num_heads=48,
            kv_num_heads=8,
            head_size=head_size,
            kv_cache_type="int8",
            k_quant_type=quant_type,
            v_quant_type=quant_type,
        )
        debug_output = self._capture_xqa_debug(config)
        self.assertIn("Operator=PagedAttention", debug_output)
        self.assertIn("SdpaKernel=XQA", debug_output)
        self.assertIn("GqaGroupSize=6", debug_output)
 
    @parameterized.expand([("128", 128), ("256", 256), ("512", 512)])
    def test_xqa_block_size(self, _, block_size):
        # Larger blocks are remapped to consecutive 128-token XQA pages; 128-token tables pass through.
        self._check_xqa(paged_kv_block_size=block_size)
 
    @parameterized.expand(
        [
            ("contiguous", [0, 1], -1),
            ("fragmented", [2, 0], -1),
            ("negative_one", [-1, 1], 128),
        ]
    )
    def test_xqa_native_page_table_matches_expanded(self, _, expanded_block_ids, local_window_size):
        """A 128-token native table must be exactly the page expansion of the 256-token table."""
        # The -1 entries are outside the 128-token local window and therefore never dereferenced.
        device = "cuda"
        pages_per_expanded_block = 2
        expanded_block_table = torch.tensor([expanded_block_ids], dtype=torch.int32, device=device)
        page_offsets = torch.arange(pages_per_expanded_block, dtype=torch.int32, device=device)
        native_page_table = torch.where(
            expanded_block_table.unsqueeze(-1) < 0,
            torch.full_like(expanded_block_table.unsqueeze(-1) + page_offsets, -1),
            expanded_block_table.unsqueeze(-1) * pages_per_expanded_block + page_offsets,
        ).reshape(1, -1)
 
        expected_pages = []
        for block_id in expanded_block_ids:
            expected_pages.extend([-1, -1] if block_id < 0 else [block_id * 2, block_id * 2 + 1])
        self.assertEqual(native_page_table.cpu().tolist(), [expected_pages])
 
        physical_blocks = max(expanded_block_ids) + 1
        expanded_key_cache = torch.randint(
            -32,
            33,
            (physical_blocks, 256, 2, 64),
            dtype=torch.int8,
            device=device,
        )
        expanded_value_cache = torch.randint(
            -32,
            33,
            (physical_blocks, 256, 2, 64),
            dtype=torch.int8,
            device=device,
        )
        native_key_cache = expanded_key_cache.reshape(physical_blocks * 2, 128, 2, 64).clone()
        native_value_cache = expanded_value_cache.reshape(physical_blocks * 2, 128, 2, 64).clone()
 
        query = torch.randn(1, 8 * 64, dtype=torch.float16, device=device)
        key = torch.randn(1, 2 * 64, dtype=torch.float16, device=device)
        value = torch.randn(1, 2 * 64, dtype=torch.float16, device=device)
        cumulative_seqlens = torch.tensor([0, 1], dtype=torch.int32, device=device)
        past_seqlens = torch.tensor([383], dtype=torch.int32, device=device)
        k_scale = torch.tensor([1.0 / 32.0], dtype=torch.float32, device=device)
        v_scale = torch.tensor([1.0 / 32.0], dtype=torch.float32, device=device)
 
        def run(block_size, block_table, key_cache, value_cache):
            config = self._config(
                batch_size=1,
                total_sequence_length=512,
                paged_kv_block_size=block_size,
                local=local_window_size > 0,
                kv_cache_type="int8",
                k_quant_type="PER_TENSOR",
                v_quant_type="PER_TENSOR",
                use_attention_metadata=True,
            )
            return paged_attention_func(
                config,
                query,
                key,
                value,
                key_cache,
                value_cache,
                cumulative_seqlens,
                past_seqlens,
                block_table,
                window_size=local_window_size,
                k_scale=k_scale,
                v_scale=v_scale,
            )
 
        with patch.dict(
            os.environ,
            {"ORT_ENABLE_ATTENTION_KERNEL_DEBUG_INFO": "1", "ORT_ENABLE_XQA": "1"},
        ):
            native_debug, native_result = capture_native_stdout_and_result(
                lambda: run(128, native_page_table, native_key_cache, native_value_cache)
            )
            expanded_debug, expanded_result = capture_native_stdout_and_result(
                lambda: run(256, expanded_block_table, expanded_key_cache, expanded_value_cache)
            )
 
        for debug_output, expected_mode in (
            (native_debug, "native"),
            (expanded_debug, "expanded"),
        ):
            self.assertIn("Operator=PagedAttention", debug_output)
            self.assertIn("SdpaKernel=XQA", debug_output)
            self.assertIn(f"XqaPageTable={expected_mode}", debug_output)
 
        native_output, native_key_cache_out, native_value_cache_out = native_result
        expanded_output, expanded_key_cache_out, expanded_value_cache_out = expanded_result
        torch.testing.assert_close(native_output, expanded_output, rtol=0, atol=0)
        torch.testing.assert_close(native_key_cache_out.reshape(-1), expanded_key_cache_out.reshape(-1), rtol=0, atol=0)
        torch.testing.assert_close(
            native_value_cache_out.reshape(-1), expanded_value_cache_out.reshape(-1), rtol=0, atol=0
        )
 
    def test_xqa_batch_one(self):
        self._check_xqa(batch_size=1)
 
    def test_xqa_long_context_multi_block(self):
        # Long enough that XQA splits the sequence and reduces across CTAs through its scratch.
        self._check_xqa(total_sequence_length=8192, batch_size=2)
 
    def test_xqa_short_context(self):
        self._check_xqa(total_sequence_length=8, batch_size=1)
 
    def test_xqa_context_not_page_aligned(self):
        # The live length is not a multiple of 128, so the last page is partially valid.
        self._check_xqa(total_sequence_length=1000)
 
    @parameterized.expand(
        [
            (f"{cache}_{mask}", cache, local)
            for cache in ["float16", "int8"]
            for mask, local in [("full", False), ("local", True)]
        ]
    )
    def test_xqa_non_causal(self, _, kv_cache_type, local):
        with patch.dict(os.environ, {"ORT_ENABLE_XQA_NATIVE_KV": "1"}):
            self._check_xqa(
                kv_cache_type=kv_cache_type,
                quant_type="NONE" if kv_cache_type == "float16" else "PER_TENSOR",
                num_heads=6,
                kv_num_heads=1,
                head_size=256,
                total_sequence_length=128,
                is_causal=False,
                local=local,
                local_window_size=4,
                use_attention_metadata=True,
                past_seqlens_override=torch.tensor([17, 29, 7, 63], dtype=torch.int32),
                expect_xqa=True,
            )
 
    # ---- quantization granularity -------------------------------------------------------
 
    @parameterized.expand(
        [
            ("int8_per_tensor", "int8", "PER_TENSOR"),
            ("int8_per_channel", "int8", "PER_CHANNEL"),
            ("fp8_per_tensor", "fp8", "PER_TENSOR"),
            ("fp8_per_channel", "fp8", "PER_CHANNEL"),
        ]
    )
    def test_xqa_quant_type(self, _, kv_cache_type, quant_type):
        self._check_xqa(kv_cache_type=kv_cache_type, quant_type=quant_type)
 
    @parameterized.expand([("int8", "int8"), ("fp8", "fp8")])
    def test_xqa_large_per_channel_k_scale(self, _, kv_cache_type):
        # Scaling the whole table up to FP32 max leaves its dynamic range intact, which is the shape
        # a calibrated table has. The power-of-two normalizer keeps the fold in range, so this stays
        # on XQA.
        self._check_xqa(
            kv_cache_type=kv_cache_type,
            quant_type="PER_CHANNEL",
            k_scale_max_override=torch.finfo(torch.float32).max,
            expect_xqa=True,
        )
 
    @parameterized.expand([("int8", "int8"), ("fp8", "fp8")])
    def test_per_channel_xqa_opt_out_uses_portable_kernel(self, _, kv_cache_type):
        # ORT_ENABLE_XQA_PER_CHANNEL_KV=0 is the escape hatch for scale tables whose channel range
        # exceeds what folding into an fp16 query can hold.
        self._check_xqa(
            kv_cache_type=kv_cache_type,
            quant_type="PER_CHANNEL",
            expect_xqa=False,
            per_channel_xqa=False,
        )
 
    def test_xqa_mixed_granularity(self):
        # k PER_CHANNEL folds into Q, v PER_TENSOR stays a kernel argument: the two scales take
        # different routes, so an asymmetric config catches a mix-up between them.
        config = self._config(kv_cache_type="int8", k_quant_type="PER_CHANNEL", v_quant_type="PER_TENSOR")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    # ---- masking and score transforms ---------------------------------------------------
 
    def test_xqa_local_window(self):
        self._check_xqa(local=True)
 
    def test_xqa_head_sink(self):
        self._check_xqa(use_head_sink=True)
 
    def test_xqa_head_sink_and_local(self):
        self._check_xqa(use_head_sink=True, local=True)
 
    # ---- prologue interaction -----------------------------------------------------------
 
    def test_xqa_rotary(self):
        self._check_xqa(rotary=True, atol=2e-2)
 
    def test_xqa_rotary_interleaved_and_packed(self):
        self._check_xqa(rotary=True, rotary_interleaved=True, packed=True, atol=2e-2)
 
    def test_xqa_qk_norm_and_slot_mapping(self):
        self._check_xqa(use_qk_norm=True, use_slot_mapping=True, rotary=True, atol=2e-2)
 
    # ---- fallback -----------------------------------------------------------------------
 
    def test_softcap_falls_back(self):
        # XQA has no softcap, so this must land on the portable decode kernel and still be correct.
        self._check_xqa(softcap=50.0)
 
    def test_unsupported_head_size_falls_back(self):
        self._check_xqa(head_size=96)
 
    def test_unsupported_block_size_falls_back(self):
        self._check_xqa(paged_kv_block_size=64)
 
    def test_multi_token_step_falls_back(self):
        # More than one new token in a sequence: without 'attention_metadata' the speculative XQA
        # specialization is not eligible, so this has to use a backend that handles a ragged step.
        config = self._config(
            sequence_length=2, kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR"
        )
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
 
@unittest.skipIf(not has_xqa(), reason="XQA requires an SM80 or newer GPU")
class TestPagedAttentionXqaSpeculative(unittest.TestCase):
    """Coverage for the multi-token (speculative decoding) paged XQA specialization.
 
    Head size 256 / group size 6 / 2..8 new tokens per sequence routes a speculative verification
    step onto XQA with a packed lower-triangular mask instead of the ragged fallback. The mask is
    the whole point of these tests: a kernel that ignores it lets a draft token attend to its own
    future, which stays inside a loose tolerance when K and V barely vary with position.
    `parity_check_paged_attention` uses random K/V and a torch reference, so a dropped mask shows
    up as a large error on every row except the last."""
 
    def setUp(self):
        torch.manual_seed(0)
 
    def _check(
        self,
        new_seqlens=None,
        rtol=5e-3,
        atol=5e-3,
        expect_xqa=None,
        local_window_size=None,
        past_seqlens=None,
        **overrides,
    ):
        kwargs = {
            "batch_size": 4,
            "sequence_length": 8,
            "total_sequence_length": 1024,
            "num_heads": 6,
            "kv_num_heads": 1,
            "head_size": 256,
            "paged_kv_block_size": 256,
            "local": False,
            "rotary": False,
            "rotary_interleaved": False,
            "packed": False,
            "softcap": 0.0,
        }
        features = {k: overrides.pop(k) for k in list(overrides) if k not in kwargs}
        kwargs.update(overrides)
        config = Config(**kwargs)
        for key, value in {
            "kv_cache_type": "int8",
            "k_quant_type": "PER_TENSOR",
            "v_quant_type": "PER_TENSOR",
            "use_attention_metadata": True,
            **features,
        }.items():
            setattr(config, key, value)
        override = None
        if new_seqlens is not None:
            override = torch.tensor(new_seqlens, dtype=torch.int32)
 
        def run():
            parity_check_paged_attention(
                config,
                rtol=rtol,
                atol=atol,
                new_seqlens_override=override,
                local_window_size_override=local_window_size,
                past_seqlens_override=torch.tensor(past_seqlens, dtype=torch.int32)
                if past_seqlens is not None
                else None,
            )
 
        # Output parity alone would still pass if a dispatch regression routed the case to the
        # ragged fallback, leaving the mask, page-table and scale paths untested. Assert the
        # selected backend wherever the case is meant to prove speculative XQA behavior.
        if expect_xqa is None:
            run()
            return
        with patch.dict(
            os.environ,
            {"ORT_ENABLE_ATTENTION_KERNEL_DEBUG_INFO": "1", "ORT_ENABLE_XQA": "1"},
        ):
            debug_output = capture_native_stdout(run)
        if expect_xqa:
            self.assertIn("SdpaKernel=XQA", debug_output)
        else:
            self.assertNotIn("SdpaKernel=XQA", debug_output)
 
    @parameterized.expand([(f"q{q}", q) for q in range(2, 9)])
    def test_spec_dec_query_length(self, _, query_length):
        self._check(sequence_length=query_length, new_seqlens=[query_length] * 4)
 
    @parameterized.expand([("int8", "int8"), ("native_fp16", "float16")])
    def test_spec_dec_dispatches_to_xqa(self, _, kv_cache_type):
        is_native_cache = kv_cache_type == "float16"
        quant = "NONE" if kv_cache_type == "float16" else "PER_TENSOR"
        config = Config(4, 8, 1024, 6, 1, 256, 256, False, False, False, False, 0.0)
        for key, value in {
            "kv_cache_type": kv_cache_type,
            "k_quant_type": quant,
            "v_quant_type": quant,
            "use_attention_metadata": True,
        }.items():
            setattr(config, key, value)
        with patch.dict(
            os.environ,
            {
                "ORT_ENABLE_ATTENTION_KERNEL_DEBUG_INFO": "1",
                "ORT_ENABLE_XQA": "1",
                "ORT_ENABLE_XQA_NATIVE_KV": "1" if is_native_cache else "0",
            },
        ):
            debug_output = capture_native_stdout(
                lambda: parity_check_paged_attention(
                    config, rtol=5e-3, atol=5e-3, new_seqlens_override=torch.tensor([8, 8, 8, 8], dtype=torch.int32)
                )
            )
        self.assertIn("SdpaKernel=XQA", debug_output)
 
        if is_native_cache:
            with patch.dict(
                os.environ,
                {
                    "ORT_ENABLE_ATTENTION_KERNEL_DEBUG_INFO": "1",
                    "ORT_ENABLE_XQA": "1",
                    "ORT_ENABLE_XQA_NATIVE_KV": "0",
                },
            ):
                debug_output = capture_native_stdout(
                    lambda: parity_check_paged_attention(
                        config,
                        rtol=5e-3,
                        atol=5e-3,
                        new_seqlens_override=torch.tensor([8, 8, 8, 8], dtype=torch.int32),
                    )
                )
            self.assertNotIn("SdpaKernel=XQA", debug_output)
            self.assertIn("SdpaKernel=FLASH_ATTENTION", debug_output)
 
    @parameterized.expand(
        [
            ("ragged", [1, 8, 3, 8]),
            ("inactive", [0, 0, 0, 7]),
            ("uniform2", [2, 2, 2, 2]),
            # token_count (2) <= batch_size (4): the gate is the metadata query bound, not the
            # aggregate token count, so this still routes to the speculative kernel.
            ("fewer_tokens_than_sequences", [0, 0, 0, 2]),
        ]
    )
    def test_spec_dec_ragged_batch(self, _, new_seqlens):
        # A continuous-batching step mixes acceptance lengths, and a scheduled sequence may
        # contribute no token at all.
        self._check(new_seqlens=new_seqlens, expect_xqa=True)
 
    @parameterized.expand(
        [
            (f"{cache}_{mask}", cache, local)
            for cache in ["float16", "int8"]
            for mask, local in [("full", False), ("local", True)]
        ]
    )
    def test_spec_dec_non_causal_ragged(self, _, kv_cache_type, local):
        # Eight tokens at group size six cross XQA's 32-row tile; W=4 must not mask future tokens.
        quant_type = "NONE" if kv_cache_type == "float16" else "PER_TENSOR"
        with patch.dict(os.environ, {"ORT_ENABLE_XQA_NATIVE_KV": "1"}):
            self._check(
                kv_cache_type=kv_cache_type,
                k_quant_type=quant_type,
                v_quant_type=quant_type,
                total_sequence_length=128,
                new_seqlens=[1, 8, 0, 3],
                past_seqlens=[17, 29, 7, 0],
                is_causal=False,
                local=local,
                local_window_size=4 if local else None,
                expect_xqa=True,
            )
 
    @parameterized.expand([("64", 64), ("256", 256), ("1000", 1000), ("8192", 8192)])
    def test_spec_dec_context_length(self, _, total_sequence_length):
        # 8192 splits the sequence across CTAs and reduces through the XQA scratch; 1000 is not
        # page aligned, so the masked tail straddles the last two tiles.
        self._check(batch_size=2, total_sequence_length=total_sequence_length, new_seqlens=[8, 8], expect_xqa=True)
 
    @parameterized.expand([("128", 128), ("512", 512)])
    def test_spec_dec_block_size(self, _, block_size):
        self._check(batch_size=2, paged_kv_block_size=block_size, new_seqlens=[8, 8], expect_xqa=True)
 
    def test_spec_dec_per_channel_scales(self):
        self._check(k_quant_type="PER_CHANNEL", v_quant_type="PER_CHANNEL", expect_xqa=True)
 
    def test_spec_dec_batch_one(self):
        self._check(batch_size=1, new_seqlens=[8], expect_xqa=True)
 
    @parameterized.expand([(f"q{q}", q) for q in range(6, 9)])
    def test_spec_dec_local_window(self, _, query_length):
        # 6..8 query tokens with group size 6 spill past the 32-row tile, so the second tile has to
        # derive each row's window from its own query position instead of the tile offset.
        self._check(
            batch_size=2,
            sequence_length=query_length,
            total_sequence_length=1024,
            new_seqlens=[query_length, query_length],
            local=True,
            local_window_size=64,
            expect_xqa=True,
        )
 
    @parameterized.expand([(f"q{q}", q) for q in range(6, 9)])
    def test_spec_dec_head_sink(self, _, query_length):
        # Rows are flattened (token, head) pairs here, so every row past the first tile must still
        # pick up its own head's sink.
        self._check(
            batch_size=2,
            sequence_length=query_length,
            new_seqlens=[query_length, query_length],
            use_head_sink=True,
            expect_xqa=True,
        )
 
    def test_spec_dec_head_sink_and_local(self):
        self._check(
            batch_size=2,
            new_seqlens=[8, 8],
            use_head_sink=True,
            local=True,
            local_window_size=64,
            expect_xqa=True,
        )
 
    def test_spec_dec_native_fp16_cache(self):
        with patch.dict(os.environ, {"ORT_ENABLE_XQA_NATIVE_KV": "1"}):
            self._check(kv_cache_type="float16", k_quant_type="NONE", v_quant_type="NONE", expect_xqa=True)
 
    def test_bound_above_specialization_falls_back(self):
        # A query bound of 9 is outside the 2..8 window, so this must land on the ragged backend
        # and still be correct.
        self._check(sequence_length=9, new_seqlens=[9] * 4, expect_xqa=False)
 
 
@unittest.skipIf(not has_cuda_device(), reason="CUDA is not available, skipping tests.")
class TestPagedAttentionAttentionMetadata(unittest.TestCase):
    """Coverage for the optional 'attention_metadata' input.
 
    'cumulative_sequence_length' and 'past_seqlens' are device tensors, but the op needs an upper
    bound on the query length (to size grids) and on the KV length (to size workspaces) on the host.
    Without this input it falls back to the static capacities, and in two narrow prefill-side cases
    -- a dense gather, or XQA, which needs proof of exactly one token per sequence -- it copies the
    cumulative arrays back and blocks the stream instead. 'attention_metadata' supplies both bounds
    in CPU memory so neither ever happens.
 
    It is purely an optimization, so the contract under test is that it changes nothing: every case
    here mirrors a config that is also covered without the input and must produce the same results.
    The cases span the backends because they consume the bounds differently."""
 
    def setUp(self):
        torch.manual_seed(0)
 
    def _config(self, **overrides):
        kwargs = {
            "batch_size": 4,
            "sequence_length": 1,
            "total_sequence_length": 1024,
            "num_heads": 8,
            "kv_num_heads": 2,
            "head_size": 64,
            "paged_kv_block_size": 256,
            "local": False,
            "rotary": False,
            "rotary_interleaved": False,
            "packed": False,
            "softcap": 0.0,
        }
        feature_overrides = {k: overrides.pop(k) for k in list(overrides) if k not in kwargs}
        kwargs.update(overrides)
        config = Config(**kwargs)
        config.use_attention_metadata = True
        for key, value in feature_overrides.items():
            setattr(config, key, value)
        return config
 
    def test_prefill_flash_attention(self):
        # A prefill bound is > 1, so it only sizes the FlashAttention grid; the input must not
        # perturb anything there either.
        parity_check_paged_attention(self._config(sequence_length=256, total_sequence_length=256))
 
    def test_decode_unquantized(self):
        parity_check_paged_attention(self._config(), sdpa_kernel=SDPA_KERNEL_DECODER_ATTENTION)
 
    def test_decode_xqa_int8(self):
        config = self._config(kv_cache_type="int8", k_quant_type="PER_CHANNEL", v_quant_type="PER_CHANNEL")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    @unittest.skipIf(not has_fp8_kv_cache(), reason="FP8 KV cache kernels are not built")
    def test_decode_xqa_fp8(self):
        config = self._config(kv_cache_type="fp8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        parity_check_paged_attention(config, rtol=5e-2, atol=5e-2)
 
    def test_decode_softcap_portable_kernel(self):
        # softcap rules out XQA, so this exercises the split-KV decode kernel, whose split count is
        # derived from max_kv_len -- here from the bound rather than from a readback.
        config = self._config(kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR", softcap=50.0)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_decode_local_window(self):
        config = self._config(local=True, kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_chunked_prefill_dense_gather(self):
        # A quantized cache on a multi-token step gathers the live context into a dense buffer. With
        # a bound available that buffer is sized by batch_size * max_kv_len_bound instead of the
        # exact total_kv_tokens, so the gather kernel has to tolerate indices past the real end of
        # the packed layout.
        config = self._config(
            sequence_length=8,
            kv_cache_type="int8",
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_TENSOR",
        )
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_ragged_new_token_counts(self):
        # token_count == batch_size even though one sequence contributes two tokens and another
        # none. The shape test alone selects a decode-shaped backend, so every backend it can reach
        # must handle the raggedness.
        new_seqlens = torch.tensor([2, 0, 1, 1], dtype=torch.int32)
        parity_check_paged_attention(self._config(sequence_length=2), new_seqlens_override=new_seqlens)
 
    def test_ragged_new_token_counts_decode_kernel(self):
        # Same step, pinned to the paged decode kernel: with a bound of 2 there is no readback, so
        # the kernel is the only thing that knows the tokens are unevenly distributed.
        new_seqlens = torch.tensor([2, 0, 1, 1], dtype=torch.int32)
        parity_check_paged_attention(
            self._config(sequence_length=2),
            new_seqlens_override=new_seqlens,
            sdpa_kernel=SDPA_KERNEL_DECODER_ATTENTION,
            rtol=5e-3,
            atol=5e-3,
        )
 
    def test_zero_new_tokens_in_batch(self):
        # token_count < batch_size: still decode-shaped, but XQA is excluded because it would emit a
        # row for the sequence that contributed nothing.
        new_seqlens = torch.tensor([1, 0, 1, 1], dtype=torch.int32)
        parity_check_paged_attention(self._config(), new_seqlens_override=new_seqlens)
 
    def test_batch_one(self):
        parity_check_paged_attention(self._config(batch_size=1), sdpa_kernel=SDPA_KERNEL_DECODER_ATTENTION)
 
    def test_negative_entry_is_rejected(self):
        config = self._config()
        config.attention_metadata_override = numpy.array([-1, 1024], dtype=numpy.int32)
        with self.assertRaises(Exception) as ctx:
            parity_check_paged_attention(config)
        self.assertIn("must be non-negative", str(ctx.exception))
 
    def test_unknown_bounds_fall_back_to_readback(self):
        # All-zero means "no bound", which must behave exactly like supplying the static capacities.
        config = self._config(kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        config.attention_metadata_override = numpy.array([0, 0], dtype=numpy.int32)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
    def test_over_large_bounds_are_clamped(self):
        # Bounds beyond the static limits are legal (they are still upper bounds) and must be
        # clamped rather than used to size an allocation.
        config = self._config(kv_cache_type="int8", k_quant_type="PER_TENSOR", v_quant_type="PER_TENSOR")
        config.attention_metadata_override = numpy.array([1 << 20, 1 << 20], dtype=numpy.int32)
        parity_check_paged_attention(config, rtol=5e-3, atol=5e-3)
 
 
####################################################################################################
# Multi-head Latent Attention (kv_cache_layout="LATENT")
#
# See docs/contrib_ops/cuda/paged_attention.md §12. In the absorbed form there is a single physical
# cache holding the latent row [compressed_kv | k_pe] of width head_size = kv_lora_rank +
# qk_rope_head_dim. K is the whole row; V of every head is its leading v_head_size = kv_lora_rank
# channels. 'value' and 'value_cache' are therefore absent and kv_num_heads is 1.
####################################################################################################
 
 
class MLAConfig:
    """Shape bundle for a LATENT-layout PagedAttention node. Deliberately separate from Config,
    whose fields (kv_num_heads, packed, ...) encode SEPARATE-mode assumptions."""
 
    def __init__(
        self,
        batch_size,
        num_heads,
        kv_lora_rank,
        qk_rope_head_dim,
        block_size,
        qk_nope_head_dim=None,
        kv_cache_type="float16",
        k_quant_type="NONE",
        is_causal=True,
    ):
        self.batch_size = batch_size
        self.num_heads = num_heads
        self.kv_lora_rank = kv_lora_rank
        self.qk_rope_head_dim = qk_rope_head_dim
        # Absorbed geometry, i.e. what the op actually sees.
        self.head_size = kv_lora_rank + qk_rope_head_dim
        self.v_head_size = kv_lora_rank
        self.rotary_offset = kv_lora_rank
        self.kv_num_heads = 1
        self.block_size = block_size
        # Un-absorbed geometry, used only by the equivalence test.
        self.qk_nope_head_dim = qk_nope_head_dim
        self.kv_cache_type = kv_cache_type
        self.k_quant_type = k_quant_type
        self.is_causal = is_causal
 
    @property
    def softmax_scale(self):
        # DeepSeek scales by the pre-absorption QK width, which is nope + rope, NOT the absorbed
        # head_size. This is exactly why the op requires an explicit 'scale' for MLA.
        width = (self.qk_nope_head_dim or self.kv_lora_rank) + self.qk_rope_head_dim
        return width**-0.5
 
 
def create_mla_graph(
    mla_config,
    num_tokens,
    num_blocks,
    max_blocks_per_sequence,
    do_rotary=False,
    rotary_interleaved=False,
    rotary_offset=None,
    scale=None,
    local_window_size=-1,
    softcap=0.0,
    with_value=False,
    with_value_cache=False,
    with_value_cache_out=False,
    with_head_sink=False,
    with_qk_norm=False,
    kv_cache_layout="LATENT",
    v_head_size=None,
):
    """Build a single-node LATENT PagedAttention model. Every deviation from a valid MLA graph is a
    keyword here so that the negative tests can construct rejected models."""
    cache_proto_type = KV_CACHE_TENSOR_PROTO[mla_config.kv_cache_type]
    head_size = mla_config.head_size
    v_head_size = mla_config.v_head_size if v_head_size is None else v_head_size
    rotary_offset = mla_config.rotary_offset if rotary_offset is None else rotary_offset
    rotary_dim = mla_config.qk_rope_head_dim
 
    attrs = {
        "num_heads": mla_config.num_heads,
        "kv_num_heads": mla_config.kv_num_heads,
        "kv_cache_layout": kv_cache_layout,
        "v_head_size": v_head_size,
        "local_window_size": local_window_size,
        "softcap": softcap,
        "domain": "com.microsoft",
    }
    if scale is not None:
        attrs["scale"] = scale
    if not mla_config.is_causal:
        attrs["is_causal"] = 0
    if do_rotary:
        attrs["do_rotary"] = 1
        attrs["rotary_interleaved"] = 1 if rotary_interleaved else 0
        attrs["rotary_offset"] = rotary_offset
    if mla_config.k_quant_type != "NONE":
        attrs["k_quant_type"] = mla_config.k_quant_type
 
    node_outputs = ["output", "key_cache_out"]
    if with_value_cache_out:
        node_outputs.append("value_cache_out")
 
    nodes = [
        helper.make_node(
            "PagedAttention",
            [
                "query",
                "key",
                "value" if with_value else "",
                "key_cache",
                "value_cache" if with_value_cache else "",
                "cumulative_sequence_length",
                "past_seqlens",
                "block_table",
                "cos_cache" if do_rotary else "",
                "sin_cache" if do_rotary else "",
                "",  # slot_mapping
                "head_sink" if with_head_sink else "",
                "q_norm_weight" if with_qk_norm else "",
                "k_norm_weight" if with_qk_norm else "",
                "k_scale" if mla_config.k_quant_type != "NONE" else "",
            ],
            node_outputs,
            "PagedAttention_MLA",
            **attrs,
        ),
    ]
 
    cache_dims = [num_blocks, mla_config.block_size, mla_config.kv_num_heads, head_size]
    graph_input = [
        helper.make_tensor_value_info("query", TensorProto.FLOAT16, [num_tokens, mla_config.num_heads * head_size]),
        helper.make_tensor_value_info("key", TensorProto.FLOAT16, [num_tokens, mla_config.kv_num_heads * head_size]),
        helper.make_tensor_value_info("key_cache", cache_proto_type, cache_dims),
        helper.make_tensor_value_info("cumulative_sequence_length", TensorProto.INT32, [mla_config.batch_size + 1]),
        helper.make_tensor_value_info("past_seqlens", TensorProto.INT32, [mla_config.batch_size]),
        helper.make_tensor_value_info(
            "block_table", TensorProto.INT32, [mla_config.batch_size, max_blocks_per_sequence]
        ),
    ]
    if with_value:
        # SEPARATE mode requires value to match key's hidden size; in LATENT its mere presence is
        # the violation under test.
        graph_input.append(
            helper.make_tensor_value_info(
                "value", TensorProto.FLOAT16, [num_tokens, mla_config.kv_num_heads * head_size]
            )
        )
    if with_value_cache:
        graph_input.append(helper.make_tensor_value_info("value_cache", cache_proto_type, cache_dims))
    if do_rotary:
        # The rotary caches are indexed by rotary_dim // 2, and the op derives rotary_dim from their
        # width. MLA rotates only the qk_rope_head_dim suffix, so these are much narrower than the
        # head_size-derived caches a full-width RoPE would use.
        cache_width = rotary_dim // 2
        graph_input += [
            helper.make_tensor_value_info("cos_cache", TensorProto.FLOAT16, [None, cache_width]),
            helper.make_tensor_value_info("sin_cache", TensorProto.FLOAT16, [None, cache_width]),
        ]
    if with_head_sink:
        graph_input.append(helper.make_tensor_value_info("head_sink", TensorProto.FLOAT16, [mla_config.num_heads]))
    if with_qk_norm:
        graph_input += [
            helper.make_tensor_value_info("q_norm_weight", TensorProto.FLOAT16, [head_size]),
            helper.make_tensor_value_info("k_norm_weight", TensorProto.FLOAT16, [head_size]),
        ]
    if mla_config.k_quant_type != "NONE":
        scale_shape = [1] if mla_config.k_quant_type == "PER_TENSOR" else [mla_config.kv_num_heads, 1, head_size]
        graph_input.append(helper.make_tensor_value_info("k_scale", TensorProto.FLOAT, scale_shape))
 
    graph_output = [
        helper.make_tensor_value_info("output", TensorProto.FLOAT16, [num_tokens, mla_config.num_heads * v_head_size]),
        helper.make_tensor_value_info("key_cache_out", cache_proto_type, cache_dims),
    ]
    if with_value_cache_out:
        graph_output.append(helper.make_tensor_value_info("value_cache_out", cache_proto_type, cache_dims))
 
    graph = helper.make_graph(nodes, "PagedAttention_MLA_Graph", graph_input, graph_output)
    return helper.make_model(graph).SerializeToString()
 
 
def run_mla(
    mla_config,
    query,
    key,
    key_cache,
    cumulative_sequence_length,
    past_seqlens,
    block_table,
    cos=None,
    sin=None,
    k_scale=None,
    **graph_kwargs,
):
    """Run a LATENT PagedAttention model and return (output, key_cache) with the cache updated in
    place. key_cache is bound on device so the in-place scatter is observable."""
    num_tokens = int(cumulative_sequence_length[-1].item())
    onnx_model_str = create_mla_graph(
        mla_config,
        num_tokens,
        key_cache.shape[0],
        block_table.shape[1],
        do_rotary=cos is not None,
        **graph_kwargs,
    )
    ort_session = InferenceSession(onnx_model_str, SessionOptions(), providers=["CUDAExecutionProvider"])
    io_binding = ort_session.io_binding()
 
    io_binding.bind_cpu_input("query", query.detach().cpu().numpy())
    io_binding.bind_cpu_input("key", key.detach().cpu().numpy())
    io_binding.bind_cpu_input("cumulative_sequence_length", cumulative_sequence_length.detach().cpu().numpy())
    io_binding.bind_cpu_input("past_seqlens", past_seqlens.detach().cpu().numpy())
    io_binding.bind_cpu_input("block_table", block_table.detach().cpu().numpy())
    if cos is not None:
        io_binding.bind_cpu_input("cos_cache", cos.detach().cpu().numpy())
        io_binding.bind_cpu_input("sin_cache", sin.detach().cpu().numpy())
    if k_scale is not None:
        io_binding.bind_cpu_input("k_scale", k_scale.detach().cpu().numpy())
 
    cache_proto_type = KV_CACHE_TENSOR_PROTO[mla_config.kv_cache_type]
    key_cache = key_cache.contiguous()
    io_binding.bind_input("key_cache", "cuda", 0, cache_proto_type, tuple(key_cache.shape), key_cache.data_ptr())
    io_binding.bind_output("output")
    io_binding.bind_output("key_cache_out", "cuda", 0, cache_proto_type, tuple(key_cache.shape), key_cache.data_ptr())
    ort_session.run_with_iobinding(io_binding)
    output = torch.tensor(numpy.array(io_binding.copy_outputs_to_cpu()[0]))
    return output, key_cache
 
 
def mla_reference(
    mla_config,
    query,  # [token_count, num_heads, head_size]
    latent_cache,  # [batch, total_seqlen, head_size] dense view of the paged cache
    past_seqlens,
    new_seqlens,
    cum_seqlens,
    scale,
    local_window_size=-1,
    softcap=0.0,
):
    """Straightforward fp32 MLA: K is the whole latent row, V its leading v_head_size channels."""
    v_head_size = mla_config.v_head_size
    token_count = int(cum_seqlens[-1].item())
    out = torch.zeros(token_count, mla_config.num_heads, v_head_size, dtype=torch.float32, device="cuda")
    q = query.to(torch.float32)
    for b in range(mla_config.batch_size):
        start = int(cum_seqlens[b].item())
        for j in range(int(new_seqlens[b].item())):
            query_end = int(past_seqlens[b].item()) + j + 1
            kv_end = query_end if mla_config.is_causal else int((past_seqlens[b] + new_seqlens[b]).item())
            kv_begin = max(0, query_end - local_window_size) if local_window_size > 0 else 0
            k = latent_cache[b, kv_begin:kv_end].to(torch.float32)  # [L, head_size]
            v = k[:, :v_head_size]
            logits = torch.einsum("nh,lh->nl", q[start + j], k) * scale
            if softcap > 0.0:
                logits = softcap * torch.tanh(logits / softcap)
            probs = torch.softmax(logits, dim=-1)
            out[start + j] = torch.einsum("nl,lv->nv", probs, v)
    return out
 
 
def make_mla_batch(mla_config, past_seqlens, new_seqlens, device="cuda"):
    """Allocate a shuffled paged latent cache pre-filled with the 'past' tokens, plus the block
    table and cumulative sequence lengths. Returns everything both paged and densified."""
    total_seqlens = past_seqlens + new_seqlens
    max_total = int(total_seqlens.max().item())
    blocks_per_seq = math.ceil(max_total / mla_config.block_size)
    num_blocks = blocks_per_seq * mla_config.batch_size
    # A shuffled permutation makes block-table indirection load-bearing: a kernel that ignored it
    # and read blocks sequentially would fail.
    block_table = torch.randperm(num_blocks, dtype=torch.int32, device=device).reshape(
        mla_config.batch_size, blocks_per_seq
    )
    latent_paged = torch.randn(
        num_blocks,
        mla_config.block_size,
        mla_config.kv_num_heads,
        mla_config.head_size,
        device=device,
        dtype=torch.float16,
    )
    cum_seqlens = torch.zeros(mla_config.batch_size + 1, dtype=torch.int32, device=device)
    cum_seqlens[1:] = torch.cumsum(new_seqlens, dim=0)
    return latent_paged, block_table, cum_seqlens, blocks_per_seq * mla_config.block_size
 
 
def densify_latent(mla_config, latent_paged, block_table, total_len):
    return rearrange(
        latent_paged[block_table.to(dtype=torch.long).flatten()],
        "(b nblocks) block_size h d -> b (nblocks block_size) (h d)",
        b=mla_config.batch_size,
    )[:, :total_len]
 
 
def apply_offset_rope(x, cos, sin, positions, rotary_offset, rotary_dim, interleaved):
    """Reference for the 'rotary_offset' attribute: rotate x[..., offset:offset+rotary_dim] using
    the same half-rotated / interleaved conventions as the op, copying everything else through."""
    out = x.clone().to(torch.float32)
    seg = out[..., rotary_offset : rotary_offset + rotary_dim]
    c = cos[positions].to(torch.float32)  # [tokens, rotary_dim // 2]
    s = sin[positions].to(torch.float32)
    c = c[..., : rotary_dim // 2]
    s = s[..., : rotary_dim // 2]
    while c.dim() < seg.dim():
        c = c.unsqueeze(-2)
        s = s.unsqueeze(-2)
    if interleaved:
        even = seg[..., 0::2]
        odd = seg[..., 1::2]
        rotated = torch.stack([even * c - odd * s, even * s + odd * c], dim=-1).flatten(-2)
    else:
        half = rotary_dim // 2
        x1 = seg[..., :half]
        x2 = seg[..., half:]
        rotated = torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1)
    out[..., rotary_offset : rotary_offset + rotary_dim] = rotated
    return out.to(x.dtype)
 
 
@unittest.skipIf(not has_cuda_device(), reason="CUDA is not available, skipping tests.")
class TestPagedAttentionMLA(unittest.TestCase):
    """Correctness of kv_cache_layout='LATENT' (design doc §12, phase P4)."""
 
    def setUp(self):
        # These tests build random weights; a fixed seed keeps them order-independent.
        torch.manual_seed(20240727)
 
    def _config(self, **kwargs):
        # Small but structurally faithful: kv_lora_rank and qk_rope_head_dim keep DeepSeek's ratio
        # while staying cheap enough for a unit test.
        defaults = dict(batch_size=2, num_heads=4, kv_lora_rank=64, qk_rope_head_dim=32, block_size=16)
        defaults.update(kwargs)
        return MLAConfig(**defaults)
 
    def _run_case(self, mla_config, past_seqlens, new_seqlens, local_window_size=-1, softcap=0.0):
        """Shared body: build a paged latent cache, run the op, compare against mla_reference."""
        device = "cuda"
        past_seqlens = torch.tensor(past_seqlens, dtype=torch.int32, device=device)
        new_seqlens = torch.tensor(new_seqlens, dtype=torch.int32, device=device)
        latent_paged, block_table, cum_seqlens, total_len = make_mla_batch(mla_config, past_seqlens, new_seqlens)
        token_count = int(cum_seqlens[-1].item())
 
        query = torch.randn(token_count, mla_config.num_heads, mla_config.head_size, device=device, dtype=torch.float16)
        new_key = torch.randn(token_count, mla_config.head_size, device=device, dtype=torch.float16)
 
        scale = mla_config.softmax_scale
        out, latent_paged = run_mla(
            mla_config,
            query.reshape(token_count, -1),
            new_key,
            latent_paged,
            cum_seqlens,
            past_seqlens,
            block_table,
            scale=scale,
            local_window_size=local_window_size,
            softcap=softcap,
        )
 
        # The op scattered the new keys into the cache in place, so densifying afterwards gives the
        # exact K/V the reference must see (including any quantization error).
        dense = densify_latent(mla_config, latent_paged, block_table, total_len)
        ref = mla_reference(
            mla_config,
            query,
            dense,
            past_seqlens,
            new_seqlens,
            cum_seqlens,
            scale,
            local_window_size=local_window_size,
            softcap=softcap,
        )
        out = out.reshape(token_count, mla_config.num_heads, mla_config.v_head_size).to(device).to(torch.float32)
        torch.testing.assert_close(out, ref, rtol=2e-3, atol=2e-3)
        return out
 
    def test_prefill(self):
        config = self._config()
        self._run_case(config, past_seqlens=[0, 0], new_seqlens=[13, 7])
 
    def test_decode(self):
        config = self._config()
        self._run_case(config, past_seqlens=[31, 18], new_seqlens=[1, 1])
 
    def test_chunked_prefill(self):
        # Mixed batch: one sequence extends an existing cache, one is pure decode, one adds nothing.
        config = self._config(batch_size=3)
        self._run_case(config, past_seqlens=[20, 9, 5], new_seqlens=[6, 1, 0])
 
    @parameterized.expand(
        [
            (f"{step}_{mask}", cached, local)
            for step, cached in [("prefill", False), ("cached", True)]
            for mask, local in [("full", False), ("local", True)]
        ]
    )
    def test_non_causal_ragged(self, _, cached, local):
        self._run_case(
            self._config(batch_size=4, is_causal=False),
            past_seqlens=[17, 129, 7, 63] if cached else [0, 0, 0, 0],
            new_seqlens=[1, 8, 0, 3],
            local_window_size=4 if local else -1,
        )
 
    def test_local_window(self):
        config = self._config()
        self._run_case(config, past_seqlens=[24, 24], new_seqlens=[5, 5], local_window_size=8)
 
    def test_softcap(self):
        config = self._config()
        self._run_case(config, past_seqlens=[12, 12], new_seqlens=[4, 4], softcap=30.0)
 
    def test_deepseek_v3_geometry(self):
        # The real absorbed shape: head_size 576, v_head_size 512, kv_num_heads 1.
        config = self._config(num_heads=8, kv_lora_rank=512, qk_rope_head_dim=64, block_size=16)
        self.assertEqual(config.head_size, 576)
        self.assertEqual(config.v_head_size, 512)
        self._run_case(config, past_seqlens=[17, 3], new_seqlens=[1, 4])
 
    def test_absorbed_matches_non_absorbed(self):
        """The point of MLA: attention over the latent row with absorbed projections equals
        standard MHA over the up-projected K/V. Both sides run through PagedAttention, so this also
        pins the LATENT path against the already-verified SEPARATE path."""
        device = "cuda"
        batch_size, num_heads = 2, 4
        kv_lora_rank, qk_rope_head_dim = 64, 32
        qk_nope_head_dim, v_head_dim = 32, 32
        mla_config = MLAConfig(
            batch_size,
            num_heads,
            kv_lora_rank,
            qk_rope_head_dim,
            block_size=16,
            qk_nope_head_dim=qk_nope_head_dim,
        )
        past_seqlens = torch.tensor([9, 5], dtype=torch.int32, device=device)
        new_seqlens = torch.tensor([4, 6], dtype=torch.int32, device=device)
        latent_paged, block_table, cum_seqlens, total_len = make_mla_batch(mla_config, past_seqlens, new_seqlens)
        token_count = int(cum_seqlens[-1].item())
        scale = mla_config.softmax_scale
 
        # Up-projection weights, shared by both spellings.
        w_uk = torch.randn(kv_lora_rank, num_heads, qk_nope_head_dim, device=device, dtype=torch.float32) * 0.1
        w_uv = torch.randn(kv_lora_rank, num_heads, v_head_dim, device=device, dtype=torch.float32) * 0.1
 
        # Non-absorbed query: q_nope [N, qk_nope_head_dim] and q_pe [N, qk_rope_head_dim].
        q_nope = torch.randn(token_count, num_heads, qk_nope_head_dim, device=device, dtype=torch.float32) * 0.5
        q_pe = torch.randn(token_count, num_heads, qk_rope_head_dim, device=device, dtype=torch.float32) * 0.5
        new_key = torch.randn(token_count, mla_config.head_size, device=device, dtype=torch.float16)
 
        # --- absorbed: q_latent = [q_nope @ W_UK^T | q_pe], attention over the latent row ---
        q_absorbed_nope = torch.einsum("tnp,cnp->tnc", q_nope, w_uk)  # [T, N, kv_lora_rank]
        q_absorbed = torch.cat([q_absorbed_nope, q_pe], dim=-1).to(torch.float16)
        out_absorbed, latent_paged = run_mla(
            mla_config,
            q_absorbed.reshape(token_count, -1),
            new_key,
            latent_paged,
            cum_seqlens,
            past_seqlens,
            block_table,
            scale=scale,
        )
        out_absorbed = out_absorbed.reshape(token_count, num_heads, kv_lora_rank).to(device).to(torch.float32)
        # Absorbed output lives in latent space; project it out with W_UV to compare.
        out_absorbed = torch.einsum("tnc,cnv->tnv", out_absorbed, w_uv)
 
        # --- non-absorbed: up-project the cache into per-head K/V and run plain MHA ---
        dense = densify_latent(mla_config, latent_paged, block_table, total_len).to(torch.float32)
        compressed_kv = dense[..., :kv_lora_rank]  # [B, L, kv_lora_rank]
        k_pe = dense[..., kv_lora_rank:]  # [B, L, qk_rope_head_dim]
        k_nope = torch.einsum("blc,cnp->blnp", compressed_kv, w_uk)
        k_full = torch.cat([k_nope, k_pe.unsqueeze(2).expand(-1, -1, num_heads, -1)], dim=-1)
        v_full = torch.einsum("blc,cnv->blnv", compressed_kv, w_uv)
        q_full = torch.cat([q_nope, q_pe], dim=-1)
 
        out_ref = torch.zeros(token_count, num_heads, v_head_dim, dtype=torch.float32, device=device)
        for b in range(batch_size):
            start = int(cum_seqlens[b].item())
            for j in range(int(new_seqlens[b].item())):
                kv_end = int(past_seqlens[b].item()) + j + 1
                logits = torch.einsum("nd,lnd->nl", q_full[start + j], k_full[b, :kv_end]) * scale
                probs = torch.softmax(logits, dim=-1)
                out_ref[start + j] = torch.einsum("nl,lnv->nv", probs, v_full[b, :kv_end])
 
        torch.testing.assert_close(out_absorbed, out_ref, rtol=5e-3, atol=5e-3)
 
    def test_rotary_offset_matches_graph_applied_rope(self):
        """do_rotary=1 with rotary_offset=kv_lora_rank must equal applying the same RoPE to the
        k_pe suffix outside the op and running with do_rotary=0."""
        device = "cuda"
        for interleaved in (False, True):
            with self.subTest(interleaved=interleaved):
                config = self._config()
                past_seqlens = torch.tensor([6, 2], dtype=torch.int32, device=device)
                new_seqlens = torch.tensor([3, 5], dtype=torch.int32, device=device)
                latent_paged, block_table, cum_seqlens, total_len = make_mla_batch(config, past_seqlens, new_seqlens)
                token_count = int(cum_seqlens[-1].item())
                rotary_dim = config.qk_rope_head_dim
                cache_width = rotary_dim // 2
                max_pos = 128
                angle = torch.rand(max_pos, cache_width, device=device) * 2 - 1
                cos = torch.cos(angle).to(torch.float16)
                sin = torch.sin(angle).to(torch.float16)
 
                query = torch.randn(token_count, config.num_heads, config.head_size, device=device, dtype=torch.float16)
                new_key = torch.randn(token_count, config.head_size, device=device, dtype=torch.float16)
                scale = config.softmax_scale
 
                # Positions the op uses: past_seqlens[b] + index within the sequence.
                positions = torch.empty(token_count, dtype=torch.long, device=device)
                for b in range(config.batch_size):
                    start = int(cum_seqlens[b].item())
                    n = int(new_seqlens[b].item())
                    positions[start : start + n] = int(past_seqlens[b].item()) + torch.arange(n, device=device)
 
                out_in_op, cache_in_op = run_mla(
                    config,
                    query.reshape(token_count, -1),
                    new_key,
                    latent_paged.clone(),
                    cum_seqlens,
                    past_seqlens,
                    block_table,
                    cos=cos,
                    sin=sin,
                    rotary_interleaved=interleaved,
                    scale=scale,
                )
 
                q_roped = apply_offset_rope(query, cos, sin, positions, config.rotary_offset, rotary_dim, interleaved)
                k_roped = apply_offset_rope(new_key, cos, sin, positions, config.rotary_offset, rotary_dim, interleaved)
                out_pre, cache_pre = run_mla(
                    config,
                    q_roped.reshape(token_count, -1),
                    k_roped,
                    latent_paged.clone(),
                    cum_seqlens,
                    past_seqlens,
                    block_table,
                    scale=scale,
                )
 
                torch.testing.assert_close(out_in_op.to(torch.float32), out_pre.to(torch.float32), rtol=3e-3, atol=3e-3)
                # The scattered latent rows must match too: RoPE touches only the k_pe suffix.
                torch.testing.assert_close(
                    cache_in_op.to(torch.float32), cache_pre.to(torch.float32), rtol=3e-3, atol=3e-3
                )
 
    def test_v_aliases_k(self):
        """With value_cache absent, V must be the leading v_head_size channels of key_cache. Zero
        the tail of every latent row and confirm the output is unchanged: the tail is K-only."""
        device = "cuda"
        config = self._config()
        past_seqlens = torch.tensor([0, 0], dtype=torch.int32, device=device)
        new_seqlens = torch.tensor([4, 4], dtype=torch.int32, device=device)
        latent_paged, block_table, cum_seqlens, total_len = make_mla_batch(config, past_seqlens, new_seqlens)
        token_count = int(cum_seqlens[-1].item())
        query = torch.randn(token_count, config.num_heads, config.head_size, device=device, dtype=torch.float16)
        # Zero the query's rope slice so the k_pe channels cannot influence the logits either.
        query[..., config.v_head_size :] = 0
        new_key = torch.randn(token_count, config.head_size, device=device, dtype=torch.float16)
        scale = config.softmax_scale
 
        out_a, cache_a = run_mla(
            config,
            query.reshape(token_count, -1),
            new_key,
            latent_paged.clone(),
            cum_seqlens,
            past_seqlens,
            block_table,
            scale=scale,
        )
        key_tail_zeroed = new_key.clone()
        key_tail_zeroed[:, config.v_head_size :] = 0
        paged_tail_zeroed = latent_paged.clone()
        paged_tail_zeroed[..., config.v_head_size :] = 0
        out_b, _ = run_mla(
            config,
            query.reshape(token_count, -1),
            key_tail_zeroed,
            paged_tail_zeroed,
            cum_seqlens,
            past_seqlens,
            block_table,
            scale=scale,
        )
        torch.testing.assert_close(out_a.to(torch.float32), out_b.to(torch.float32), rtol=2e-3, atol=2e-3)
 
        # And the leading channels really are V: scaling them scales the output linearly.
        self.assertGreater(out_a.abs().max().item(), 1e-3)
 
    def test_fp8_latent_cache(self):
        if not has_fp8_kv_cache():
            self.skipTest("FP8 KV cache kernels are not built")
        device = "cuda"
        config = self._config(kv_cache_type="fp8", k_quant_type="PER_TENSOR")
        past_seqlens = torch.tensor([8, 8], dtype=torch.int32, device=device)
        new_seqlens = torch.tensor([2, 2], dtype=torch.int32, device=device)
        total_seqlens = past_seqlens + new_seqlens
        max_total = int(total_seqlens.max().item())
        blocks_per_seq = math.ceil(max_total / config.block_size)
        num_blocks = blocks_per_seq * config.batch_size
        block_table = torch.randperm(num_blocks, dtype=torch.int32, device=device).reshape(
            config.batch_size, blocks_per_seq
        )
        cum_seqlens = torch.zeros(config.batch_size + 1, dtype=torch.int32, device=device)
        cum_seqlens[1:] = torch.cumsum(new_seqlens, dim=0)
        token_count = int(cum_seqlens[-1].item())
 
        k_scale = torch.tensor([0.01], dtype=torch.float32, device=device)
        latent_float = torch.randn(
            num_blocks, config.block_size, config.kv_num_heads, config.head_size, device=device, dtype=torch.float16
        )
        latent_paged = quantize_kv(latent_float, k_scale, "fp8")
 
        query = torch.randn(token_count, config.num_heads, config.head_size, device=device, dtype=torch.float16)
        new_key = torch.randn(token_count, config.head_size, device=device, dtype=torch.float16)
        scale = config.softmax_scale
        out, latent_paged = run_mla(
            config,
            query.reshape(token_count, -1),
            new_key,
            latent_paged,
            cum_seqlens,
            past_seqlens,
            block_table,
            k_scale=k_scale,
            scale=scale,
        )
        # Dequantize the cache the op left behind and score against it, so only the attention math
        # (not the quantization error) is under test.
        dense_q = densify_latent(config, latent_paged, block_table, blocks_per_seq * config.block_size)
        dense = dequantize_kv(dense_q, k_scale)
        ref = mla_reference(config, query, dense, past_seqlens, new_seqlens, cum_seqlens, scale)
        out = out.reshape(token_count, config.num_heads, config.v_head_size).to(device).to(torch.float32)
        torch.testing.assert_close(out, ref, rtol=5e-3, atol=5e-3)
 
    # ---- rejected configurations (design doc §12.9, §12.10) ----
 
    def _expect_rejected(self, message_fragment, **graph_kwargs):
        """Build a LATENT model with one deliberate violation and assert the op rejects it. Schema
        violations surface at session creation, input violations in ComputeInternal, so both are
        wrapped."""
        config = graph_kwargs.pop("config", None) or self._config()
        num_tokens, num_blocks, max_blocks = 4, 4, 2
        head_size = config.head_size
 
        def build_and_run():
            model = create_mla_graph(config, num_tokens, num_blocks, max_blocks, **graph_kwargs)
            session = InferenceSession(model, SessionOptions(), providers=["CUDAExecutionProvider"])
            feeds = {
                "query": torch.randn(num_tokens, config.num_heads * head_size).to(torch.float16).numpy(),
                "key": torch.randn(num_tokens, config.kv_num_heads * head_size).to(torch.float16).numpy(),
                "key_cache": torch.randn(num_blocks, config.block_size, config.kv_num_heads, head_size)
                .to(torch.float16)
                .numpy(),
                "cumulative_sequence_length": numpy.array([0, 2, 4, 4, 4][: config.batch_size + 1], dtype=numpy.int32),
                "past_seqlens": numpy.zeros(config.batch_size, dtype=numpy.int32),
                "block_table": numpy.arange(config.batch_size * max_blocks, dtype=numpy.int32).reshape(
                    config.batch_size, max_blocks
                ),
            }
            if graph_kwargs.get("with_value"):
                feeds["value"] = torch.randn(num_tokens, config.kv_num_heads * head_size).to(torch.float16).numpy()
            if graph_kwargs.get("with_value_cache"):
                feeds["value_cache"] = feeds["key_cache"].copy()
            if graph_kwargs.get("do_rotary"):
                cache_width = config.qk_rope_head_dim // 2
                feeds["cos_cache"] = torch.ones(64, cache_width).to(torch.float16).numpy()
                feeds["sin_cache"] = torch.zeros(64, cache_width).to(torch.float16).numpy()
            if graph_kwargs.get("with_head_sink"):
                feeds["head_sink"] = torch.zeros(config.num_heads).to(torch.float16).numpy()
            if graph_kwargs.get("with_qk_norm"):
                feeds["q_norm_weight"] = torch.ones(head_size).to(torch.float16).numpy()
                feeds["k_norm_weight"] = torch.ones(head_size).to(torch.float16).numpy()
            session.run(None, feeds)
 
        with self.assertRaises(Exception) as ctx:
            build_and_run()
        self.assertIn(message_fragment, str(ctx.exception))
 
    def test_reject_missing_scale(self):
        # v_head_size != head_size with no explicit scale would silently use 1/sqrt(head_size).
        self._expect_rejected("explicit 'scale'")
 
    def test_reject_value_input(self):
        self._expect_rejected("'value'", scale=0.1, with_value=True)
 
    def test_reject_value_cache(self):
        self._expect_rejected("'value_cache' must be absent", scale=0.1, with_value_cache=True)
 
    def test_reject_value_cache_output(self):
        self._expect_rejected("value_cache_out must be absent", scale=0.1, with_value_cache_out=True)
 
    def test_reject_head_sink(self):
        self._expect_rejected("'head_sink'", scale=0.1, with_head_sink=True)
 
    def test_reject_qk_norm(self):
        self._expect_rejected("q_norm_weight", scale=0.1, with_qk_norm=True)
 
    def test_reject_multi_kv_head(self):
        config = self._config()
        config.kv_num_heads = 2
        self._expect_rejected("'kv_num_heads' must be 1", config=config, scale=0.1)
 
    def test_reject_v_head_size_in_separate_layout(self):
        # v_head_size != head_size is only meaningful for LATENT.
        self._expect_rejected(
            "may only differ from head_size",
            scale=0.1,
            kv_cache_layout="SEPARATE",
            with_value=True,
            with_value_cache=True,
            with_value_cache_out=True,
        )
 
    def test_reject_unaligned_rotary_offset(self):
        self._expect_rejected("multiple of 8", scale=0.1, do_rotary=True, rotary_offset=60)
 
    def test_reject_rotary_offset_overflow(self):
        config = self._config()
        self._expect_rejected(
            "must not exceed head_size", config=config, scale=0.1, do_rotary=True, rotary_offset=config.head_size
        )
 
 
if __name__ == "__main__":
    unittest.main(verbosity=2)