Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation.  All rights reserved.
# Licensed under the MIT License.  See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# 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
# -------------------------------------------------------------------------
import gc
import math
import os
import platform
import random
import re
import sys
import threading
import typing
import unittest
from copy import deepcopy
from dataclasses import dataclass
 
import numpy
import torch
from cuda_plugin_ep_helper import get_cuda_provider_name, resolve_cuda_plugin_ep
from einops import rearrange, repeat
from env_var_helper import scoped_env_var
 
# --- ONNX and Torch/Numpy Dtype Mappings ---
from gqa_test_helper import (
    ONNX_TENSOR_TYPE_MAP,
    TORCH_DTYPE_MAP,
    compute_scale,
    dequantize_tensor,
    quantize_tensor_with_scale,
)
from onnx import TensorProto, helper
from packaging import version
from parameterized import parameterized
 
from onnxruntime import InferenceSession, OrtValue, SessionOptions, get_available_providers, get_build_info
from onnxruntime import __version__ as ort_version
 
# Set seed for reproducibility
torch.manual_seed(0)
random.seed(69)
 
try:
    from rotary_flash import apply_rotary_emb
except ImportError:
    apply_rotary_emb = None
 
# Reduces number of tests to run for faster pipeline checks
pipeline_mode = os.getenv("PIPELINE_MODE", "1") == "1"
 
# Number of values per parameter (compared to pipeline mode)
param_count = int(os.getenv("PARAM_COUNT", "3")) if not pipeline_mode else 2
 
# When quick build is used, flash attention only supports head_size=128
quick_build = ", quick-build=" in get_build_info()
 
has_int4_kv_cache = ", int4-kv-cache=" in get_build_info()
 
has_fp8_kv_cache = ", fp8-kv-cache=" in get_build_info()
 
# Enable debug print if tensor or node dumping is enabled in build.
enable_debug_print = ("dump-tensor" in get_build_info()) or ("dump-node" in get_build_info())
 
enable_deterministic_check = True
# #################################################################################################
#  Configuration and Helper Classes
# #################################################################################################
 
 
class TestBorrowedKVCache(unittest.TestCase):
    @parameterized.expand(
        [
            (provider, device, dtype, tensor_type, head_size, query_length, with_past)
            for provider, device, dtype, tensor_type in (
                ("CPUExecutionProvider", "cpu", numpy.float32, TensorProto.FLOAT),
                ("CUDAExecutionProvider", "cuda", numpy.float16, TensorProto.FLOAT16),
            )
            for head_size in (64, 512)
            for query_length, with_past in ((1, True), (7, False), (7, True))
        ]
    )
    def test_cache_inputs_remain_unchanged(
        self, provider, device, dtype, tensor_type, head_size, query_length, with_past
    ):
        """Omitted present outputs must preserve borrowed caches across repeated runs."""
        if provider not in get_available_providers():
            self.skipTest(f"{provider} unavailable")
        self.check_borrowed_cache(provider, device, dtype, tensor_type, head_size, query_length, with_past)
 
    @parameterized.expand([(head_size, query_length) for head_size in (16, 64) for query_length in (1, 7)])
    def test_cpu_fp16_generic_reference(self, head_size, query_length):
        """Check generic CPU FP16 attention with padded caches and multiple KV heads."""
        self.check_borrowed_cache(
            "CPUExecutionProvider", "cpu", numpy.float16, TensorProto.FLOAT16, head_size, query_length, True
        )
 
    @parameterized.expand(
        [
            (head_size, query_length, window)
            for head_size in (64, 128, 256)
            for query_length in (1, 7)
            for window in (1, 16, 32)
        ]
    )
    def test_unfused_sliding_window_reference(self, head_size, query_length, window):
        """Force unfused CUDA attention and verify that the window includes the current token."""
        if "CUDAExecutionProvider" not in get_available_providers():
            self.skipTest("CUDAExecutionProvider unavailable")
        with (
            scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "1"),
            scoped_env_var("ORT_DISABLE_MEMORY_EFFICIENT_ATTENTION", "1"),
            scoped_env_var("ORT_ENABLE_CUDNN_FLASH_ATTENTION", "0"),
            scoped_env_var("ORT_ENABLE_XQA", "0"),
            scoped_env_var("ORT_DISABLE_FLASH_DECODE", "1"),
        ):
            kernel = get_sdpa_kernel_from_debug_info(
                lambda: self.check_borrowed_cache(
                    "CUDAExecutionProvider",
                    "cuda",
                    numpy.float16,
                    TensorProto.FLOAT16,
                    head_size,
                    query_length,
                    True,
                    window,
                )
            )
            self.assertEqual(kernel, "MATH")
 
    def check_borrowed_cache(
        self, provider, device, dtype, tensor_type, head_size, query_length, with_past, local_window_size=16
    ):
        random = numpy.random.default_rng(42)
        batch_size = 1 if query_length > 1 and with_past else 2
        shapes = {
            "query": [batch_size, query_length, 8 * head_size],
            "key": [batch_size, 0, 2 * head_size],
            "value": [batch_size, 0, 2 * head_size],
            "past_key": [batch_size, 2, 64, head_size],
            "past_value": [batch_size, 2, 64, head_size],
        }
        feeds = {name: random.uniform(-1, 1, shape).astype(dtype) for name, shape in shapes.items()}
        lengths = [32, 28] if query_length == 1 else ([38] if with_past else [6, 4])
        feeds["seqlens_k"] = numpy.asarray(lengths, dtype=numpy.int32)
        feeds["total_sequence_length"] = numpy.asarray([max(lengths) + 1], dtype=numpy.int32)
        inputs = [helper.make_tensor_value_info(name, tensor_type, shape) for name, shape in shapes.items()]
        inputs += [helper.make_tensor_value_info("seqlens_k", TensorProto.INT32, [batch_size])]
        inputs += [helper.make_tensor_value_info("total_sequence_length", TensorProto.INT32, [1])]
        options = SessionOptions()
        options.intra_op_num_threads = 12
        if device == "cuda":
            options.add_session_config_entry("session.disable_cpu_ep_fallback", "1")
 
        def make_session(omit_outputs):
            outputs = [helper.make_tensor_value_info("output", tensor_type, shapes["query"])]
            if not omit_outputs:
                outputs += [
                    helper.make_tensor_value_info("present_key", tensor_type, shapes["past_key"]),
                    helper.make_tensor_value_info("present_value", tensor_type, shapes["past_value"]),
                ]
            node = helper.make_node(
                "GroupQueryAttention",
                list(feeds),
                [output.name for output in outputs],
                domain="com.microsoft",
                num_heads=8,
                kv_num_heads=2,
                local_window_size=local_window_size,
            )
            model = helper.make_model(
                helper.make_graph([node], "borrowed-cache", inputs, outputs),
                opset_imports=[helper.make_opsetid("", 17), helper.make_opsetid("com.microsoft", 1)],
                ir_version=10,
            )
            return InferenceSession(model.SerializeToString(), options, providers=[provider])
 
        expected_session = make_session(False)
        borrowed_session = make_session(True)
        caches = {name: OrtValue.ortvalue_from_numpy(feeds[name], device, 0) for name in ("past_key", "past_value")}
        originals = {name: feeds[name].copy() for name in caches}
        for _ in range(2):
            expected = expected_session.run(["output"], feeds)[0]
            binding = borrowed_session.io_binding()
            for name, values in feeds.items():
                if name in caches:
                    binding.bind_ortvalue_input(name, caches[name])
                else:
                    binding.bind_cpu_input(name, values)
            binding.bind_output("output", device)
            borrowed_session.run_with_iobinding(binding)
            actual = binding.copy_outputs_to_cpu()[0]
            self.assertTrue(numpy.isfinite(actual).all())
            tolerance = 2e-3 if dtype == numpy.float16 else 2e-5
            numpy.testing.assert_allclose(actual, expected, rtol=tolerance, atol=2e-5)
            if with_past:
                reference = numpy.empty((batch_size, query_length, 8, head_size), dtype=numpy.float64)
                queries = feeds["query"].reshape(reference.shape).astype(numpy.float64)
                for batch_index, last_position in enumerate(feeds["seqlens_k"]):
                    for query_index in range(query_length):
                        end = int(last_position) + 2 - query_length + query_index
                        start = max(0, end - local_window_size)
                        for head_index in range(8):
                            keys = originals["past_key"][batch_index, head_index // 4, start:end].astype(numpy.float64)
                            values = originals["past_value"][batch_index, head_index // 4, start:end].astype(
                                numpy.float64
                            )
                            scores = keys @ queries[batch_index, query_index, head_index] / math.sqrt(head_size)
                            weights = numpy.exp(scores - scores.max())
                            reference[batch_index, query_index, head_index] = (weights / weights.sum()) @ values
                numpy.testing.assert_allclose(
                    actual,
                    reference.reshape(actual.shape),
                    rtol=tolerance,
                    atol=tolerance,
                )
                feeds["seqlens_k"] -= 3
                feeds["total_sequence_length"] -= 3
            for name, cache in caches.items():
                numpy.testing.assert_array_equal(cache.numpy(), originals[name])
            feeds["query"] = random.uniform(-1, 1, shapes["query"]).astype(dtype)
 
 
class CaptureStdout:
    """Capture output written to OS file descriptor 1 (C++ stdout).
 
    Uses fd-level dup2 redirection rather than contextlib.redirect_stdout because the kernel
    debug info is emitted by the native ONNX Runtime library directly to fd 1, which Python's
    redirect_stdout (which only swaps sys.stdout) cannot intercept.
    """
 
    def __init__(self):
        self.fd = 1
        self.chunk_size = 1024
        self.output = b""
 
    def _capture(self):
        chunks = []
        while chunk := os.read(self._pipe_reader, self.chunk_size):
            chunks.append(chunk)
        self.output = b"".join(chunks)
 
    def __enter__(self):
        sys.stdout.flush()
        self._duped_fd = os.dup(self.fd)
        self._pipe_reader, pipe_writer = os.pipe()
        os.dup2(pipe_writer, self.fd)
        os.close(pipe_writer)
        self._capture_thread = threading.Thread(target=self._capture)
        self._capture_thread.start()
        return self
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.flush()
        os.dup2(self._duped_fd, self.fd)
        self._capture_thread.join()
        os.close(self._pipe_reader)
        os.close(self._duped_fd)
 
 
def get_sdpa_kernel_from_debug_info(run_func):
    captured_text = None
    with scoped_env_var("ORT_ENABLE_ATTENTION_KERNEL_DEBUG_INFO", "1"):
        with CaptureStdout() as captured:
            run_func()
        captured_text = captured.output.decode(errors="replace")
 
    if captured_text is not None:
        match = re.search(r"SdpaKernel=(?P<kernel>[A-Z_]+)", captured_text)
        if match is not None:
            return match.group("kernel")
 
        print("Failed to get sdpa kernel from debug info:", captured_text)
 
    return None
 
 
@dataclass
class GQAConfig:
    batch_size: int
    q_sequence_length: int
    kv_sequence_length: int
    num_heads: int
    kv_num_heads: int
    head_size: int
    past_kv_sequence_length: int = 0
    buffer_sequence_length: int = 0
    # Test-specific parameters
    local_window_size: int = -1
    # Opt into the cache-relative (windowed) KV cache. Requires local_window_size > 0 and a
    # past/present shared buffer whose capacity C is at least local_window_size. There is no
    # requirement involving q_sequence_length: a multi-token step that would need more than C
    # entries runs against a longer staging buffer, so prefill of any length works at C == W.
    # Slack above local_window_size is worth allocating anyway: it lets the append point drift, so
    # the CPU kernel compacts once every C - W + 1 steps instead of on every step.
    sliding_window_cache: int = 0
    # Length of the cos/sin caches. 0 means "same as buffer_sequence_length". A windowed KV cache is
    # shorter than the sequence, so RoPE positions must be driven by a separately sized rotary cache.
    rope_cache_length: int = 0
    rotary: bool = False
    rotary_interleaved: bool = False
    packed: bool = False
    softcap: float = 0.0
    use_smooth_softmax: bool = False
    has_head_sink: bool = False
    # When True, head_sink is baked into the model as a constant initializer (instead of a runtime
    # input). This exercises the GroupQueryAttention::PrePack path that converts the constant
    # head_sink to a cached FP32 XQA buffer.
    head_sink_as_initializer: bool = False
    kv_cache_type: str = ""
    share_buffer: bool = True
    share_kv_scale: bool = False
    causal: bool = True
 
    has_position_ids: bool = False
    has_attention_bias: bool = False
    # attention_bias leading dims: dim 0 is batch_size (or 1 when broadcast), dim 1 is
    # 1 (broadcast over heads) or num_heads. Defaults keep the original [batch, 1, ...] shape.
    attention_bias_broadcast_dim_0: bool = False
    attention_bias_per_head: bool = False
 
    # Quantization parameters
    k_quant_type: str = "NONE"
    v_quant_type: str = "NONE"
    kv_cache_bit_width: int = 0
 
    # Fused per-head Q/K RMSNorm (QK-Norm) applied before RoPE. Weight shape (head_size,) shared across heads.
    has_qk_norm: bool = False
    qk_norm_epsilon: float = 1e-6
 
 
# #################################################################################################
#  Rotary Embedding Implementations (CPU and CUDA)
# #################################################################################################
 
 
# PyTorch implementation for CPU and fallback
class LlamaMSRotaryEmbedding(torch.nn.Module):
    def __init__(self):
        super().__init__()
 
    def rotate_tensor(self, x, cos, sin, pos, interleaved):
        rot_dim = 2 * cos.shape[3]
        x_rot = x[:, :, :, :rot_dim]
 
        if interleaved:
            x1 = x_rot[:, :, :, 0::2]
            x2 = x_rot[:, :, :, 1::2]
        else:
            half = x_rot.shape[-1] // 2
            x1 = x_rot[:, :, :, 0:half]
            x2 = x_rot[:, :, :, half : 2 * half]
 
        seq_len = x.shape[1]
        batch_size = x.shape[0]
 
        cos = cos.squeeze(0).squeeze(1)
        sin = sin.squeeze(0).squeeze(1)
 
        if seq_len == 1:
            pos_i = pos.long()
            cos_x = cos[pos_i].unsqueeze(1)
            sin_x = sin[pos_i].unsqueeze(1)
        else:
            cos_x_list = []
            sin_x_list = []
            for b in range(batch_size):
                pos_b = pos[b]
                cos_x_list.append(cos[pos_b : pos_b + seq_len])
                sin_x_list.append(sin[pos_b : pos_b + seq_len])
            cos_x = torch.stack(cos_x_list, dim=0)
            sin_x = torch.stack(sin_x_list, dim=0)
 
        cos_x = cos_x.unsqueeze(2)
        sin_x = sin_x.unsqueeze(2)
 
        real = cos_x * x1 - sin_x * x2
        imag = sin_x * x1 + cos_x * x2
 
        if interleaved:
            x_rot[:, :, :, 0::2] = real
            x_rot[:, :, :, 1::2] = imag
        else:
            x_rot = torch.cat((real, imag), dim=-1)
 
        return torch.cat((x_rot, x[:, :, :, rot_dim:]), dim=-1)
 
    def forward(self, x, cos, sin, pos, interleaved):
        return self.rotate_tensor(x, cos, sin, pos, interleaved)
 
 
# Triton-based implementation for CUDA
def rotary_embedding_cuda(*args, **kwargs):
    if apply_rotary_emb is None:
        raise ImportError("rotary_flash not found")
    return apply_rotary_emb(*args, **kwargs)
 
 
# Unified wrapper for rotary embeddings
def apply_rotary_embedding(x, cos, sin, pos, interleaved, device="cpu"):
    """Applies rotary embedding, using Triton for CUDA if available, otherwise fallback to PyTorch."""
    use_cuda_triton = device == "cuda" and platform.system() == "Linux"
    if use_cuda_triton:
        try:
            return rotary_embedding_cuda(x, cos, sin, seqlen_offsets=pos, interleaved=interleaved)
        except ImportError:
            print("WARNING: Triton-based rotary embedding not found. Falling back to PyTorch version.")
 
    # PyTorch implementation for CPU or as a fallback for CUDA
    rot = LlamaMSRotaryEmbedding().to(device)
    # Unsqueeze to match the expected shape in the PyTorch version
    cos_unsqueezed = cos.unsqueeze(0).unsqueeze(2)
    sin_unsqueezed = sin.unsqueeze(0).unsqueeze(2)
    return rot(x, cos_unsqueezed, sin_unsqueezed, pos, interleaved)
 
 
# #################################################################################################
#  ONNX Graph Creation
# #################################################################################################
 
 
def make_head_sink_initializer(head_sink, ort_type, num_heads):
    """Build a constant head_sink initializer (fp16/bf16) so GroupQueryAttention::PrePack runs.
 
    The 16-bit float bits are reinterpreted as uint16 and stored as raw bytes, which works for
    both float16 and bfloat16 without relying on numpy bfloat16 support.
    """
    raw = head_sink.detach().reshape(num_heads).cpu().contiguous().view(torch.uint16).numpy().tobytes()
    return helper.make_tensor(name="head_sink", data_type=ort_type, dims=[num_heads], vals=raw, raw=True)
 
 
def make_qk_norm_weights(head_size, device, torch_type, seed=7):
    """Generate deterministic per-head Q/K RMSNorm weights of shape (head_size,)."""
    gen = torch.Generator(device=device).manual_seed(seed)
    q_w = (1.0 + 0.1 * torch.randn(head_size, generator=gen, device=device, dtype=torch.float32)).to(torch_type)
    k_w = (1.0 + 0.1 * torch.randn(head_size, generator=gen, device=device, dtype=torch.float32)).to(torch_type)
    return q_w, k_w
 
 
def apply_qk_rmsnorm(x, weight, eps):
    """Reference per-head RMSNorm over the last (head_size) dim, computed in float32 then cast back.
 
    x_norm[c] = x[c] * rsqrt(mean(x^2) + eps) * weight[c]
    """
    dtype = x.dtype
    xf = x.to(torch.float32)
    inv_rms = torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + eps)
    return (xf * inv_rms * weight.to(torch.float32)).to(dtype)
 
 
def create_gqa_node_and_io(
    config: GQAConfig,
    ort_type,
    share_buffer=True,
    is_past=False,
    output_qk: int = 0,  # CUDA does not support output_qk for GQA
    head_sink_values=None,
):
    if is_past:
        if share_buffer:
            past_kv_seqlen = config.buffer_sequence_length
            present_kv_seqlen = config.buffer_sequence_length
        else:
            past_kv_seqlen = config.past_kv_sequence_length
            present_kv_seqlen = config.past_kv_sequence_length + config.kv_sequence_length
    else:  # Prompt
        past_kv_seqlen = config.buffer_sequence_length if share_buffer else 0
        present_kv_seqlen = config.buffer_sequence_length if share_buffer else config.kv_sequence_length
 
    if not config.kv_cache_type:
        config.kv_cache_type = "float16" if ort_type == TensorProto.FLOAT16 else "bfloat16"
 
    initializers = []
 
    # --- Node Definition ---
    outputs = [
        "output",
        "present_key",
        "present_value",
    ]
 
    if output_qk > 0:
        outputs.append("output_qk")
 
    # Ensure kv_cache_bit_width is set correctly based on cache type if not provided
    bit_width = config.kv_cache_bit_width
    if bit_width == 0:
        if config.kv_cache_type == "int4":
            bit_width = 4
        elif config.kv_cache_type == "int8":
            bit_width = 8
 
    inputs = [
        "query",
        "key" if not config.packed else "",
        "value" if not config.packed else "",
        "past_key" if is_past or share_buffer or config.k_quant_type != "NONE" else "",
        "past_value" if is_past or share_buffer or config.k_quant_type != "NONE" else "",
        "seqlens_k",
        "total_sequence_length",
        "cos_cache" if config.rotary else "",
        "sin_cache" if config.rotary else "",
        "position_ids" if config.has_position_ids else "",
        "attention_bias" if config.has_attention_bias else "",
        "head_sink" if config.has_head_sink else "",
        "k_scale" if config.k_quant_type != "NONE" else "",
        "k_scale"
        if config.share_kv_scale and config.k_quant_type != "NONE"
        else ("v_scale" if config.v_quant_type != "NONE" else ""),
        "q_norm_weight" if config.has_qk_norm else "",
        "k_norm_weight" if config.has_qk_norm else "",
    ]
 
    # Remove trailing empty strings
    while inputs and inputs[-1] == "":
        inputs.pop()
 
    quantization_attributes = (
        {
            "k_quant_type": config.k_quant_type,
            "v_quant_type": config.v_quant_type,
            "kv_cache_bit_width": bit_width,
        }
        if config.k_quant_type != "NONE"
        else {}
    )
 
    qk_norm_attributes = {"qk_norm_epsilon": config.qk_norm_epsilon} if config.has_qk_norm else {}
 
    windowed_cache_attributes = {"sliding_window_cache": 1} if config.sliding_window_cache else {}
 
    node = helper.make_node(
        op_type="GroupQueryAttention",
        inputs=inputs,
        outputs=outputs,
        name="GroupQueryAttention_0",
        num_heads=config.num_heads,
        kv_num_heads=config.kv_num_heads,
        local_window_size=config.local_window_size,
        do_rotary=config.rotary,
        rotary_interleaved=config.rotary_interleaved,
        softcap=config.softcap,
        causal=1 if config.causal else 0,
        smooth_softmax=1 if config.use_smooth_softmax else 0,
        qk_output=output_qk,
        **quantization_attributes,
        **qk_norm_attributes,
        **windowed_cache_attributes,
        domain="com.microsoft",
    )
 
    # --- Graph Inputs ---
    q_hidden_size = (
        (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)
    )
    graph_input = [
        helper.make_tensor_value_info("query", ort_type, [config.batch_size, config.q_sequence_length, q_hidden_size]),
        helper.make_tensor_value_info("seqlens_k", TensorProto.INT32, [config.batch_size]),
        helper.make_tensor_value_info("total_sequence_length", TensorProto.INT32, [1]),
    ]
    cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
 
    if not config.packed:
        graph_input.extend(
            [
                helper.make_tensor_value_info(
                    "key",
                    ort_type,
                    [config.batch_size, config.kv_sequence_length, config.kv_num_heads * config.head_size],
                ),
                helper.make_tensor_value_info(
                    "value",
                    ort_type,
                    [config.batch_size, config.kv_sequence_length, config.kv_num_heads * config.head_size],
                ),
            ]
        )
 
    if is_past or share_buffer or config.k_quant_type != "NONE":
        k_shape = [config.batch_size, config.kv_num_heads, past_kv_seqlen, config.head_size]
        if config.kv_cache_type == "int4":
            k_shape[-1] //= 2
        graph_input.extend(
            [
                helper.make_tensor_value_info("past_key", cache_ort_type, k_shape),
                helper.make_tensor_value_info("past_value", cache_ort_type, k_shape),
            ]
        )
        if config.k_quant_type != "NONE":
            # Scales are always float32
            graph_input.append(helper.make_tensor_value_info("k_scale", TensorProto.FLOAT, None))
        if config.v_quant_type != "NONE" and not config.share_kv_scale:
            graph_input.append(helper.make_tensor_value_info("v_scale", TensorProto.FLOAT, None))
 
    if config.rotary:
        rotary_dim = (math.floor(config.head_size / 16) * 16) // 2
        cache_seq_len = config.rope_cache_length or config.buffer_sequence_length
        graph_input.extend(
            [
                helper.make_tensor_value_info("cos_cache", ort_type, [cache_seq_len, rotary_dim]),
                helper.make_tensor_value_info("sin_cache", ort_type, [cache_seq_len, rotary_dim]),
            ]
        )
 
    if config.has_position_ids:
        graph_input.append(
            helper.make_tensor_value_info(
                "position_ids", TensorProto.INT64, [config.batch_size, config.q_sequence_length]
            )
        )
    if config.has_attention_bias:
        # Per the op spec the last dim is total_sequence_length (past + new), which the kernel
        # validates at runtime; declare it symbolic so one graph serves all cache states.
        bias_dim_0 = 1 if config.attention_bias_broadcast_dim_0 else config.batch_size
        bias_dim_1 = config.num_heads if config.attention_bias_per_head else 1
        graph_input.append(
            helper.make_tensor_value_info(
                "attention_bias", ort_type, [bias_dim_0, bias_dim_1, config.q_sequence_length, "total_sequence_length"]
            )
        )
    if config.has_head_sink:
        if config.head_sink_as_initializer and head_sink_values is not None:
            # Constant initializer (not a graph input) so ORT treats it as a constant and PrePack runs.
            initializers.append(make_head_sink_initializer(head_sink_values, ort_type, config.num_heads))
        else:
            graph_input.append(helper.make_tensor_value_info("head_sink", ort_type, [config.num_heads]))
 
    if config.has_qk_norm:
        graph_input.append(helper.make_tensor_value_info("q_norm_weight", ort_type, [config.head_size]))
        graph_input.append(helper.make_tensor_value_info("k_norm_weight", ort_type, [config.head_size]))
 
    # --- Graph Outputs ---
    output_k_shape = [config.batch_size, config.kv_num_heads, present_kv_seqlen, config.head_size]
    if config.kv_cache_type == "int4":
        output_k_shape[-1] //= 2
 
    graph_output = [
        helper.make_tensor_value_info(
            "output", ort_type, [config.batch_size, config.q_sequence_length, config.num_heads * config.head_size]
        ),
        helper.make_tensor_value_info("present_key", cache_ort_type, output_k_shape),
        helper.make_tensor_value_info("present_value", cache_ort_type, output_k_shape),
    ]
 
    if output_qk > 0:
        graph_output.append(
            helper.make_tensor_value_info(
                "output_qk",
                ort_type,
                [config.batch_size, config.num_heads, config.q_sequence_length, present_kv_seqlen],
            )
        )
 
    return node, graph_input, graph_output, initializers
 
 
def create_group_query_attention_graph_prompt(config: GQAConfig, ort_type, share_buffer=True):
    node, graph_input, graph_output, initializers = create_gqa_node_and_io(
        config, ort_type, share_buffer, is_past=False
    )
    graph = helper.make_graph([node], "GroupQueryAttention_Graph", graph_input, graph_output, initializer=initializers)
    model = helper.make_model(
        graph, opset_imports=[helper.make_opsetid("", 26), helper.make_opsetid("com.microsoft", 1)]
    )
    return model.SerializeToString()
 
 
def create_group_query_attention_graph_past(config: GQAConfig, ort_type, share_buffer=True, head_sink_values=None):
    node, graph_input, graph_output, initializers = create_gqa_node_and_io(
        config, ort_type, share_buffer, is_past=True, head_sink_values=head_sink_values
    )
    graph = helper.make_graph([node], "GroupQueryAttention_Graph", graph_input, graph_output, initializer=initializers)
    model = helper.make_model(
        graph, opset_imports=[helper.make_opsetid("", 26), helper.make_opsetid("com.microsoft", 1)]
    )
    return model.SerializeToString()
 
 
# #################################################################################################
#  ONNX Runtime Execution Functions
# #################################################################################################
 
 
def bind_tensor(io_binding, name, tensor, device, ort_type):
    # Helper to bind a tensor to ONNX Runtime based on its device and type
    if tensor is None:
        return
    # Assuming tensor is a torch tensor. This works for both CPU and GPU tensors.
    io_binding.bind_input(
        name,
        tensor.device.type,
        0,
        ort_type,
        tuple(tensor.shape),
        tensor.data_ptr(),
    )
 
 
def bind_output_tensor(io_binding, name, tensor, device, ort_type):
    if tensor is None:
        return
    io_binding.bind_output(
        name,
        tensor.device.type,
        0,
        ort_type,
        tuple(tensor.shape),
        tensor.data_ptr(),
    )
 
 
def gqa_prompt_func(
    q,
    k,
    v,
    config: GQAConfig,
    new_k,
    new_v,
    cos,
    sin,
    seqlens_k,
    position_ids,
    attention_bias,
    head_sink,
    k_scale,
    v_scale,
    ep,
    device,
    share_buffer=True,
    ort_type=TensorProto.FLOAT16,
    q_norm_weight=None,
    k_norm_weight=None,
):
    if not config.kv_cache_type:
        config.kv_cache_type = "float16" if ort_type == TensorProto.FLOAT16 else "bfloat16"
 
    onnx_model_str = create_group_query_attention_graph_prompt(
        config=config,
        ort_type=ort_type,
        share_buffer=share_buffer,
    )
 
    q = torch.reshape(q, (config.batch_size, config.q_sequence_length, -1))
    if new_k is not None:
        kv_hidden_size = config.kv_num_heads * config.head_size
        new_k = torch.reshape(new_k, (config.batch_size, config.kv_sequence_length, kv_hidden_size))
        new_v = torch.reshape(new_v, (config.batch_size, config.kv_sequence_length, kv_hidden_size))
 
    sess_options = SessionOptions()
    ort_session = InferenceSession(onnx_model_str, sess_options, providers=[resolve_cuda_plugin_ep(ep)])
    io_binding = ort_session.io_binding()
 
    # Determine input device for binding
    # We assume primary inputs are on the target device
 
    # 1. Bind 'query'
    bind_tensor(io_binding, "query", q, device, ort_type)
 
    # 2. Bind 'key', 'value' (from new_k, new_v)
    if new_k is not None:
        bind_tensor(io_binding, "key", new_k, device, ort_type)
        bind_tensor(io_binding, "value", new_v, device, ort_type)
 
    # 3. Bind 'past_key', 'past_value' (if share_buffer or quantized)
    if share_buffer or config.k_quant_type != "NONE":
        # cache_ort_type corresponds to config.kv_cache_type
        cache_ort_type = ort_type
        if config.kv_cache_type:
            cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
 
        # Use full buffer if sharing, otherwise empty tensor for prompt phase
        k_to_bind = k if share_buffer else k[:, :, :0, :].contiguous()
        v_to_bind = v if share_buffer else v[:, :, :0, :].contiguous()
 
        bind_tensor(io_binding, "past_key", k_to_bind, device, cache_ort_type)
        bind_tensor(io_binding, "past_value", v_to_bind, device, cache_ort_type)
 
    # Scales are bound below in section 6
 
    # 4. Bind scalars/1D tensors
    # seqlens_k is INT32
    bind_tensor(io_binding, "seqlens_k", seqlens_k.to(torch.int32), device, TensorProto.INT32)
 
    # total_sequence_length is INT32 [1]
    # Schema requires this to be on CPU (OrtMemTypeCPUInput)
    cpu_device = torch.device("cpu")
    tsl = torch.tensor([config.q_sequence_length], dtype=torch.int32, device=cpu_device)
    bind_tensor(io_binding, "total_sequence_length", tsl, cpu_device, TensorProto.INT32)
 
    # 5. Optional inputs
    if cos is not None:
        bind_tensor(io_binding, "cos_cache", cos, device, ort_type)
        bind_tensor(io_binding, "sin_cache", sin, device, ort_type)
 
    if config.has_position_ids and position_ids is not None:
        bind_tensor(io_binding, "position_ids", position_ids, device, TensorProto.INT64)
 
    if config.has_attention_bias and attention_bias is not None:
        bind_tensor(io_binding, "attention_bias", attention_bias, device, ort_type)
 
    if config.has_head_sink and head_sink is not None:
        bind_tensor(io_binding, "head_sink", head_sink, device, ort_type)
 
    if config.has_qk_norm and q_norm_weight is not None and k_norm_weight is not None:
        bind_tensor(io_binding, "q_norm_weight", q_norm_weight, device, ort_type)
        bind_tensor(io_binding, "k_norm_weight", k_norm_weight, device, ort_type)
 
    # 6. Quantization scales
    if k_scale is not None:
        k_scale_ort_type = TensorProto.FLOAT
        if k_scale.dtype != torch.float32:
            k_scale = k_scale.to(torch.float32)
        k_scale = k_scale.contiguous()
        bind_tensor(io_binding, "k_scale", k_scale, device, k_scale_ort_type)
    if v_scale is not None:
        v_scale_ort_type = TensorProto.FLOAT
        if v_scale.dtype != torch.float32:
            v_scale = v_scale.to(torch.float32)
        v_scale = v_scale.contiguous()
        if not config.share_kv_scale:
            bind_tensor(io_binding, "v_scale", v_scale, device, v_scale_ort_type)
 
    # 7. Bind Outputs
    # output shape calculation
    hidden_size = config.num_heads * config.head_size
 
    out_dtype = TORCH_DTYPE_MAP.get(config.kv_cache_type, torch.float16)
    if ort_type == TensorProto.BFLOAT16:
        out_dtype = torch.bfloat16
    elif ort_type == TensorProto.FLOAT16:
        out_dtype = torch.float16
    else:
        out_dtype = torch.float32
 
    out_torch = torch.zeros((config.batch_size, config.q_sequence_length, hidden_size), dtype=out_dtype, device=device)
    bind_output_tensor(io_binding, "output", out_torch, device, ort_type)
 
    # present_dims logic
    if share_buffer:
        present_seqlen = config.buffer_sequence_length
    else:
        present_seqlen = config.kv_sequence_length
 
    present_dims = [config.batch_size, config.kv_num_heads, present_seqlen, config.head_size]
 
    # Update present shape when kv cache has quantization (int4 packs 2 values)
    if config.kv_cache_bit_width == 4:
        present_dims[-1] //= 2
 
    # Determine dtype for cache tensors
    cache_dtype = out_dtype
    cache_ort_type = ort_type
    if config.kv_cache_type in ONNX_TENSOR_TYPE_MAP:
        cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
 
    if config.kv_cache_type in TORCH_DTYPE_MAP:
        cache_dtype = TORCH_DTYPE_MAP[config.kv_cache_type]
 
    if share_buffer:
        # We bind output to the input buffer 'k' / 'v' (in-place update)
        # Assuming k and v are large enough buffers provided as input
        io_binding.bind_output("present_key", device, 0, cache_ort_type, tuple(k.shape), k.data_ptr())
        io_binding.bind_output("present_value", device, 0, cache_ort_type, tuple(v.shape), v.data_ptr())
        present_k = k
        present_v = v
    else:
        present_k = torch.zeros(tuple(present_dims), dtype=cache_dtype, device=device)
        present_v = torch.zeros(tuple(present_dims), dtype=cache_dtype, device=device)
        bind_output_tensor(io_binding, "present_key", present_k, device, cache_ort_type)
        bind_output_tensor(io_binding, "present_value", present_v, device, cache_ort_type)
 
    io_binding.synchronize_inputs()
    ort_session.run_with_iobinding(io_binding)
    io_binding.synchronize_outputs()
 
    return out_torch, present_k, present_v
 
 
def gqa_past_func(
    q,
    k,
    v,
    config: GQAConfig,
    new_k,
    new_v,
    cos,
    sin,
    seqlens_k,
    position_ids,
    attention_bias,
    head_sink,
    k_scale,
    v_scale,
    ep,
    device,
    share_buffer=True,
    ort_type=TensorProto.FLOAT16,
    q_norm_weight=None,
    k_norm_weight=None,
):
    if not config.kv_cache_type:
        config.kv_cache_type = "float16" if ort_type == TensorProto.FLOAT16 else "bfloat16"
 
    head_sink_as_initializer = config.has_head_sink and config.head_sink_as_initializer and head_sink is not None
    onnx_model_str = create_group_query_attention_graph_past(
        config=config,
        ort_type=ort_type,
        share_buffer=share_buffer,
        head_sink_values=head_sink if head_sink_as_initializer else None,
    )
 
    q = torch.reshape(q, (config.batch_size, config.q_sequence_length, -1))
    if new_k is not None:
        kv_hidden_size = config.kv_num_heads * config.head_size
        new_k = torch.reshape(new_k, (config.batch_size, config.kv_sequence_length, kv_hidden_size))
        new_v = torch.reshape(new_v, (config.batch_size, config.kv_sequence_length, kv_hidden_size))
 
    sess_options = SessionOptions()
    # sess_options.log_severity_level = 0
    ort_session = InferenceSession(onnx_model_str, sess_options, providers=[resolve_cuda_plugin_ep(ep)])
    io_binding = ort_session.io_binding()
 
    # Common inputs
    total_seq_len = config.past_kv_sequence_length + config.kv_sequence_length
 
    # 1. Bind 'query'
    bind_tensor(io_binding, "query", q, device, ort_type)
 
    # 2. Bind 'key', 'value' (from new_k, new_v) --> wait, past func takes separate new_k/new_v inputs?
    # In past_func, new_k/new_v are the *new* tokens to accept.
    if new_k is not None:
        bind_tensor(io_binding, "key", new_k, device, ort_type)
        bind_tensor(io_binding, "value", new_v, device, ort_type)
 
    # 3. Bind 'past_key', 'past_value'
    # These are required inputs for past_func
    # cache_ort_type corresponds to config.kv_cache_type
    cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
 
    if share_buffer:
        # If sharing buffer, we bind 'past_key' to the large buffer 'k'
        bind_tensor(io_binding, "past_key", k, device, cache_ort_type)
        bind_tensor(io_binding, "past_value", v, device, cache_ort_type)
    else:
        # If not sharing buffer, 'k' and 'v' are the *past* states passed in.
        # We must slice the buffer to the valid past length expected by the graph.
        past_len = config.past_kv_sequence_length
        k_sliced = k[:, :, :past_len, :].contiguous()
        v_sliced = v[:, :, :past_len, :].contiguous()
        bind_tensor(io_binding, "past_key", k_sliced, device, cache_ort_type)
        bind_tensor(io_binding, "past_value", v_sliced, device, cache_ort_type)
 
    # 4. Scalars
    seqlens_k_int32 = seqlens_k.to(dtype=torch.int32, device=device)
    bind_tensor(io_binding, "seqlens_k", seqlens_k_int32, device, TensorProto.INT32)
 
    # GroupQueryAttention expects total_sequence_length as CPU input.
    cpu_device = torch.device("cpu")
    tsl = torch.tensor([total_seq_len], dtype=torch.int32, device=cpu_device)
    bind_tensor(io_binding, "total_sequence_length", tsl, cpu_device, TensorProto.INT32)
 
    # 5. Optional inputs
    if cos is not None:
        bind_tensor(io_binding, "cos_cache", cos, device, ort_type)
        bind_tensor(io_binding, "sin_cache", sin, device, ort_type)
 
    if config.has_position_ids and position_ids is not None:
        bind_tensor(io_binding, "position_ids", position_ids, device, TensorProto.INT64)
 
    if config.has_attention_bias and attention_bias is not None:
        bind_tensor(io_binding, "attention_bias", attention_bias, device, ort_type)
 
    if config.has_head_sink and head_sink is not None and not head_sink_as_initializer:
        bind_tensor(io_binding, "head_sink", head_sink, device, ort_type)
 
    if config.has_qk_norm and q_norm_weight is not None and k_norm_weight is not None:
        bind_tensor(io_binding, "q_norm_weight", q_norm_weight, device, ort_type)
        bind_tensor(io_binding, "k_norm_weight", k_norm_weight, device, ort_type)
 
    # 6. Quantization
    if k_scale is not None:
        k_scale_ort_type = TensorProto.FLOAT
        if k_scale.dtype != torch.float32:
            k_scale = k_scale.to(torch.float32)
        k_scale = k_scale.contiguous()
        bind_tensor(io_binding, "k_scale", k_scale, device, k_scale_ort_type)
 
    if v_scale is not None and not config.share_kv_scale:
        v_scale_ort_type = TensorProto.FLOAT
        if v_scale.dtype != torch.float32:
            v_scale = v_scale.to(torch.float32)
        v_scale = v_scale.contiguous()
        # Even if share_kv_scale is True, the node might have two scale inputs named "k_scale" and "v_scale"
        # depending on the graph creation logic. We should bind "v_scale" if it's expected by the graph.
        # In create_gqa_node_and_io, if share_kv_scale is True, Input 13 is named "k_scale".
        # But if it's False, it's named "v_scale".
        if not config.share_kv_scale:
            bind_tensor(io_binding, "v_scale", v_scale, device, v_scale_ort_type)
 
    # 7. Outputs
    # output shape calculation
    hidden_size = config.num_heads * config.head_size
 
    out_dtype = TORCH_DTYPE_MAP.get(config.kv_cache_type, torch.float16)
    if ort_type == TensorProto.BFLOAT16:
        out_dtype = torch.bfloat16
    elif ort_type == TensorProto.FLOAT16:
        out_dtype = torch.float16
    else:
        out_dtype = torch.float32
 
    # Initialize to zeros
    out_torch = torch.zeros((config.batch_size, config.q_sequence_length, hidden_size), dtype=out_dtype, device=device)
    bind_output_tensor(io_binding, "output", out_torch, device, ort_type)
 
    # present_dims logic
    if share_buffer:
        present_seqlen = config.buffer_sequence_length
    else:
        present_seqlen = total_seq_len  # For past_func, total seq len is accumulated
 
    present_dims = [config.batch_size, config.kv_num_heads, present_seqlen, config.head_size]
    if config.kv_cache_bit_width == 4:
        present_dims[-1] //= 2
 
    cache_dtype = out_dtype
    cache_ort_type = ort_type
    if config.kv_cache_type in ONNX_TENSOR_TYPE_MAP:
        cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
        if config.kv_cache_type in TORCH_DTYPE_MAP:
            cache_dtype = TORCH_DTYPE_MAP[config.kv_cache_type]
 
    if share_buffer:
        # In-place update to k/v buffers
        io_binding.bind_output("present_key", device, 0, cache_ort_type, tuple(k.shape), k.data_ptr())
        io_binding.bind_output("present_value", device, 0, cache_ort_type, tuple(v.shape), v.data_ptr())
        present_k = k
        present_v = v
    else:
        present_k = torch.zeros(tuple(present_dims), dtype=cache_dtype, device=device)
        present_v = torch.zeros(tuple(present_dims), dtype=cache_dtype, device=device)
        bind_output_tensor(io_binding, "present_key", present_k, device, cache_ort_type)
        bind_output_tensor(io_binding, "present_value", present_v, device, cache_ort_type)
 
    io_binding.synchronize_inputs()
    ort_session.run_with_iobinding(io_binding)
    io_binding.synchronize_outputs()
 
    return out_torch, present_k, present_v
 
 
# #################################################################################################
#  Reference Attention Implementation
# #################################################################################################
 
 
def construct_local_mask(seqlen_q, seqlen_k, window_size, query_padding_mask, key_padding_mask, device):
    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 smooth_softmax_ref(x, head_sink):
    b, n, s, _ = x.shape
    if head_sink is not None:
        sink = head_sink.reshape(1, n, 1, 1).expand(b, -1, s, -1)
    else:
        sink = torch.zeros(b, n, s, 1, dtype=x.dtype, device=x.device)
 
    y = torch.cat([x, sink], dim=-1)
    y = torch.softmax(y, dim=-1)
    return y[..., :-1]
 
 
def attention_ref(
    q,
    k,
    v,
    query_padding_mask=None,
    key_padding_mask=None,
    attention_bias=None,
    causal=False,
    window_size=(-1, -1),
    softcap=0.0,
    use_smooth_softmax=False,
    head_sink=None,
):
    if causal:
        window_size = (window_size[0], 0)
 
    dtype_og = q.dtype
    q, k, v = q.float(), k.float(), v.float()
    seqlen_q, seqlen_k = q.shape[1], k.shape[1]
 
    # Repeat K/V heads for Grouped-Query Attention
    if k.shape[2] != q.shape[2]:
        k = repeat(k, "b s h d -> b s (h g) d", g=q.shape[2] // k.shape[2])
    if v.shape[2] != q.shape[2]:
        v = repeat(v, "b s h d -> b s (h g) d", g=q.shape[2] // v.shape[2])
 
    scores = torch.einsum("bthd,bshd->bhts", q, k) / math.sqrt(q.shape[-1])
 
    if softcap > 0:
        scores = (scores / softcap).tanh() * softcap
 
    if key_padding_mask is not None:
        scores.masked_fill_(rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf"))
 
    local_mask = None
    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"))
 
    # Add custom attention bias if provided (for CPU tests)
    if attention_bias is not None:
        # The bias should only be applied to the relevant part of the scores matrix,
        # matching the sequence length of the bias tensor.
        scores[..., : attention_bias.shape[-1]] += attention_bias
 
    if use_smooth_softmax or (head_sink is not None):
        # Note that the sink directly joins softmax. No scaling and softcap is needed!
        attention = smooth_softmax_ref(scores, head_sink)
    else:
        attention = torch.softmax(scores, dim=-1)
 
    # Fill NaNs with 0
    if local_mask is not None:
        attention = attention.masked_fill(torch.all(local_mask, dim=-1, keepdim=True), 0.0)
    if query_padding_mask is not None:
        attention = attention.masked_fill(rearrange(~query_padding_mask, "b s -> b 1 s 1"), 0.0)
 
    output = torch.einsum("bhts,bshd->bthd", attention, v)
 
    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)
 
 
# #################################################################################################
# Parity Check (Core Test Logic)
# #################################################################################################
def get_static_scale(config: GQAConfig, device, torch_type, std):
    """Generates calibration data and computes the static quantization scale."""
    calibration_batch_size = 1
    calibration_sequence_length = 1024
    calibration_data_k = (
        torch.randn(
            calibration_batch_size,
            config.kv_num_heads,
            calibration_sequence_length,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
    calibration_data_v = torch.randn_like(calibration_data_k) * std
 
    # TODO: handle config.share_kv_scale here.
    k_scale = compute_scale(calibration_data_k, config.k_quant_type, config.kv_cache_type)
    if config.share_kv_scale:
        v_scale = k_scale
    else:
        v_scale = compute_scale(calibration_data_v, config.v_quant_type, config.kv_cache_type)
    return k_scale, v_scale
 
 
def parity_check_gqa_prompt(
    config: GQAConfig,
    ep,
    device,
    torch_type,
    ort_type,
    causal,
    rtol,
    atol,
    std=0.2,
):
    config.causal = causal
    torch.manual_seed(0)
    q = (
        torch.randn(
            config.batch_size,
            config.q_sequence_length,
            config.num_heads,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
 
    # Initialize the KV cache to zeros since no past context in prompt testing.
    cache_dtype = torch_type
    if config.kv_cache_type:
        cache_dtype = TORCH_DTYPE_MAP[config.kv_cache_type]
 
    k = torch.zeros(
        config.batch_size,
        config.kv_num_heads,
        config.buffer_sequence_length,
        config.head_size if config.kv_cache_bit_width != 4 else config.head_size // 2,
        device=device,
        dtype=cache_dtype,
    )
    v = torch.zeros_like(k)
 
    new_k = (
        torch.randn(
            config.batch_size,
            config.kv_sequence_length,
            config.kv_num_heads,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
    new_v = torch.randn_like(new_k) * std
 
    k_scale, v_scale = get_static_scale(config, device, torch_type, std)
    if k_scale is not None:
        k_scale = k_scale.to(torch_type)
    if v_scale is not None:
        v_scale = v_scale.to(torch_type)
 
    head_sink = torch.rand(config.num_heads, dtype=torch_type, device=device) if config.has_head_sink else None
    window_size = (-1, -1)
    if config.local_window_size > 0:
        window_size = (config.local_window_size, 0)
    elif causal:
        window_size = (-1, 0)
 
    if config.kv_cache_bit_width == 4 or config.kv_cache_type == "int8" or config.kv_cache_type == "fp8":
        # k/v are already quantized (int8/fp8) in inputs
        k_ref_dequant = dequantize_tensor(k, k_scale, config.k_quant_type, config.kv_cache_type)
        v_ref_dequant = dequantize_tensor(v, v_scale, config.v_quant_type, config.kv_cache_type)
    else:
        k_ref_dequant = dequantize_tensor(
            quantize_tensor_with_scale(
                k,
                k_scale.to(torch.float32) if k_scale is not None else None,
                config.k_quant_type,
                config.kv_cache_type,
            ),
            k_scale.to(torch.float32) if k_scale is not None else None,
            config.k_quant_type,
            config.kv_cache_type,
        )
        v_ref_dequant = dequantize_tensor(
            quantize_tensor_with_scale(
                v,
                v_scale.to(torch.float32) if v_scale is not None else None,
                config.v_quant_type,
                config.kv_cache_type,
            ),
            v_scale.to(torch.float32) if v_scale is not None else None,
            config.v_quant_type,
            config.kv_cache_type,
        )
    k_cache_ref = k_ref_dequant.clone().transpose(1, 2)
    v_cache_ref = v_ref_dequant.clone().transpose(1, 2)
    cache_seqlens = torch.full((config.batch_size,), config.kv_sequence_length, device=device, dtype=torch.int32)
    rotary_seqlens = torch.zeros(config.batch_size, device=device, dtype=torch.long)
 
    cos, sin, q_ro, k_ro = None, None, q, new_k
    q_norm_weight, k_norm_weight = None, None
    if config.has_qk_norm:
        q_norm_weight, k_norm_weight = make_qk_norm_weights(config.head_size, device, torch_type)
        q_ro = apply_qk_rmsnorm(q, q_norm_weight, config.qk_norm_epsilon)
        k_ro = apply_qk_rmsnorm(new_k, k_norm_weight, config.qk_norm_epsilon)
    if config.rotary:
        rotary_dim = math.floor(config.head_size / 16) * 16
        angle = torch.rand(config.buffer_sequence_length, rotary_dim // 2, device=device) * 2 * math.pi
        cos = torch.cos(angle).to(dtype=torch_type)
        sin = torch.sin(angle).to(dtype=torch_type)
        q_ro = apply_rotary_embedding(q_ro.clone(), cos, sin, rotary_seqlens, config.rotary_interleaved, device)
        k_ro = apply_rotary_embedding(k_ro.clone(), cos, sin, rotary_seqlens, config.rotary_interleaved, device)
 
    position_ids, attention_bias = None, None
    if config.has_position_ids:
        position_ids = (
            torch.arange(config.q_sequence_length, device=device)
            .unsqueeze(0)
            .expand(config.batch_size, -1)
            .contiguous()
        )
    if config.has_attention_bias:
        # Random (non-zero) bias so that a kernel silently ignoring the input fails parity.
        attention_bias = (
            torch.randn(
                1 if config.attention_bias_broadcast_dim_0 else config.batch_size,
                config.num_heads if config.attention_bias_per_head else 1,
                config.q_sequence_length,
                config.kv_sequence_length,
                device=device,
                dtype=torch_type,
            )
            * 0.5
        )
 
    arange = rearrange(torch.arange(config.buffer_sequence_length, device=device), "s -> 1 s")
    kv_seqlens_expanded = rearrange(cache_seqlens, "b -> b 1")
    update_mask = arange < kv_seqlens_expanded
 
    k_to_cache = k_ro
    v_to_cache = new_v
    if config.kv_cache_type != "none":
        k_scale_bsnh = k_scale
        v_scale_bsnh = v_scale
        if config.k_quant_type == "PER_CHANNEL" and k_scale is not None:
            k_scale_bsnh = k_scale.transpose(1, 2)  # (1, H, 1, D) -> (1, 1, H, D)
        if config.v_quant_type == "PER_CHANNEL" and v_scale is not None:
            v_scale_bsnh = v_scale.transpose(1, 2)  # (1, H, 1, D) -> (1, 1, H, D)
 
        k_to_cache = dequantize_tensor(
            quantize_tensor_with_scale(k_ro, k_scale_bsnh, config.k_quant_type, config.kv_cache_type),
            k_scale_bsnh,
            config.k_quant_type,
            config.kv_cache_type,
        ).to(torch_type)
        v_to_cache = dequantize_tensor(
            quantize_tensor_with_scale(new_v, v_scale_bsnh, config.v_quant_type, config.kv_cache_type),
            v_scale_bsnh,
            config.v_quant_type,
            config.kv_cache_type,
        ).to(torch_type)
 
    k_cache_ref[update_mask] = rearrange(k_to_cache, "b s ... -> (b s) ...").to(k_cache_ref.dtype)
    v_cache_ref[update_mask] = rearrange(v_to_cache, "b s ... -> (b s) ...").to(v_cache_ref.dtype)
 
    out_ref, _ = attention_ref(
        q=q_ro,
        k=k_ro,
        v=new_v,
        key_padding_mask=None,
        attention_bias=attention_bias,
        causal=causal,
        window_size=window_size,
        softcap=config.softcap,
        use_smooth_softmax=config.use_smooth_softmax,
        head_sink=head_sink,
    )
    out_ref_np = out_ref.to(torch.float32).detach().cpu().numpy()
 
    # --- ONNX Runtime Path ---
    q_ort, new_k_ort, new_v_ort = q, new_k, new_v
    if config.packed:
        q_ort = torch.cat([q, new_k, new_v], dim=2)
        new_k_ort, new_v_ort = None, None
 
    ort_seqlens = cache_seqlens - 1
    out, present_k, present_v = gqa_prompt_func(
        q=q_ort,
        k=k,
        v=v,
        config=config,
        new_k=new_k_ort,
        new_v=new_v_ort,
        cos=cos,
        sin=sin,
        seqlens_k=ort_seqlens,
        position_ids=position_ids,
        attention_bias=attention_bias,
        head_sink=head_sink,
        k_scale=k_scale,
        v_scale=v_scale,
        ep=ep,
        device=device,
        share_buffer=config.share_buffer,
        ort_type=ort_type,
        q_norm_weight=q_norm_weight,
        k_norm_weight=k_norm_weight,
    )
    out = torch.reshape(out, (config.batch_size, config.q_sequence_length, config.num_heads, config.head_size))
    out_np = out.to(torch.float32).detach().cpu().numpy()
 
    # --- Comparison ---
    # Check for NaN in output
    nan_count = numpy.sum(numpy.isnan(out_np))
    if nan_count > 0:
        nan_indices = numpy.argwhere(numpy.isnan(out_np))
        print(f"DEBUG_NAN: Found {nan_count} NaN values in output!")
        print(f"DEBUG_NAN: First 5 NaN indices: {nan_indices[:5]}")
        # Also check where non-nan exists in reference
        ref_nan_count = numpy.sum(numpy.isnan(out_ref_np))
        print(f"DEBUG_NAN: Reference has {ref_nan_count} NaN values")
 
    # Compare KV cache
    # Use float32 for comparison to support bfloat16 and avoid numpy issues
    # Transpose reference back to BNSH to match ORT output
    k_cache_ref_np = k_cache_ref.transpose(1, 2).to(torch.float32).detach().cpu().numpy()
    v_cache_ref_np = v_cache_ref.transpose(1, 2).to(torch.float32).detach().cpu().numpy()
    present_k_np = present_k.to(torch.float32).detach().cpu().numpy()
    present_v_np = present_v.to(torch.float32).detach().cpu().numpy()
 
    if not config.share_buffer:
        k_cache_ref_np = k_cache_ref_np[:, :, : config.kv_sequence_length, :]
        v_cache_ref_np = v_cache_ref_np[:, :, : config.kv_sequence_length, :]
 
    if config.k_quant_type == "NONE":
        numpy.testing.assert_allclose(present_k_np, k_cache_ref_np, rtol=rtol, atol=atol)
        numpy.testing.assert_allclose(present_v_np, v_cache_ref_np, rtol=rtol, atol=atol)
 
    print_diff_statistics(torch.tensor(out_np - out_ref_np), "out")
    numpy.testing.assert_allclose(out_np, out_ref_np, rtol=rtol, atol=atol)
 
    # Compare quantized cache with proper masking per batch
    if config.k_quant_type != "NONE":
        # Convert numpy array to torch tensor with correct dtype
        if isinstance(present_k, torch.Tensor):
            present_k_torch = present_k.to(device)
            # If tensor is int8/uint8, it should be preserved.
        else:
            if config.kv_cache_type == "int4":
                # For int4, present_k is uint8 packed data
                present_k_torch = torch.from_numpy(present_k).to(device)
            elif config.kv_cache_type == "int8":
                # For int8, present_k is int8 data
                present_k_torch = torch.from_numpy(present_k.astype(numpy.int8)).to(device)
            elif config.kv_cache_type == "fp8":
                # For fp8, present_k is float8_e4m3fn data, returned as uint8/int8 by ORT python
                present_k_torch = torch.from_numpy(present_k).view(torch.float8_e4m3fn).to(device)
            else:
                present_k_torch = torch.from_numpy(present_k).to(device)
 
        present_k_dequant = (
            dequantize_tensor(present_k_torch, k_scale, config.k_quant_type, config.kv_cache_type)
            .detach()
            .cpu()
            .numpy()
        )
 
        # Mask the reference cache to only valid regions
        k_cache_ref_masked = k_cache_ref.transpose(1, 2).clone()
        arange = torch.arange(config.buffer_sequence_length, device=device).unsqueeze(0).unsqueeze(0).unsqueeze(-1)
        cache_seqlens_expanded = cache_seqlens.unsqueeze(1).unsqueeze(1).unsqueeze(-1)
        mask = arange >= cache_seqlens_expanded
        k_cache_ref_masked[mask.expand_as(k_cache_ref_masked)] = 0
        k_cache_ref_dequant = k_cache_ref_masked.cpu().numpy()
 
        for b in range(config.batch_size):
            valid_len = cache_seqlens[b].item()
            print_diff_statistics(
                torch.tensor(present_k_dequant[b, :, :valid_len, :] - k_cache_ref_dequant[b, :, :valid_len, :]),
                f"present_k[{b}]",
            )
            numpy.testing.assert_allclose(
                present_k_dequant[b, :, :valid_len, :], k_cache_ref_dequant[b, :, :valid_len, :], rtol=rtol, atol=atol
            )
 
    if config.v_quant_type != "NONE":
        # Convert numpy array to torch tensor with correct dtype
        if isinstance(present_v, torch.Tensor):
            present_v_torch = present_v.to(device)
        else:
            if config.kv_cache_type == "int4":
                present_v_torch = torch.from_numpy(present_v).to(device)
            elif config.kv_cache_type == "int8":
                present_v_torch = torch.from_numpy(present_v.astype(numpy.int8)).to(device)
            elif config.kv_cache_type == "fp8":
                present_v_torch = torch.from_numpy(present_v).view(torch.float8_e4m3fn).to(device)
            else:
                present_v_torch = torch.from_numpy(present_v).to(device)
 
        present_v_dequant = (
            dequantize_tensor(present_v_torch, v_scale, config.v_quant_type, config.kv_cache_type)
            .detach()
            .cpu()
            .numpy()
        )
 
        # Mask the reference cache to only valid regions
        v_cache_ref_masked = v_cache_ref.transpose(1, 2).clone()
        arange = torch.arange(config.buffer_sequence_length, device=device).unsqueeze(0).unsqueeze(0).unsqueeze(-1)
        cache_seqlens_expanded = cache_seqlens.unsqueeze(1).unsqueeze(1).unsqueeze(-1)
        mask = arange >= cache_seqlens_expanded
        v_cache_ref_masked[mask.expand_as(v_cache_ref_masked)] = 0
        v_cache_ref_dequant = v_cache_ref_masked.cpu().numpy()
 
        for b in range(config.batch_size):
            valid_len = cache_seqlens[b].item()
            print_diff_statistics(
                torch.tensor(present_v_dequant[b, :, :valid_len, :] - v_cache_ref_dequant[b, :, :valid_len, :]),
                f"present_v[{b}]",
            )
            numpy.testing.assert_allclose(
                present_v_dequant[b, :, :valid_len, :], v_cache_ref_dequant[b, :, :valid_len, :], rtol=rtol, atol=atol
            )
 
 
def parity_check_gqa_past(
    config: GQAConfig,
    ep,
    device,
    torch_type,
    ort_type,
    causal,
    rtol,
    atol,
    std=0.2,
):
    config.causal = causal
    if ort_type == TensorProto.FLOAT16:
        torch_type = torch.float16
    elif ort_type == TensorProto.BFLOAT16:
        torch_type = torch.bfloat16
    else:
        torch_type = torch.float32
    torch.manual_seed(0)
    # --- Test Data Generation ---
    q = (
        torch.randn(
            config.batch_size,
            config.q_sequence_length,
            config.num_heads,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
    k = (
        torch.randn(
            config.batch_size,
            config.kv_num_heads,
            config.buffer_sequence_length,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
    v = torch.randn_like(k) * std
 
    # Random past sequence lengths. This tests paddings in decoding.
    # Use a separate generator to ensure deterministic behavior independent of prior RNG state.
    cache_seqlens_gen = torch.Generator(device=device).manual_seed(42)
    cache_seqlens = torch.randint(
        1,
        config.past_kv_sequence_length + 1,
        (config.batch_size,),
        device=device,
        dtype=torch.long,
        generator=cache_seqlens_gen,
    )
 
    for i in range(config.batch_size):
        past_len = cache_seqlens[i].item()
        k[i, :, past_len:, :] = 0
        v[i, :, past_len:, :] = 0
 
    new_k = (
        torch.randn(
            config.batch_size,
            config.kv_sequence_length,
            config.kv_num_heads,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
    new_v = torch.randn_like(new_k) * std
    head_sink = torch.rand(config.num_heads, dtype=torch_type, device=device) if config.has_head_sink else None
    window_size = (-1, -1)
    if config.local_window_size > 0:
        window_size = (config.local_window_size, 0)
    elif causal:
        window_size = (-1, 0)
 
    k_scale, v_scale = get_static_scale(config, device, torch_type, std)
    if k_scale is not None:
        k_scale = k_scale.to(torch_type)
    if v_scale is not None:
        v_scale = v_scale.to(torch_type)
 
    # --- PyTorch Reference Path ---
    # Transpose BNSH cache to BSNH format for reference implementation
 
    k_ref_dequant = dequantize_tensor(
        quantize_tensor_with_scale(k, k_scale, config.k_quant_type, config.kv_cache_type),
        k_scale,
        config.k_quant_type,
        config.kv_cache_type,
    )
    v_ref_dequant = dequantize_tensor(
        quantize_tensor_with_scale(v, v_scale, config.v_quant_type, config.kv_cache_type),
        v_scale,
        config.v_quant_type,
        config.kv_cache_type,
    )
    k_cache_ref = k_ref_dequant.clone().transpose(1, 2)
    v_cache_ref = v_ref_dequant.clone().transpose(1, 2)
 
    cos, sin, q_ro, k_ro = None, None, q, new_k
    q_norm_weight, k_norm_weight = None, None
    if config.has_qk_norm:
        q_norm_weight, k_norm_weight = make_qk_norm_weights(config.head_size, device, torch_type)
        q_ro = apply_qk_rmsnorm(q, q_norm_weight, config.qk_norm_epsilon)
        k_ro = apply_qk_rmsnorm(new_k, k_norm_weight, config.qk_norm_epsilon)
    if config.rotary:
        rotary_dim = math.floor(config.head_size / 16) * 16
        angle = torch.rand(config.buffer_sequence_length, rotary_dim // 2, device=device) * 2 * math.pi
        cos = torch.cos(angle).to(dtype=torch_type)
        sin = torch.sin(angle).to(dtype=torch_type)
        q_ro = apply_rotary_embedding(q_ro.clone(), cos, sin, cache_seqlens, config.rotary_interleaved, device)
        k_ro = apply_rotary_embedding(k_ro.clone(), cos, sin, cache_seqlens, config.rotary_interleaved, device)
 
    position_ids, attention_bias = None, None
    total_seq_len = config.past_kv_sequence_length + config.kv_sequence_length
    if config.has_position_ids:
        position_ids = (cache_seqlens.unsqueeze(1) + torch.arange(config.q_sequence_length, device=device)).long()
    if config.has_attention_bias:
        # Random (non-zero) bias so that a kernel silently ignoring the input fails parity.
        # Positions beyond each batch's valid length get a large negative finite value
        # (matching the CPU test convention; avoids inf-inf NaN when composed with masking).
        # A batch-broadcast bias (dim 0 == 1) cannot carry per-batch tails; it relies on
        # the kernel's seqlens_k cutoff and the reference mask never reading those
        # positions — which the dim0-broadcast past cases below verify holds.
        attention_bias = (
            torch.randn(
                1 if config.attention_bias_broadcast_dim_0 else config.batch_size,
                config.num_heads if config.attention_bias_per_head else 1,
                config.q_sequence_length,
                total_seq_len,
                device=device,
                dtype=torch_type,
            )
            * 0.5
        )
        if not config.attention_bias_broadcast_dim_0:
            for b in range(config.batch_size):
                end_pos = cache_seqlens[b] + config.q_sequence_length
                attention_bias[b, :, :, end_pos:] = -10000.0
 
    arange = rearrange(torch.arange(config.buffer_sequence_length, device=device), "s -> 1 s")
    cache_seqlens_expanded = rearrange(cache_seqlens, "b -> b 1")
    update_mask = torch.logical_and(
        cache_seqlens_expanded <= arange, arange < cache_seqlens_expanded + config.kv_sequence_length
    )
 
    k_to_cache = k_ro
    v_to_cache = new_v
    if config.kv_cache_type != "none":
        k_scale_bsnh = k_scale
        v_scale_bsnh = v_scale
        if config.k_quant_type == "PER_CHANNEL" and k_scale is not None:
            k_scale_bsnh = k_scale.transpose(1, 2)  # (1, H, 1, D) -> (1, 1, H, D)
        if config.v_quant_type == "PER_CHANNEL" and v_scale is not None:
            v_scale_bsnh = v_scale.transpose(1, 2)  # (1, H, 1, D) -> (1, 1, H, D)
 
        k_to_cache = dequantize_tensor(
            quantize_tensor_with_scale(k_ro, k_scale_bsnh, config.k_quant_type, config.kv_cache_type),
            k_scale_bsnh,
            config.k_quant_type,
            config.kv_cache_type,
        ).to(torch_type)
        v_to_cache = dequantize_tensor(
            quantize_tensor_with_scale(new_v, v_scale_bsnh, config.v_quant_type, config.kv_cache_type),
            v_scale_bsnh,
            config.v_quant_type,
            config.kv_cache_type,
        ).to(torch_type)
 
    k_cache_ref[update_mask] = rearrange(k_to_cache, "b s ... -> (b s) ...").to(k_cache_ref.dtype)
    v_cache_ref[update_mask] = rearrange(v_to_cache, "b s ... -> (b s) ...").to(v_cache_ref.dtype)
    key_padding_mask = arange < cache_seqlens_expanded + config.kv_sequence_length
 
    out_ref, _ = attention_ref(
        q=q_ro,
        k=k_cache_ref,
        v=v_cache_ref,
        key_padding_mask=key_padding_mask,
        attention_bias=attention_bias,
        causal=causal,
        window_size=window_size,
        softcap=config.softcap,
        use_smooth_softmax=config.use_smooth_softmax,
        head_sink=head_sink,
    )
    out_ref_np = out_ref.to(torch.float32).detach().cpu().numpy()
 
    # --- ONNX Runtime Path ---
 
    q_ort, new_k_ort, new_v_ort = q, new_k, new_v
    if config.packed:
        q_ort = torch.cat([q, new_k, new_v], dim=2)
        new_k_ort, new_v_ort = None, None
 
    # Quantize k and v for ORT when using quantized KV cache
    # Quantize k and v for ORT when using quantized KV cache
    k_ort = k
    v_ort = v
    if config.kv_cache_type in ["int8", "int4", "fp8"]:
        # NOTE: Quantize returns tensor with kv_cache_type (int8, int4, or fp8)
        k_ort = quantize_tensor_with_scale(k, k_scale, config.k_quant_type, config.kv_cache_type)
        v_ort = quantize_tensor_with_scale(v, v_scale, config.v_quant_type, config.kv_cache_type)
 
        # Ensure they are contiguous for binding
        k_ort = k_ort.contiguous()
        v_ort = v_ort.contiguous()
 
    ort_seqlens = cache_seqlens + config.kv_sequence_length - 1
 
    out, present_k, present_v = gqa_past_func(
        q=q_ort,
        k=k_ort,
        v=v_ort,
        config=config,
        new_k=new_k_ort,
        new_v=new_v_ort,
        cos=cos,
        sin=sin,
        seqlens_k=ort_seqlens.int(),
        position_ids=position_ids,
        attention_bias=attention_bias,
        head_sink=head_sink,
        k_scale=k_scale,
        v_scale=v_scale,
        ep=ep,
        device=device,
        share_buffer=config.share_buffer,
        ort_type=ort_type,
        q_norm_weight=q_norm_weight,
        k_norm_weight=k_norm_weight,
    )
    out = torch.reshape(out, (config.batch_size, config.q_sequence_length, config.num_heads, config.head_size))
    out_np = out.to(torch.float32).detach().cpu().numpy()
 
    if enable_debug_print:
        print(f"[DEBUG] out_np non-zeros: {numpy.count_nonzero(out_np)} / {out_np.size}")
        print(f"[DEBUG] out_ref_np non-zeros: {numpy.count_nonzero(out_ref_np)} / {out_ref_np.size}")
 
    if numpy.count_nonzero(out_ref_np) > 0 and numpy.count_nonzero(out_np) == 0:
        raise RuntimeError("Output is all zeros")
 
    print_diff_statistics(torch.tensor(out_np - out_ref_np), "out")
    numpy.testing.assert_allclose(out_np, out_ref_np, rtol=rtol, atol=atol)
 
    # --- Comparison ---
    compare_kv = (config.k_quant_type == "NONE" and config.v_quant_type == "NONE") or (config.kv_cache_type == "fp8")
    if compare_kv:
        # Compare KV cache
        # Transpose reference back to BNSH to match ORT output
        k_cache_ref_np = k_cache_ref.transpose(1, 2).to(torch.float32).detach().cpu().numpy()
        v_cache_ref_np = v_cache_ref.transpose(1, 2).to(torch.float32).detach().cpu().numpy()
 
        if isinstance(present_k, torch.Tensor):
            present_k_torch = present_k.to(device)
            present_v_torch = present_v.to(device)
        else:
            present_k_torch = torch.from_numpy(present_k).to(device)
            present_v_torch = torch.from_numpy(present_v).to(device)
 
        if config.kv_cache_type == "fp8":
            # FP8 cache needs dequantization for comparison with float reference
            present_k_dequant = dequantize_tensor(present_k_torch, k_scale, config.k_quant_type, config.kv_cache_type)
            present_v_dequant = dequantize_tensor(present_v_torch, v_scale, config.v_quant_type, config.kv_cache_type)
            present_k_np = present_k_dequant.to(torch.float32).detach().cpu().numpy()
            present_v_np = present_v_dequant.to(torch.float32).detach().cpu().numpy()
        else:
            present_k_np = present_k_torch.to(torch.float32).detach().cpu().numpy()
            present_v_np = present_v_torch.to(torch.float32).detach().cpu().numpy()
 
        numpy.testing.assert_allclose(present_k_np, k_cache_ref_np, rtol=rtol, atol=atol)
        numpy.testing.assert_allclose(present_v_np, v_cache_ref_np, rtol=rtol, atol=atol)
 
    # Compare quantized cache with proper masking per batch
    if config.k_quant_type != "NONE":
        if isinstance(present_k, torch.Tensor):
            present_k_torch = present_k.to(device)
        else:
            if config.kv_cache_type == "int4":
                present_k_torch = torch.from_numpy(present_k).to(device)
            elif config.kv_cache_type == "int8":
                present_k_torch = torch.from_numpy(present_k.astype(numpy.int8)).to(device)
            elif config.kv_cache_type == "fp8":
                present_k_torch = torch.from_numpy(present_k).view(torch.float8_e4m3fn).to(device)
            else:
                present_k_torch = torch.from_numpy(present_k).to(device)
 
        present_k_dequant = (
            dequantize_tensor(present_k_torch, k_scale, config.k_quant_type, config.kv_cache_type)
            .detach()
            .cpu()
            .numpy()
        )
 
        # Mask the reference cache to only valid regions
        k_cache_ref_masked = k_cache_ref.transpose(1, 2).clone()
        total_seqlens = cache_seqlens + config.q_sequence_length
        arange = torch.arange(config.buffer_sequence_length, device=device).unsqueeze(0).unsqueeze(0).unsqueeze(-1)
        total_seqlens_expanded = total_seqlens.unsqueeze(1).unsqueeze(1).unsqueeze(-1)
        mask = arange >= total_seqlens_expanded
        k_cache_ref_masked[mask.expand_as(k_cache_ref_masked)] = 0
        k_cache_ref_dequant = k_cache_ref_masked.cpu().numpy()
 
        for b in range(config.batch_size):
            valid_len = (cache_seqlens[b] + config.q_sequence_length).item()
            print_diff_statistics(
                torch.tensor(present_k_dequant[b, :, :valid_len, :] - k_cache_ref_dequant[b, :, :valid_len, :]),
                f"present_k[{b}]",
            )
            numpy.testing.assert_allclose(
                present_k_dequant[b, :, :valid_len, :],
                k_cache_ref_dequant[b, :, :valid_len, :],
                rtol=rtol,
                atol=atol,
            )
 
    if config.v_quant_type != "NONE":
        if isinstance(present_v, torch.Tensor):
            present_v_torch = present_v.to(device)
        else:
            if config.kv_cache_type == "int4":
                present_v_torch = torch.from_numpy(present_v).to(device)
            elif config.kv_cache_type == "int8":
                present_v_torch = torch.from_numpy(present_v.astype(numpy.int8)).to(device)
            elif config.kv_cache_type == "fp8":
                present_v_torch = torch.from_numpy(present_v).view(torch.float8_e4m3fn).to(device)
            else:
                present_v_torch = torch.from_numpy(present_v).to(device)
 
        present_v_dequant = (
            dequantize_tensor(present_v_torch, v_scale, config.v_quant_type, config.kv_cache_type)
            .detach()
            .cpu()
            .numpy()
        )
 
        # Mask the reference cache to only valid regions
        v_cache_ref_masked = v_cache_ref.transpose(1, 2).clone()
        total_seqlens = cache_seqlens + config.q_sequence_length
        arange = torch.arange(config.buffer_sequence_length, device=device).unsqueeze(0).unsqueeze(0).unsqueeze(-1)
        total_seqlens_expanded = total_seqlens.unsqueeze(1).unsqueeze(1).unsqueeze(-1)
        mask = arange >= total_seqlens_expanded
        v_cache_ref_masked[mask.expand_as(v_cache_ref_masked)] = 0
        v_cache_ref_dequant = v_cache_ref_masked.cpu().numpy()
 
        for b in range(config.batch_size):
            valid_len = (cache_seqlens[b] + config.q_sequence_length).item()
            print_diff_statistics(
                torch.tensor(present_v_dequant[b, :, :valid_len, :] - v_cache_ref_dequant[b, :, :valid_len, :]),
                f"present_v[{b}]",
            )
            numpy.testing.assert_allclose(
                present_v_dequant[b, :, :valid_len, :],
                v_cache_ref_dequant[b, :, :valid_len, :],
                rtol=rtol,
                atol=atol,
            )
 
 
def parity_test_gqa_padding_prompt():
    device = "cuda"
    torch_type = torch.float16
    ort_type = TensorProto.FLOAT16
 
    # config
    config = GQAConfig(
        batch_size=2,
        q_sequence_length=16,
        kv_sequence_length=16,
        num_heads=8,
        kv_num_heads=2,
        head_size=128,
        buffer_sequence_length=16,
        share_buffer=True,
        packed=False,
        rotary=True,
    )
 
    # Inputs
    torch.manual_seed(0)
    std = 0.02
    q = (
        torch.randn(
            config.batch_size,
            config.q_sequence_length,
            config.num_heads,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
    k = (
        torch.randn(
            config.batch_size,
            config.kv_num_heads,
            config.kv_sequence_length,
            config.head_size,
            device=device,
            dtype=torch_type,
        )
        * std
    )
    v = torch.randn_like(k) * std
 
    new_k = k.transpose(1, 2).contiguous()
    new_v = v.transpose(1, 2).contiguous()
 
    seqlens_k = torch.tensor([9, 15], dtype=torch.int32, device=device)
 
    # Generate Rotary Embeddings
    rotary_dim = config.head_size
    max_seq_len = config.buffer_sequence_length
    cos = torch.randn(1, max_seq_len, 1, rotary_dim // 2, device=device, dtype=torch_type)
    sin = torch.randn(1, max_seq_len, 1, rotary_dim // 2, device=device, dtype=torch_type)
 
    # Apply Rotary to inputs for Reference
    rotary_op = LlamaMSRotaryEmbedding()
    pos = torch.zeros(config.batch_size, device=device, dtype=torch.long)
 
    # In ORT, we pass raw Q/K and ORT applies rotary.
    # For REF, we must apply rotary manually.
    # But wait, ORT only rotates 'q' and 'k' inside the attention kernel.
    # Wait, if `share_buffer=True`, `past_key` is used.
    # In prompt mode, `new_k` is appended to `past_key`.
    # ORT will apply rotary to Q.
    # Does ORT apply rotary to K? Yes, if `do_rotary` is true.
    # So we rotate Q and K for REF.
 
    q_ref = rotary_op.rotate_tensor(q, cos, sin, pos, False)
    k_ref = rotary_op.rotate_tensor(new_k, cos, sin, pos, False)
    v_ref = new_v
 
    # Run ONNX Runtime
    out_ort, present_key_ort, present_value_ort = gqa_prompt_func(
        q=q,
        k=k,
        v=v,
        config=config,
        new_k=new_k,
        new_v=new_v,
        cos=cos.squeeze(2).squeeze(0),
        sin=sin.squeeze(2).squeeze(0),
        seqlens_k=seqlens_k,
        position_ids=None,
        attention_bias=None,
        head_sink=None,
        k_scale=None,
        v_scale=None,
        ep="CUDAExecutionProvider",
        device=device,
        share_buffer=config.share_buffer,
        ort_type=ort_type,
    )
 
    # Compare present_key and present_value with reference
    # ORT present_key is BNSH format: [batch, kv_num_heads, seq, head_size]
    # k_ref is BSNH format: [batch, seq, kv_num_heads, head_size]
    # Transpose k_ref to BNSH for comparison
    k_ref_bnsh = k_ref.transpose(1, 2)  # BSNH -> BNSH
    v_ref_bnsh = v_ref.transpose(1, 2)  # BSNH -> BNSH
 
    # Compare only valid positions (positions 0..9 for Batch 0, 0..15 for Batch 1)
    torch.testing.assert_close(present_key_ort[0, :, :10, :], k_ref_bnsh[0, :, :10, :], rtol=1e-3, atol=1e-3)
    torch.testing.assert_close(present_key_ort[1, :, :16, :], k_ref_bnsh[1, :, :16, :], rtol=1e-3, atol=1e-3)
    torch.testing.assert_close(present_value_ort[0, :, :10, :], v_ref_bnsh[0, :, :10, :], rtol=1e-3, atol=1e-3)
    torch.testing.assert_close(present_value_ort[1, :, :16, :], v_ref_bnsh[1, :, :16, :], rtol=1e-3, atol=1e-3)
 
    # Run Reference
    # key_padding_mask is a "Validity Mask" where True=Valid, False=Invalid
    key_padding_mask = torch.zeros((config.batch_size, config.q_sequence_length), dtype=torch.bool, device=device)
 
    # Batch 0: Valid 0..9 (length 10)
    key_padding_mask[0, :10] = True
 
    # Batch 1: Valid 0..15 (length 16)
    key_padding_mask[1, :16] = True
 
    out_ref, _ = attention_ref(
        q_ref, k_ref, v_ref, key_padding_mask=key_padding_mask, query_padding_mask=key_padding_mask, causal=True
    )
 
    # Compare
    # Batch 0: 10..15 are padding
    out_ort[0, 10:] = 0
    out_ref[0, 10:] = 0
 
    # Reshape ref to match ORT
    out_ref = out_ref.reshape(config.batch_size, config.q_sequence_length, -1)
 
    # Debugging
    diff = (out_ort - out_ref).abs()
    max_diff = diff.max()
    # Check Batch 0
    b0_diff = diff[0].max()
    # Check Batch 1
    b1_diff = diff[1].max()
 
    if not torch.allclose(out_ort, out_ref, rtol=1e-2, atol=1e-2):
        msg = f"Mismatch! Max Diff: {max_diff}, Batch 0 Max: {b0_diff}, Batch 1 Max: {b1_diff}\n"
        raise AssertionError(msg)
 
    torch.testing.assert_close(out_ort, out_ref, rtol=1e-2, atol=1e-2)
 
 
# #################################################################################################
#  Test Utilities
# #################################################################################################
 
 
def print_diff_statistics(diff_tensor: torch.Tensor, prefix: str = ""):
    """
    Print percentile statistics (75%, 95%, 99%) for a difference tensor.
    This helps assess parity quality beyond just max difference.
 
    Args:
        diff_tensor: Tensor containing absolute differences between expected and actual outputs.
        prefix: Optional prefix string for the output message.
    """
    if not enable_debug_print:
        return
 
    diff_flat = diff_tensor.flatten().float()
    if diff_flat.numel() == 0:
        print(f"{prefix}Diff statistics: empty tensor")
        return
 
    # Compute percentiles
    sorted_diff, _ = torch.sort(diff_flat)
    n = sorted_diff.numel()
 
    p75_idx = min(int(n * 0.75), n - 1)
    p90_idx = min(int(n * 0.90), n - 1)
    p95_idx = min(int(n * 0.95), n - 1)
    p99_idx = min(int(n * 0.99), n - 1)
    p999_idx = min(int(n * 0.999), n - 1)
 
    p75 = sorted_diff[p75_idx].item()
    p90 = sorted_diff[p90_idx].item()
    p95 = sorted_diff[p95_idx].item()
    p99 = sorted_diff[p99_idx].item()
    p999 = sorted_diff[p999_idx].item()
    max_val = sorted_diff[-1].item()
    mean_val = diff_flat.mean().item()
 
    print(
        f"{prefix} Diff stats - mean: {mean_val:.6f}, p75: {p75:.6f}, p90: {p90:.6f}, p95: {p95:.6f}, p99: {p99:.6f}, p999: {p999:.6f}, max: {max_val:.6f}"
    )
 
 
# #################################################################################################
#  Test Case Generators
# #################################################################################################
 
 
def get_cuda_rotary_options():
    return [(False, False), (True, False), (True, True)]
 
 
def get_cpu_rotary_options():
    return [(False, False), (True, False), (True, True)]
 
 
def get_softmax_options(allow_head_sink: bool = True):
    options = [(False, False), (False, True), (True, False)]
    if not allow_head_sink:
        options = [opt for opt in options if not opt[1]]
    return options
 
 
def gqa_cuda_prompt_test_cases(allow_head_sink: bool = True, allow_local: bool = True):
    batches = [3, 1, 5]
    seqs = [(35, 35), (1, 1), (64, 64), (128, 128), (240, 240), (2000, 2000)]
    heads = [(6, 3), (3, 1), (32, 8)]
    h_sizes = [128] if quick_build else [128, 32, 64, 80, 160, 256]
    smmoth_softmax__head_sink = get_softmax_options(allow_head_sink)
 
    rotary_opts = list(get_cuda_rotary_options())
    packed_opts = [False, True]
    share_buffer_opts = [True, False]
    softcap_opts = [0.0, 50.0]
 
    # Use new strategy for both modes: iterate over key code path parameters
    # The difference between modes is the number of head_sizes tested
    # Pipeline mode: h_sizes[:1] = [128] -> 12 combinations (fast)
    # Comprehensive mode: all h_sizes -> 40+ combinations (thorough)
    h_sizes_to_test = h_sizes[:1] if pipeline_mode else h_sizes
 
    combo_index = 0
    for h in h_sizes_to_test:
        for packed in packed_opts:
            for rotary, rotary_interleaved in rotary_opts:
                # Skip invalid: rotary requires head_size divisible by 16
                if rotary and h % 16 > 0:
                    continue
 
                for share_buffer in share_buffer_opts:
                    # Rotate secondary parameters
                    b = batches[combo_index % len(batches)]
                    sq, skv = seqs[combo_index % len(seqs)]
                    n, n2 = heads[combo_index % len(heads)]
                    lws_opts = [-1, max(1, skv // 2)] if allow_local else [-1]
                    lws = lws_opts[combo_index % len(lws_opts)]
                    softcap = softcap_opts[combo_index % len(softcap_opts)]
                    use_smooth_softmax, has_head_sink = smmoth_softmax__head_sink[
                        combo_index % len(smmoth_softmax__head_sink)
                    ]
                    has_position_ids = False if pipeline_mode else combo_index % 2 == 0
 
                    combo_index += 1
 
                    if softcap > 0 and (use_smooth_softmax or has_head_sink):
                        continue
 
                    config = GQAConfig(
                        batch_size=b,
                        q_sequence_length=sq,
                        kv_sequence_length=skv,
                        past_kv_sequence_length=0,
                        buffer_sequence_length=sq + skv + 8,
                        num_heads=n,
                        kv_num_heads=n2,
                        head_size=h,
                        local_window_size=lws,
                        rotary=rotary,
                        rotary_interleaved=rotary_interleaved,
                        packed=packed,
                        share_buffer=share_buffer,
                        softcap=softcap,
                        use_smooth_softmax=use_smooth_softmax,
                        has_head_sink=has_head_sink,
                        has_position_ids=has_position_ids,
                    )
                    name = f"b{b}_sq{sq}_skv{skv}_nh{n}_{n2}_h{h}_w{lws}_rot{rotary}{rotary_interleaved}_pkd{packed}_sb{share_buffer}_sc{softcap}_sm{use_smooth_softmax}_{has_head_sink}_pid{has_position_ids}"
                    yield name, config
 
 
def gqa_cuda_past_test_cases(
    allow_head_sink: bool = True, allow_local: bool = True, enforce_share_buffer: bool = False
):
    batches = [2, 1, 3]
    # s: new sequence length, s2: past sequence length``
    seqs = [(1, 1), (1, 128), (1, 2048), (1, 5000)]
    subsequent_prompt_seqs = [(3, 256)]
    heads = [(32, 8), (6, 3), (9, 9)]
    h_sizes = [128] if quick_build else [128, 40, 64, 80, 256]
    smmoth_softmax__head_sink = get_softmax_options(allow_head_sink)
 
    rotary_opts = list(get_cuda_rotary_options())
    packed_opts = [False, True]
    # For past test: pipeline tests share_buffer=True only, comprehensive tests both
    share_buffer_opts = [True] if pipeline_mode or enforce_share_buffer else [True, False]
    softcap_opts = [0.0, 50.0]
 
    # Use new strategy for both modes: iterate over key code path parameters
    # The difference between modes is the number of head_sizes tested
    # Pipeline mode: h_sizes[:1] = [128] -> 6 combinations (share_buffer=[True] only)
    # Comprehensive mode: all h_sizes -> 36+ combinations
    h_sizes_to_test = h_sizes[:1] if pipeline_mode else h_sizes
    all_seqs = seqs + subsequent_prompt_seqs
 
    combo_index = 0
    for h in h_sizes_to_test:
        for packed in packed_opts:
            for rotary, rotary_interleaved in rotary_opts:
                # Skip invalid: rotary requires head_size divisible by 16
                if rotary and h % 16 > 0:
                    continue
 
                for share_buffer in share_buffer_opts:
                    # Rotate secondary parameters
                    b = batches[combo_index % len(batches)]
                    s, s2 = all_seqs[combo_index % len(all_seqs)]
 
                    # Skip subsequent prompt for batch > 1
                    if s > 1 and b > 1:
                        b = 1  # Force batch=1 for subsequent prompt
 
                    n, n2 = heads[combo_index % len(heads)]
                    lws_opts = [-1, max(1, s2 // 2)] if allow_local else [-1]
                    lws = lws_opts[combo_index % len(lws_opts)]
                    softcap = softcap_opts[combo_index % len(softcap_opts)]
                    use_smooth_softmax, has_head_sink = smmoth_softmax__head_sink[
                        combo_index % len(smmoth_softmax__head_sink)
                    ]
                    has_position_ids = False if pipeline_mode else s > 1
 
                    combo_index += 1
 
                    if softcap > 0 and (use_smooth_softmax or has_head_sink):
                        continue
 
                    config = GQAConfig(
                        batch_size=b,
                        q_sequence_length=s,
                        kv_sequence_length=s,
                        past_kv_sequence_length=s2,
                        buffer_sequence_length=s + s2 + 8,
                        num_heads=n,
                        kv_num_heads=n2,
                        head_size=h,
                        local_window_size=lws,
                        rotary=rotary,
                        rotary_interleaved=rotary_interleaved,
                        packed=packed,
                        share_buffer=share_buffer,
                        softcap=softcap,
                        use_smooth_softmax=use_smooth_softmax,
                        has_head_sink=has_head_sink,
                        has_position_ids=has_position_ids,
                    )
                    name = f"b{b}_s{s}_{s2}_nh{n}_{n2}_h{h}_w{lws}_rot{rotary}{rotary_interleaved}_pkd{packed}_sb{share_buffer}_sc{softcap}_sm{use_smooth_softmax}_{has_head_sink}_pid{has_position_ids}"
                    yield name, config
 
 
def gqa_cuda_attention_bias_test_cases(is_past: bool):
    """Focused cases for the attention_bias input. Dispatch must route these away from
    the bias-incapable fused paths (flash/XQA/cuDNN), so no kernel-pinning env vars are
    needed. Covers packed/unpacked QKV, shared/separate KV buffer, rotary, odd head
    sizes (unfused supports any head_size) and a subsequent multi-token prompt."""
    if is_past:
        # (batch, new_seq, past_seq, num_heads, kv_num_heads, head_size, packed, share_buffer,
        #  rotary, per_head_bias)
        cases = [
            (2, 1, 128, 32, 8, 128, False, True, False, False),
            (1, 1, 2048, 6, 3, 128, True, True, True, False),
            (3, 1, 500, 9, 9, 80, False, False, False, False),
            (1, 3, 256, 6, 3, 128, True, True, False, False),  # subsequent prompt
            (2, 1, 128, 6, 3, 40, False, True, False, False),  # odd head size
            (2, 1, 128, 32, 8, 128, False, True, False, True),  # per-head bias (dim 1 == num_heads)
        ]
        cases = [(*c, False) for c in cases] + [
            (3, 1, 500, 9, 9, 80, False, False, False, False, True),  # batch-broadcast bias (dim 0 == 1)
            (2, 1, 128, 6, 3, 40, False, True, False, False, True),  # batch-broadcast, shared buffer
        ]
        for b, s, s2, n, n2, h, packed, share_buffer, rotary, per_head, bcast0 in cases:
            # The past-parity harness compares the full present buffer; without buffer
            # sharing the op emits exactly past+new, so the buffer must match that size.
            config = GQAConfig(
                batch_size=b,
                q_sequence_length=s,
                kv_sequence_length=s,
                past_kv_sequence_length=s2,
                buffer_sequence_length=s + s2 + (8 if share_buffer else 0),
                num_heads=n,
                kv_num_heads=n2,
                head_size=h,
                rotary=rotary,
                packed=packed,
                share_buffer=share_buffer,
                has_attention_bias=True,
                attention_bias_per_head=per_head,
                attention_bias_broadcast_dim_0=bcast0,
            )
            name = (
                f"bias_b{b}_s{s}_{s2}_nh{n}_{n2}_h{h}_pkd{packed}_sb{share_buffer}_rot{rotary}_ph{per_head}_bc0{bcast0}"
            )
            yield name, config
    else:
        # (batch, seq, num_heads, kv_num_heads, head_size, packed, share_buffer, rotary,
        #  bias_broadcast_dim_0, per_head_bias)
        cases = [
            (2, 127, 6, 3, 128, False, True, False, False, False),
            (1, 500, 32, 8, 128, True, True, True, False, False),
            (3, 64, 9, 9, 80, False, False, False, False, False),
            (2, 127, 6, 3, 40, True, True, False, False, False),  # odd head size
            (3, 64, 9, 9, 80, False, False, False, True, False),  # batch-broadcast bias (dim 0 == 1)
            (2, 127, 6, 3, 128, False, True, False, False, True),  # per-head bias (dim 1 == num_heads)
        ]
        for b, sq, n, n2, h, packed, share_buffer, rotary, bcast0, per_head in cases:
            config = GQAConfig(
                batch_size=b,
                q_sequence_length=sq,
                kv_sequence_length=sq,
                past_kv_sequence_length=0,
                buffer_sequence_length=sq + 8,
                num_heads=n,
                kv_num_heads=n2,
                head_size=h,
                rotary=rotary,
                packed=packed,
                share_buffer=share_buffer,
                has_attention_bias=True,
                attention_bias_broadcast_dim_0=bcast0,
                attention_bias_per_head=per_head,
            )
            name = f"bias_b{b}_sq{sq}_nh{n}_{n2}_h{h}_pkd{packed}_sb{share_buffer}_rot{rotary}_bc0{bcast0}_ph{per_head}"
            yield name, config
 
 
def gqa_cuda_quantized_test_cases(is_past: bool):
    base_cases = (
        gqa_cuda_past_test_cases(allow_local=True, enforce_share_buffer=True)
        if is_past
        else gqa_cuda_prompt_test_cases(allow_local=True)
    )
 
    kv_types = ["int8"]
    if has_int4_kv_cache:
        kv_types.append("int4")
    if has_fp8_kv_cache:
        kv_types.append("fp8")
 
    for name, config in base_cases:
        for kv_type in kv_types:
            for quant_mode in ["PER_TENSOR", "PER_CHANNEL"]:
                share_scales_options = [False]
                if quant_mode == "PER_TENSOR" and kv_type == "int8":
                    share_scales_options = [True]
 
                for share_scales in share_scales_options:
                    q_config = deepcopy(config)
                    q_config.k_quant_type = quant_mode
                    q_config.v_quant_type = quant_mode
                    q_config.kv_cache_type = kv_type
                    q_config.share_kv_scale = share_scales
 
                    if kv_type == "int4":
                        if q_config.head_size % 2 != 0:
                            continue
                        q_config.kv_cache_bit_width = 4
                    elif kv_type == "int8":
                        q_config.kv_cache_bit_width = 8
                    elif kv_type == "fp8":
                        q_config.kv_cache_bit_width = 8
 
                    q_name = f"{name}_quant_{kv_type}_{quant_mode}"
                    if share_scales:
                        q_name += "_shared"
                    yield q_name, q_config
 
 
# #################################################################################################
#  Unit Test Classes
# #################################################################################################
 
 
def has_cuda_provider():
    return get_cuda_provider_name() is not None
 
 
def has_cuda_device(min_capability: int = 80):
    if not has_cuda_provider() or not torch.cuda.is_available():
        return False
    major, minor = torch.cuda.get_device_capability()
    return major * 10 + minor >= min_capability
 
 
def has_flash_attention(bf16=False):
    if not has_cuda_device(80):
        return False
    if bf16:
        return torch.cuda.is_bf16_supported()
    return True
 
 
def has_xqa():
    # The XQA decode kernels require Ampere (SM 8.0) or newer.
    return has_cuda_device(80)
 
 
def has_fp8_xqa():
    # FP8 XQA kernels require Hopper (SM 8.9) or newer.
    return has_cuda_device(89)
 
 
rtol = {
    "fp16": 5e-3,
    "bf16": 5e-2,
    "int8_fp16": 5e-2,
    "int4_fp16": 5e-2,
    "int8_bf16": 5e-2,
    "int4_bf16": 5e-2,
    "fp8_fp16": 5e-2,
    "fp8_bf16": 5e-2,
}
atol = {
    "fp16": 5e-3,
    "bf16": 1e-2,
    "int8_fp16": 1e-1,
    "int4_fp16": 1e-1,
    "int8_bf16": 2e-1,
    "int4_bf16": 2e-1,
    "fp8_fp16": 1e-1,
    "fp8_bf16": 2e-1,
}
 
 
def has_quantized_kv_cache():
    return version.parse(ort_version) >= version.parse("1.25.0")
 
 
@unittest.skipIf(not has_flash_attention(), "Flash Attention is not available, skipping tests.")
class TestFlashGQA(unittest.TestCase):
    def tearDown(self):
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_cuda_prompt_test_cases())
    def test_gqa_prompt_flash_attention(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    def test_gqa_prompt_feature_interactions(self):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=4,
            kv_sequence_length=4,
            buffer_sequence_length=12,
            num_heads=4,
            kv_num_heads=2,
            head_size=64,
            rotary=True,
            rotary_interleaved=True,
            softcap=2.0,
            has_attention_bias=True,
            attention_bias_per_head=True,
            has_qk_norm=True,
            share_buffer=True,
        )
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    def test_gqa_prompt_bidirectional_attention_bias_broadcast(self):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=4,
            kv_sequence_length=4,
            buffer_sequence_length=12,
            num_heads=4,
            kv_num_heads=2,
            head_size=64,
            rotary=True,
            has_attention_bias=True,
            attention_bias_broadcast_dim_0=True,
            attention_bias_per_head=False,
            share_buffer=True,
        )
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=False,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    def test_gqa_decode_rotary_head_sink_softcap_qk_norm_batch(self):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=63,
            buffer_sequence_length=72,
            num_heads=8,
            kv_num_heads=2,
            head_size=64,
            rotary=True,
            softcap=2.0,
            has_head_sink=True,
            has_qk_norm=True,
            share_buffer=True,
        )
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    def test_gqa_decode_bidirectional(self):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=2,
            kv_sequence_length=2,
            past_kv_sequence_length=4,
            buffer_sequence_length=8,
            num_heads=4,
            kv_num_heads=2,
            head_size=64,
            share_buffer=True,
        )
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=False,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    @unittest.skipUnless(has_quantized_kv_cache(), "Quantized KV cache is not available")
    def test_gqa_decode_rotary_quantized_head_sink_batch(self):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=63,
            buffer_sequence_length=72,
            num_heads=8,
            kv_num_heads=2,
            head_size=64,
            rotary=True,
            has_head_sink=True,
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_CHANNEL",
            kv_cache_type="int8",
            kv_cache_bit_width=8,
            share_buffer=True,
        )
 
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch.float16,
            ort_type=TensorProto.FLOAT16,
            causal=True,
            rtol=rtol["int8_fp16"],
            atol=atol["int8_fp16"],
        )
 
    @parameterized.expand(gqa_cuda_past_test_cases())
    def test_gqa_past_flash_attention(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
 
@unittest.skipIf(not has_cuda_device(53), "Quantized bidirectional GQA requires a CUDA GPU, skipping tests.")
@unittest.skipUnless(has_quantized_kv_cache(), "Quantized KV cache is not available")
class TestQuantizedBidirectionalGQA(unittest.TestCase):
    @staticmethod
    def _config():
        return GQAConfig(
            batch_size=1,
            q_sequence_length=2,
            kv_sequence_length=2,
            past_kv_sequence_length=4,
            buffer_sequence_length=8,
            num_heads=4,
            kv_num_heads=2,
            head_size=64,
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_TENSOR",
            kv_cache_type="int8",
            kv_cache_bit_width=8,
            share_buffer=True,
        )
 
    @unittest.skipIf(not has_flash_attention(), "Flash Attention is not available")
    def test_gqa_past_flash_attention(self):
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=self._config(),
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=False,
                rtol=rtol["int8_fp16"],
                atol=atol["int8_fp16"],
            )
 
    def test_gqa_past_without_supported_backend(self):
        with (
            scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "1"),
            self.assertRaisesRegex(Exception, "No available GroupQueryAttention kernel supports"),
        ):
            parity_check_gqa_past(
                config=self._config(),
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=False,
                rtol=rtol["int8_fp16"],
                atol=atol["int8_fp16"],
            )
 
 
@unittest.skipIf(not has_flash_attention(bf16=True), "Flash Attention is not available, skipping tests.")
class TestFlashGQABF16(unittest.TestCase):
    def tearDown(self):
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_cuda_prompt_test_cases())
    def test_gqa_prompt_flash_attention_bf16(self, name, config):
        if not torch.cuda.is_bf16_supported():
            self.skipTest("BFloat16 not supported on this device")
 
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        config.kv_cache_type = "bfloat16"
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.bfloat16,
                ort_type=TensorProto.BFLOAT16,
                causal=True,
                rtol=rtol["bf16"],
                atol=atol["bf16"],
            )
 
    @parameterized.expand(gqa_cuda_past_test_cases())
    def test_gqa_past_flash_attention_bf16(self, name, config):
        if not torch.cuda.is_bf16_supported():
            self.skipTest("BFloat16 not supported on this device")
 
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        config.kv_cache_type = "bfloat16"
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.bfloat16,
                ort_type=TensorProto.BFLOAT16,
                causal=True,
                rtol=rtol["bf16"],
                atol=atol["bf16"],
            )
 
 
def gqa_qk_norm_test_cases(is_past: bool):
    """Configs exercising the fused per-head Q/K RMSNorm (QK-Norm) prologue before RoPE."""
    head_sizes = [64, 128]
    head_groups = [(8, 2), (4, 4)]
    rotary_opts = [(False, False), (True, False), (True, True)]
    packed_opts = [False, True]
    idx = 0
    for h in head_sizes:
        for n, n2 in head_groups:
            for rotary, interleaved in rotary_opts:
                if rotary and h % 16 != 0:
                    continue
                packed = packed_opts[idx % len(packed_opts)]
                idx += 1
                if is_past:
                    b, s, s2 = 2, 1, 127
                    config = GQAConfig(
                        batch_size=b,
                        q_sequence_length=s,
                        kv_sequence_length=s,
                        past_kv_sequence_length=s2,
                        buffer_sequence_length=s + s2 + 8,
                        num_heads=n,
                        kv_num_heads=n2,
                        head_size=h,
                        rotary=rotary,
                        rotary_interleaved=interleaved,
                        packed=packed,
                        share_buffer=True,
                        has_qk_norm=True,
                    )
                else:
                    b, s = 2, 64
                    config = GQAConfig(
                        batch_size=b,
                        q_sequence_length=s,
                        kv_sequence_length=s,
                        buffer_sequence_length=s + 8,
                        num_heads=n,
                        kv_num_heads=n2,
                        head_size=h,
                        rotary=rotary,
                        rotary_interleaved=interleaved,
                        packed=packed,
                        share_buffer=True,
                        has_qk_norm=True,
                    )
                name = f"{'past' if is_past else 'prompt'}_b{b}_nh{n}_{n2}_h{h}_rot{rotary}{interleaved}_pkd{packed}"
                yield name, config
 
 
@unittest.skipIf(not has_cuda_device(80), "CUDA GQA QK-Norm requires Ampere or higher GPU, skipping tests.")
class TestGQAQKNorm(unittest.TestCase):
    def tearDown(self):
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_qk_norm_test_cases(is_past=False))
    def test_gqa_qk_norm_prompt(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    @parameterized.expand(gqa_qk_norm_test_cases(is_past=True))
    def test_gqa_qk_norm_past(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    def test_gqa_qk_norm_past_xqa(self):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=127,
            buffer_sequence_length=136,
            num_heads=32,
            kv_num_heads=8,
            head_size=128,
            rotary=True,
            rotary_interleaved=False,
            packed=False,
            share_buffer=True,
            has_qk_norm=True,
        )
 
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch.float16,
            ort_type=TensorProto.FLOAT16,
            causal=True,
            rtol=rtol["fp16"],
            atol=atol["fp16"],
        )
 
    def test_gqa_qk_norm_past_shared_kv(self):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=0,
            past_kv_sequence_length=127,
            buffer_sequence_length=135,
            num_heads=8,
            kv_num_heads=2,
            head_size=64,
            rotary=False,
            packed=False,
            share_buffer=True,
            has_qk_norm=True,
        )
 
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch.float16,
            ort_type=TensorProto.FLOAT16,
            causal=True,
            rtol=rtol["fp16"],
            atol=atol["fp16"],
        )
 
    def test_gqa_qk_norm_past_xqa_bf16(self):
        if not torch.cuda.is_bf16_supported():
            self.skipTest("BFloat16 not supported on this device")
 
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=127,
            buffer_sequence_length=136,
            num_heads=32,
            kv_num_heads=8,
            head_size=128,
            rotary=True,
            rotary_interleaved=False,
            packed=False,
            share_buffer=True,
            has_qk_norm=True,
        )
        config.kv_cache_type = "bfloat16"
 
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch.bfloat16,
            ort_type=TensorProto.BFLOAT16,
            causal=True,
            rtol=rtol["bf16"],
            atol=atol["bf16"],
        )
 
    @parameterized.expand(gqa_qk_norm_test_cases(is_past=True))
    def test_gqa_qk_norm_past_bf16(self, name, config):
        if not torch.cuda.is_bf16_supported():
            self.skipTest("BFloat16 not supported on this device")
 
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        config.kv_cache_type = "bfloat16"
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.bfloat16,
                ort_type=TensorProto.BFLOAT16,
                causal=True,
                rtol=rtol["bf16"],
                atol=atol["bf16"],
            )
 
 
@unittest.skipIf(not has_flash_attention(), "Flash Attention is not available, skipping tests.")
@unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV Cache is not available, skipping tests.")
class TestFlashGQABF16QuantizedKV(unittest.TestCase):
    def manual_seed(self):
        # Reset random seeds before each test to ensure test isolation
        torch.manual_seed(0)
        random.seed(69)
        numpy.random.seed(42)
 
    def setUp(self):
        self.manual_seed()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
 
    def tearDown(self):
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_cuda_quantized_test_cases(is_past=False))
    def test_gqa_quantized_prompt_bf16(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        self.manual_seed()
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.bfloat16,
                ort_type=TensorProto.BFLOAT16,
                causal=True,
                rtol=rtol[f"{config.kv_cache_type}_bf16"],
                atol=atol[f"{config.kv_cache_type}_bf16"],
            )
 
    @parameterized.expand(gqa_cuda_quantized_test_cases(is_past=True))
    def test_gqa_quantized_past_bf16(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        self.manual_seed()
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.bfloat16,
                ort_type=TensorProto.BFLOAT16,
                causal=True,
                rtol=rtol[f"{config.kv_cache_type}_bf16"],
                atol=atol[f"{config.kv_cache_type}_bf16"],
            )
 
 
@unittest.skipIf(not has_cuda_device(53), "Memory Efficient Attention is not available, skipping tests.")
class TestMemoryEfficientGQA(unittest.TestCase):
    @parameterized.expand(gqa_cuda_prompt_test_cases(allow_head_sink=False))
    def test_gqa_prompt_memory_efficient(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "1"):
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    @parameterized.expand(gqa_cuda_past_test_cases(allow_head_sink=False))
    def test_gqa_past_memory_efficient(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "1"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
 
@unittest.skipIf(not has_cuda_device(80), "BF16 requires Ampere or higher GPU, skipping tests.")
class TestBF16MemoryEfficientGQA(unittest.TestCase):
    @parameterized.expand(gqa_cuda_past_test_cases(allow_head_sink=False))
    def test_gqa_past_memory_efficient_bf16(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "1"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.bfloat16,
                ort_type=TensorProto.BFLOAT16,
                causal=True,
                rtol=rtol["bf16"],
                atol=atol["bf16"],
            )
 
 
@unittest.skipIf(not has_cuda_device(53), "attention_bias CUDA parity tests require a CUDA GPU, skipping tests.")
class TestGQAAttentionBias(unittest.TestCase):
    """Parity for the optional attention_bias input (CUDA). No kernel-pinning env vars:
    bias-aware dispatch itself must route to a bias-capable path."""
 
    @parameterized.expand(gqa_cuda_attention_bias_test_cases(is_past=False))
    def test_gqa_prompt_attention_bias(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        parity_check_gqa_prompt(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch.float16,
            ort_type=TensorProto.FLOAT16,
            causal=True,
            rtol=rtol["fp16"],
            atol=atol["fp16"],
        )
 
    @parameterized.expand(gqa_cuda_attention_bias_test_cases(is_past=True))
    def test_gqa_past_attention_bias(self, name, config):
        if enable_debug_print:
            print("-" * 20)
            print(f"test_case: {name}\n{config}")
 
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch.float16,
            ort_type=TensorProto.FLOAT16,
            causal=True,
            rtol=rtol["fp16"],
            atol=atol["fp16"],
        )
 
    def test_windowed_cache_attention_bias_is_rejected(self):
        config = GQAConfig(
            batch_size=1,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=128,
            buffer_sequence_length=129,
            num_heads=8,
            kv_num_heads=2,
            head_size=64,
            local_window_size=128,
            share_buffer=True,
            sliding_window_cache=1,
            has_attention_bias=True,
            attention_bias_per_head=True,
        )
 
        with self.assertRaisesRegex(Exception, "attention_bias with sliding_window_cache"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch.float16,
                ort_type=TensorProto.FLOAT16,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
 
@unittest.skipIf(not has_flash_attention(), "Flash Attention is not available, skipping tests.")
class TestFlashGQAPaddingPrompt(unittest.TestCase):
    def test_gqa_padding_prompt_flash_attention(self):
        if enable_debug_print:
            print("-" * 20)
            print("test_case: test_gqa_padding_prompt_flash_attention")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_test_gqa_padding_prompt()
 
 
@unittest.skipIf(not has_cuda_device(53), "Memory Efficient Attention is not available, skipping tests.")
class TestMemoryEfficientGQAPaddingPrompt(unittest.TestCase):
    def test_gqa_padding_prompt_memory_efficient_attention(self):
        if enable_debug_print:
            print("-" * 20)
            print("test_case: test_gqa_padding_prompt_memory_efficient_attention")
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "1"):
            parity_test_gqa_padding_prompt()
 
 
# #################################################################################################
# Fused Kernel Parity Tests (ORT_DISABLE_FUSED_KV and ORT_DISABLE_FLASH_DECODE)
# #################################################################################################
 
 
def fused_kernel_test_cases():
    """Test cases specifically for fused vs unfused kernel parity."""
    configs = [
        # Decoding with RoPE and shared buffer
        GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=1,
            num_heads=16,
            kv_num_heads=4,
            head_size=128,
            past_kv_sequence_length=128,
            buffer_sequence_length=256,
            rotary=True,
            packed=False,
            share_buffer=True,
        ),
        # Packed QKV decoding with RoPE
        GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=1,
            num_heads=8,
            kv_num_heads=2,
            head_size=128,
            past_kv_sequence_length=64,
            buffer_sequence_length=128,
            rotary=True,
            packed=True,
            share_buffer=True,
        ),
        # Subsequent prompt with RoPE
        GQAConfig(
            batch_size=1,
            q_sequence_length=4,
            kv_sequence_length=4,
            num_heads=8,
            kv_num_heads=4,
            head_size=128,
            past_kv_sequence_length=32,
            buffer_sequence_length=64,
            rotary=True,
            packed=False,
            share_buffer=True,
        ),
    ]
    for i, config in enumerate(configs):
        yield f"fused_config_{i}", config
 
 
@unittest.skipIf(not has_flash_attention(), "Flash Attention is not available, skipping tests.")
class TestFlashDecodeMultiTokenParity(unittest.TestCase):
    def test_shared_buffer_multitoken_decode_matches_flash_attention(self):
        device = "cuda"
        torch_type = torch.float16
        ort_type = TensorProto.FLOAT16
 
        config = GQAConfig(
            batch_size=1,
            q_sequence_length=4,
            kv_sequence_length=4,
            num_heads=16,
            kv_num_heads=2,
            head_size=128,
            past_kv_sequence_length=64,
            buffer_sequence_length=128,
            rotary=False,
            packed=False,
            share_buffer=True,
            softcap=0.0,
        )
 
        torch.manual_seed(123)
        std = 0.1
        q = (
            torch.randn(
                config.batch_size,
                config.q_sequence_length,
                config.num_heads,
                config.head_size,
                device=device,
                dtype=torch_type,
            )
            * std
        )
        k = (
            torch.randn(
                config.batch_size,
                config.kv_num_heads,
                config.buffer_sequence_length,
                config.head_size,
                device=device,
                dtype=torch_type,
            )
            * std
        )
        v = torch.randn_like(k) * std
 
        past_len = config.past_kv_sequence_length
        k[:, :, past_len:, :] = 0
        v[:, :, past_len:, :] = 0
 
        new_k = (
            torch.randn(
                config.batch_size,
                config.kv_sequence_length,
                config.kv_num_heads,
                config.head_size,
                device=device,
                dtype=torch_type,
            )
            * std
        )
        new_v = torch.randn_like(new_k) * std
 
        seqlens_k = torch.tensor([past_len + config.kv_sequence_length - 1], dtype=torch.int32, device=device)
 
        def run_once(disable_flash_decode: bool):
            with (
                scoped_env_var("ORT_ENABLE_XQA", "0"),
                scoped_env_var("ORT_ENABLE_CUDNN_FLASH_ATTENTION", "0"),
                scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"),
                scoped_env_var("ORT_DISABLE_FLASH_DECODE", "1" if disable_flash_decode else "0"),
            ):
                out, present_k, present_v = gqa_past_func(
                    q=q,
                    k=k.clone(),
                    v=v.clone(),
                    config=config,
                    new_k=new_k,
                    new_v=new_v,
                    cos=None,
                    sin=None,
                    seqlens_k=seqlens_k,
                    position_ids=None,
                    attention_bias=None,
                    head_sink=None,
                    k_scale=None,
                    v_scale=None,
                    ep="CUDAExecutionProvider",
                    device=device,
                    share_buffer=True,
                    ort_type=ort_type,
                )
            return out, present_k, present_v
 
        out_fast, pk_fast, pv_fast = run_once(disable_flash_decode=False)
        out_ref, pk_ref, pv_ref = run_once(disable_flash_decode=True)
 
        numpy.testing.assert_allclose(
            out_fast.to(torch.float32).detach().cpu().numpy(),
            out_ref.to(torch.float32).detach().cpu().numpy(),
            rtol=2e-3,
            atol=2e-3,
        )
 
        valid_len = past_len + config.kv_sequence_length
        numpy.testing.assert_allclose(
            pk_fast[:, :, :valid_len, :].to(torch.float32).detach().cpu().numpy(),
            pk_ref[:, :, :valid_len, :].to(torch.float32).detach().cpu().numpy(),
            rtol=2e-3,
            atol=2e-3,
        )
        numpy.testing.assert_allclose(
            pv_fast[:, :, :valid_len, :].to(torch.float32).detach().cpu().numpy(),
            pv_ref[:, :, :valid_len, :].to(torch.float32).detach().cpu().numpy(),
            rtol=2e-3,
            atol=2e-3,
        )
 
 
def gqa_xqa_test_cases():
    # Decoding config (seq_len=1, share_buffer=True)
    # Testing different group sizes and query types
    for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
        for group_size in [4, 8, 16, 32]:
            for past_kv_sequence_length in [1, 4]:
                for rotary in [False, True]:
                    for packed in [False, True]:
                        for head_size in [256, 128, 64]:
                            kv_num_heads = 4
                            num_heads = kv_num_heads * group_size
                            config = GQAConfig(
                                batch_size=2,
                                q_sequence_length=1,
                                kv_sequence_length=1,
                                num_heads=num_heads,
                                kv_num_heads=kv_num_heads,
                                head_size=head_size,
                                past_kv_sequence_length=past_kv_sequence_length,
                                buffer_sequence_length=past_kv_sequence_length + 128,
                                rotary=rotary,
                                packed=packed,
                                share_buffer=True,
                                k_quant_type="PER_TENSOR",
                                v_quant_type="PER_TENSOR",
                                kv_cache_type="int8",
                                share_kv_scale=True,
                            )
                            type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                            rot_str = "rot" if rotary else "norot"
                            pkd_str = "pkd" if packed else "sep"
                            name = f"{type_str}_g_{group_size}_h{head_size}_past{past_kv_sequence_length}_{rot_str}_{pkd_str}"
                            yield name, config, torch_type, ort_type
 
 
@unittest.skipIf(not has_flash_attention(), "Flash Attention is not available, skipping tests.")
@unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV Cache is not available, skipping tests.")
class TestXQAQuantizedParity(unittest.TestCase):
    """Tests that verify fused kernels produce the same results as unfused kernels."""
 
    def setUp(self):
        # Force XQA on so the test is hermetic even if ORT_ENABLE_XQA=0 is set in the environment.
        self._prev_enable_xqa = os.environ.get("ORT_ENABLE_XQA")
        os.environ["ORT_ENABLE_XQA"] = "1"
 
    def tearDown(self):
        """Clear CUDA cache after each test to prevent memory corruption in batch runs."""
        if self._prev_enable_xqa is None:
            os.environ.pop("ORT_ENABLE_XQA", None)
        else:
            os.environ["ORT_ENABLE_XQA"] = self._prev_enable_xqa
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_xqa_test_cases())
    def test_xqa_quantized_parity(self, name, config, torch_type, ort_type):
        """Test XQA per-tensor INT8 quantized parity."""
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch_type,
            ort_type=ort_type,
            causal=True,
            rtol=rtol["int8_bf16"] if torch_type == torch.bfloat16 else rtol["int8_fp16"],
            atol=atol["int8_bf16"] if torch_type == torch.bfloat16 else atol["int8_fp16"],
            std=0.1,
        )
 
 
def gqa_xqa_head_sink_test_cases():
    # Non-quantized global decode with a head_sink (attention sink) input.
    # These configs exercise the XQA attention-sink path added for GPT-OSS style models:
    # seq_len=1, shared KV buffer, no softcap, no local window, head_size in {64, 128},
    # and group_size in {1, 2, 4, 5, 8, 16, 32}.
    for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
        for group_size in [1, 4, 5, 8]:
            for head_size in [64, 128]:
                for rotary in [False, True]:
                    kv_num_heads = 4
                    num_heads = kv_num_heads * group_size
                    config = GQAConfig(
                        batch_size=2,
                        q_sequence_length=1,
                        kv_sequence_length=1,
                        num_heads=num_heads,
                        kv_num_heads=kv_num_heads,
                        head_size=head_size,
                        past_kv_sequence_length=4,
                        buffer_sequence_length=4 + 128,
                        rotary=rotary,
                        packed=False,
                        share_buffer=True,
                        has_head_sink=True,
                    )
                    type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                    rot_str = "rot" if rotary else "norot"
                    name = f"{type_str}_g{group_size}_h{head_size}_{rot_str}"
                    yield name, config, torch_type, ort_type
 
 
def gqa_xqa_head_sink_prepack_test_cases():
    # Same XQA attention-sink decode path as gqa_xqa_head_sink_test_cases(), but head_sink is baked
    # into the model as a constant initializer. This exercises GroupQueryAttention::PrePack, which
    # converts the constant head_sink once into the cached FP32 XQA buffer (use_prepacked_xqa_head_sink),
    # instead of the per-launch conversion scratch path used for runtime head_sink inputs.
    for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
        for group_size in [1, 4]:
            for rotary in [False, True]:
                kv_num_heads = 4
                num_heads = kv_num_heads * group_size
                config = GQAConfig(
                    batch_size=2,
                    q_sequence_length=1,
                    kv_sequence_length=1,
                    num_heads=num_heads,
                    kv_num_heads=kv_num_heads,
                    head_size=128,
                    past_kv_sequence_length=4,
                    buffer_sequence_length=4 + 128,
                    rotary=rotary,
                    packed=False,
                    share_buffer=True,
                    has_head_sink=True,
                    head_sink_as_initializer=True,
                )
                type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                rot_str = "rot" if rotary else "norot"
                name = f"{type_str}_g{group_size}_h128_{rot_str}_prepack"
                yield name, config, torch_type, ort_type
 
 
@unittest.skipIf(not has_xqa(), "XQA is not available, skipping tests.")
@unittest.skipIf(not has_flash_attention(), "Flash Attention is not available, skipping tests.")
class TestXQAHeadSinkParity(unittest.TestCase):
    """Verify the non-quantized XQA attention-sink (head_sink) decode path matches the reference."""
 
    def setUp(self):
        # XQA is enabled by default for fp16/bf16 (ORT_ENABLE_XQA defaults to 1).
        # Pop any override so we exercise the real default behavior.
        self._prev_enable_xqa = os.environ.pop("ORT_ENABLE_XQA", None)
 
    def tearDown(self):
        # Restore the environment so other tests run with the default XQA setting.
        if self._prev_enable_xqa is None:
            os.environ.pop("ORT_ENABLE_XQA", None)
        else:
            os.environ["ORT_ENABLE_XQA"] = self._prev_enable_xqa
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_xqa_head_sink_test_cases())
    def test_xqa_head_sink_parity(self, name, config, torch_type, ort_type):
        """Test XQA non-quantized parity with a head_sink (attention sink) input."""
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch_type,
            ort_type=ort_type,
            causal=True,
            rtol=rtol["bf16"] if torch_type == torch.bfloat16 else rtol["fp16"],
            atol=atol["bf16"] if torch_type == torch.bfloat16 else atol["fp16"],
            std=0.1,
        )
 
    @parameterized.expand(gqa_xqa_head_sink_prepack_test_cases())
    def test_xqa_head_sink_prepack_parity(self, name, config, torch_type, ort_type):
        """Test XQA parity when head_sink is a constant initializer (exercises PrePack)."""
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch_type,
            ort_type=ort_type,
            causal=True,
            rtol=rtol["bf16"] if torch_type == torch.bfloat16 else rtol["fp16"],
            atol=atol["bf16"] if torch_type == torch.bfloat16 else atol["fp16"],
            std=0.1,
        )
 
 
def gqa_xqa_sliding_window_test_cases():
    # Non-quantized sliding-window (local attention) decode through the XQA kernel.
    #
    # The XQA decode path now supports local_window_size > 0 on the non-quantized fp16/bf16
    # path (GPT-OSS style sliding-window layers). XQA selection requires: decode (q_seq=1),
    # a shared KV buffer, softcap==0, head_size in {64, 128, 256} and 64 % group_size == 0.
    #
    # Two window/past relationships are covered:
    #   past > window  -> the sliding mask drops the oldest keys (the new code path).
    #   past <= window -> the window spans the whole cache (parity with global attention).
    #   past + 1 == window -> the exact guard boundary (cacheSeqLen == slidingWinSize) that locks
    #                         down the kernel's `>` vs `>=` window comparison.
    # has_head_sink toggles the GPT-OSS attention-sink input, which composes with the window
    # in-kernel; both with and without a sink are exercised.
    for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
        for head_size in [64, 128]:
            for group_size in [4, 8]:
                for past_kv_sequence_length, local_window_size in [(512, 128), (64, 128), (127, 128)]:
                    for has_head_sink in [False, True]:
                        kv_num_heads = 4
                        num_heads = kv_num_heads * group_size
                        config = GQAConfig(
                            batch_size=2,
                            q_sequence_length=1,
                            kv_sequence_length=1,
                            num_heads=num_heads,
                            kv_num_heads=kv_num_heads,
                            head_size=head_size,
                            past_kv_sequence_length=past_kv_sequence_length,
                            buffer_sequence_length=past_kv_sequence_length + 128,
                            local_window_size=local_window_size,
                            rotary=True,
                            rotary_interleaved=False,
                            packed=False,
                            share_buffer=True,
                            has_head_sink=has_head_sink,
                        )
                        type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                        sink_str = "sink" if has_head_sink else "nosink"
                        win_str = f"past{past_kv_sequence_length}_win{local_window_size}"
                        name = f"{type_str}_g{group_size}_h{head_size}_{win_str}_{sink_str}"
                        yield name, config, torch_type, ort_type
 
 
@unittest.skipIf(not has_xqa(), "XQA is not available, skipping tests.")
class TestXQASlidingWindowParity(unittest.TestCase):
    """Verify the non-quantized XQA sliding-window (local attention) decode path matches the reference."""
 
    def setUp(self):
        # Force XQA on so the test is hermetic even if ORT_ENABLE_XQA=0 is set in the environment.
        self._prev_enable_xqa = os.environ.get("ORT_ENABLE_XQA")
        os.environ["ORT_ENABLE_XQA"] = "1"
 
    def tearDown(self):
        """Clear CUDA cache after each test to prevent memory corruption in batch runs."""
        if self._prev_enable_xqa is None:
            os.environ.pop("ORT_ENABLE_XQA", None)
        else:
            os.environ["ORT_ENABLE_XQA"] = self._prev_enable_xqa
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_xqa_sliding_window_test_cases())
    def test_xqa_sliding_window_parity(self, name, config, torch_type, ort_type):
        """Test XQA non-quantized parity with a sliding (local) attention window."""
 
        def run_parity_check():
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=rtol["bf16"] if torch_type == torch.bfloat16 else rtol["fp16"],
                atol=atol["bf16"] if torch_type == torch.bfloat16 else atol["fp16"],
                std=0.1,
            )
 
        # XQA is enabled by default for fp16/bf16, so no head_sink input is required to select it.
        self.assertEqual("XQA", get_sdpa_kernel_from_debug_info(run_parity_check))
 
 
def gqa_xqa_quantized_sliding_window_test_cases():
    # Quantized (INT8 / FP8) sliding-window (local attention) decode through the XQA kernel.
    #
    # The XQA decode path now supports local_window_size > 0 on the quantized KV-cache paths as
    # well. Quantized XQA selection requires: decode (q_seq=1), a shared KV buffer, supported
    # head_size and group_size combinations for the active kernel configuration. Attention sinks
    # are covered separately by
    # gqa_xqa_quantized_head_sink_test_cases(), so no head_sink here.
    #
    # Two window/past relationships are covered:
    #   past > window  -> the sliding mask drops the oldest keys (the new code path).
    #   past <= window -> the window spans the whole cache (parity with global attention).
    #   past + 1 == window -> the exact guard boundary (cacheSeqLen == slidingWinSize).
    kv_cache_types = ["int8"]
    if has_fp8_kv_cache and has_fp8_xqa():
        kv_cache_types.append("fp8")
    for kv_cache_type in kv_cache_types:
        for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
            for head_size in [64, 128]:
                for group_size in [4, 8]:
                    for past_kv_sequence_length, local_window_size in [(512, 128), (64, 128), (127, 128)]:
                        kv_num_heads = 4
                        num_heads = kv_num_heads * group_size
                        config = GQAConfig(
                            batch_size=2,
                            q_sequence_length=1,
                            kv_sequence_length=1,
                            num_heads=num_heads,
                            kv_num_heads=kv_num_heads,
                            head_size=head_size,
                            past_kv_sequence_length=past_kv_sequence_length,
                            buffer_sequence_length=past_kv_sequence_length + 128,
                            local_window_size=local_window_size,
                            rotary=True,
                            rotary_interleaved=False,
                            packed=False,
                            share_buffer=True,
                            k_quant_type="PER_TENSOR",
                            v_quant_type="PER_TENSOR",
                            kv_cache_type=kv_cache_type,
                            share_kv_scale=True,
                        )
                        type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                        win_str = f"past{past_kv_sequence_length}_win{local_window_size}"
                        name = f"{kv_cache_type}_{type_str}_g{group_size}_h{head_size}_{win_str}"
                        yield name, config, torch_type, ort_type
 
 
@unittest.skipIf(not has_xqa(), "XQA is not available, skipping tests.")
@unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV Cache is not available, skipping tests.")
class TestXQAQuantizedSlidingWindowParity(unittest.TestCase):
    """Verify the quantized (INT8/FP8) XQA sliding-window (local attention) decode path matches the reference."""
 
    def setUp(self):
        # Force XQA on so the test is hermetic even if ORT_ENABLE_XQA=0 is set in the environment.
        self._prev_enable_xqa = os.environ.get("ORT_ENABLE_XQA")
        os.environ["ORT_ENABLE_XQA"] = "1"
 
    def tearDown(self):
        """Clear CUDA cache after each test to prevent memory corruption in batch runs."""
        if self._prev_enable_xqa is None:
            os.environ.pop("ORT_ENABLE_XQA", None)
        else:
            os.environ["ORT_ENABLE_XQA"] = self._prev_enable_xqa
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_xqa_quantized_sliding_window_test_cases())
    def test_xqa_quantized_sliding_window_parity(self, name, config, torch_type, ort_type):
        """Test XQA quantized parity with a sliding (local) attention window."""
        type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
        rtol_key = f"{config.kv_cache_type}_{type_str}"
 
        def run_parity_check():
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=rtol[rtol_key],
                atol=atol[rtol_key],
                std=0.1,
            )
 
        # XQA is enabled by default for fp16/bf16, so the quantized sliding-window path is selected.
        self.assertEqual("XQA", get_sdpa_kernel_from_debug_info(run_parity_check))
 
 
def gqa_xqa_quantized_head_sink_test_cases():
    # Quantized (INT8 / FP8) decode with an attention sink (head_sink / smooth softmax) through
    # the XQA kernel -- the GPT-OSS style configuration.
    #
    # The sink term is folded into the softmax row sum by the same kernel code used on the
    # non-quantized path, and the KV dequant scale is applied to the QK scores before the row
    # max/sum are computed, so the sink and the scores live in the same dequantized domain.
    #
    # Coverage:
    #   local_window_size == -1 -> global attention with a sink.
    #   local_window_size > 0 with past > window -> sliding window composed with a sink.
    #   past_kv_sequence_length 512 also forces the multi-block (Flash Decoding) reduction, where
    #   the sink is added to the merged row sum instead of the per-CTA row sum.
    #   head_sink_as_initializer toggles the PrePack'd FP32 sink buffer vs. the per-launch
    #   conversion scratch path.
    kv_cache_types = ["int8"]
    if has_fp8_kv_cache:
        kv_cache_types.append("fp8")
    for kv_cache_type in kv_cache_types:
        for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
            for head_size in [64, 128]:
                for group_size in [4, 8]:
                    for past_kv_sequence_length, local_window_size in [(4, -1), (512, -1), (512, 128)]:
                        for head_sink_as_initializer in [False, True]:
                            kv_num_heads = 4
                            num_heads = kv_num_heads * group_size
                            config = GQAConfig(
                                batch_size=2,
                                q_sequence_length=1,
                                kv_sequence_length=1,
                                num_heads=num_heads,
                                kv_num_heads=kv_num_heads,
                                head_size=head_size,
                                past_kv_sequence_length=past_kv_sequence_length,
                                buffer_sequence_length=past_kv_sequence_length + 128,
                                local_window_size=local_window_size,
                                rotary=True,
                                rotary_interleaved=False,
                                packed=False,
                                share_buffer=True,
                                has_head_sink=True,
                                head_sink_as_initializer=head_sink_as_initializer,
                                k_quant_type="PER_TENSOR",
                                v_quant_type="PER_TENSOR",
                                kv_cache_type=kv_cache_type,
                                share_kv_scale=True,
                            )
                            type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                            win_str = f"past{past_kv_sequence_length}_win{local_window_size}"
                            pack_str = "prepack" if head_sink_as_initializer else "runtime"
                            name = f"{kv_cache_type}_{type_str}_g{group_size}_h{head_size}_{win_str}_{pack_str}"
                            yield name, config, torch_type, ort_type
 
 
@unittest.skipIf(not has_xqa(), "XQA is not available, skipping tests.")
@unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV Cache is not available, skipping tests.")
class TestXQAQuantizedHeadSinkParity(unittest.TestCase):
    """Verify the quantized (INT8/FP8) XQA attention-sink decode path matches the reference."""
 
    def setUp(self):
        # Force XQA on so the test is hermetic even if ORT_ENABLE_XQA=0 is set in the environment.
        self._prev_enable_xqa = os.environ.get("ORT_ENABLE_XQA")
        os.environ["ORT_ENABLE_XQA"] = "1"
 
    def tearDown(self):
        """Clear CUDA cache after each test to prevent memory corruption in batch runs."""
        if self._prev_enable_xqa is None:
            os.environ.pop("ORT_ENABLE_XQA", None)
        else:
            os.environ["ORT_ENABLE_XQA"] = self._prev_enable_xqa
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_xqa_quantized_head_sink_test_cases())
    def test_xqa_quantized_head_sink_parity(self, name, config, torch_type, ort_type):
        """Test XQA quantized parity with an attention sink (head_sink) input."""
        type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
        rtol_key = f"{config.kv_cache_type}_{type_str}"
 
        def run_parity_check():
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=rtol[rtol_key],
                atol=atol[rtol_key],
                std=0.1,
            )
 
        # Guard against silently falling back: the quantized + sink combination must reach XQA.
        self.assertEqual("XQA", get_sdpa_kernel_from_debug_info(run_parity_check))
 
 
def gqa_xqa_separate_kv_scale_test_cases():
    # Quantized (INT8 / FP8) decode where K and V use *different* per-tensor scales.
    #
    # The XQA kernel keeps the two scales apart: k_scale is folded into qkScale (applied to Q*K.T
    # before the softmax row max/sum) and v_scale into voScale (applied to the P*V accumulator).
    # These tests guard both the numerics and the dispatch decision -- XQA used to require the two
    # scale inputs to be the same tensor, which silently disqualified any model that calibrates K
    # and V independently.
    #
    # Coverage includes global attention, sliding window, the multi-block (Flash Decoding)
    # reduction (past 512), and attention sinks, since each of those paths touches the rescales.
    kv_cache_types = ["int8"]
    if has_fp8_kv_cache:
        kv_cache_types.append("fp8")
    for kv_cache_type in kv_cache_types:
        for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
            for head_size in [64, 128, 256]:
                for group_size in [4, 8]:
                    for past_kv_sequence_length, local_window_size in [(4, -1), (512, -1), (512, 128)]:
                        for has_head_sink in [False, True]:
                            kv_num_heads = 4
                            num_heads = kv_num_heads * group_size
                            config = GQAConfig(
                                batch_size=2,
                                q_sequence_length=1,
                                kv_sequence_length=1,
                                num_heads=num_heads,
                                kv_num_heads=kv_num_heads,
                                head_size=head_size,
                                past_kv_sequence_length=past_kv_sequence_length,
                                buffer_sequence_length=past_kv_sequence_length + 128,
                                local_window_size=local_window_size,
                                rotary=True,
                                rotary_interleaved=False,
                                packed=False,
                                share_buffer=True,
                                has_head_sink=has_head_sink,
                                head_sink_as_initializer=True,
                                k_quant_type="PER_TENSOR",
                                v_quant_type="PER_TENSOR",
                                kv_cache_type=kv_cache_type,
                                share_kv_scale=False,
                            )
                            type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                            win_str = f"past{past_kv_sequence_length}_win{local_window_size}"
                            sink_str = "sink" if has_head_sink else "nosink"
                            name = f"{kv_cache_type}_{type_str}_g{group_size}_h{head_size}_{win_str}_{sink_str}"
                            yield name, config, torch_type, ort_type
 
 
@unittest.skipIf(not has_xqa(), "XQA is not available, skipping tests.")
@unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV Cache is not available, skipping tests.")
class TestXQASeparateKVScaleParity(unittest.TestCase):
    """Verify XQA handles independent K and V dequantization scales."""
 
    def setUp(self):
        # Force XQA on so the test is hermetic even if ORT_ENABLE_XQA=0 is set in the environment.
        self._prev_enable_xqa = os.environ.get("ORT_ENABLE_XQA")
        os.environ["ORT_ENABLE_XQA"] = "1"
 
    def tearDown(self):
        """Clear CUDA cache after each test to prevent memory corruption in batch runs."""
        if self._prev_enable_xqa is None:
            os.environ.pop("ORT_ENABLE_XQA", None)
        else:
            os.environ["ORT_ENABLE_XQA"] = self._prev_enable_xqa
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_xqa_separate_kv_scale_test_cases())
    def test_xqa_separate_kv_scale_parity(self, name, config, torch_type, ort_type):
        """Test XQA quantized parity when k_scale and v_scale are distinct tensors."""
        type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
        rtol_key = f"{config.kv_cache_type}_{type_str}"
 
        def run_parity_check():
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=rtol[rtol_key],
                atol=atol[rtol_key],
                std=0.1,
            )
 
        # Distinct k_scale/v_scale tensors must not disqualify the op from XQA.
        self.assertEqual("XQA", get_sdpa_kernel_from_debug_info(run_parity_check))
 
 
def gqa_xqa_per_channel_scale_test_cases():
    # Quantized (INT8 / FP8) decode with PER_CHANNEL k/v scales on the XQA path.
    #
    # XQA only understands a scalar dequant scale, so per-channel scales are folded out of the
    # kernel: k_scale into Q (the channel dim is contracted by Q*K.T) and v_scale into the
    # attention output (the channel dim is free in P*V). Both foldings are exact because
    # dequantization is linear, so these tests are ordinary parity tests -- but they also guard
    # the dispatch decision, since per-channel used to fall back to
    # "dequantize the whole cache, then run flash attention" on every decode step.
    #
    # Coverage: global attention, sliding window, the multi-block (Flash Decoding) reduction
    # (past 512), attention sinks, and rotary on/off (rotary decides whether the folded Q lands in
    # the RoPE scratch buffer or in a scratch buffer allocated only for the folding).
    kv_cache_types = ["int8"]
    if has_fp8_kv_cache:
        kv_cache_types.append("fp8")
    for kv_cache_type in kv_cache_types:
        for torch_type, ort_type in [(torch.float16, TensorProto.FLOAT16), (torch.bfloat16, TensorProto.BFLOAT16)]:
            for head_size in [64, 128]:
                for group_size in [4, 8]:
                    for past_kv_sequence_length, local_window_size in [(4, -1), (512, -1), (512, 128)]:
                        for has_head_sink, rotary in [(False, True), (True, True), (True, False)]:
                            kv_num_heads = 4
                            num_heads = kv_num_heads * group_size
                            config = GQAConfig(
                                batch_size=2,
                                q_sequence_length=1,
                                kv_sequence_length=1,
                                num_heads=num_heads,
                                kv_num_heads=kv_num_heads,
                                head_size=head_size,
                                past_kv_sequence_length=past_kv_sequence_length,
                                buffer_sequence_length=past_kv_sequence_length + 128,
                                local_window_size=local_window_size,
                                rotary=rotary,
                                rotary_interleaved=False,
                                packed=False,
                                share_buffer=True,
                                has_head_sink=has_head_sink,
                                head_sink_as_initializer=True,
                                k_quant_type="PER_CHANNEL",
                                v_quant_type="PER_CHANNEL",
                                kv_cache_type=kv_cache_type,
                                share_kv_scale=False,
                            )
                            type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
                            win_str = f"past{past_kv_sequence_length}_win{local_window_size}"
                            sink_str = "sink" if has_head_sink else "nosink"
                            rot_str = "rot" if rotary else "norot"
                            name = (
                                f"{kv_cache_type}_{type_str}_g{group_size}_h{head_size}_{win_str}_{sink_str}_{rot_str}"
                            )
                            yield name, config, torch_type, ort_type
 
 
@unittest.skipIf(not has_xqa(), "XQA is not available, skipping tests.")
@unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV Cache is not available, skipping tests.")
class TestXQAPerChannelScaleParity(unittest.TestCase):
    """Verify XQA serves PER_CHANNEL quantized KV caches by folding the scales into Q / the output."""
 
    def setUp(self):
        # Force XQA on so the test is hermetic even if ORT_ENABLE_XQA=0 is set in the environment.
        self._prev_enable_xqa = os.environ.get("ORT_ENABLE_XQA")
        os.environ["ORT_ENABLE_XQA"] = "1"
 
    def tearDown(self):
        """Clear CUDA cache after each test to prevent memory corruption in batch runs."""
        if self._prev_enable_xqa is None:
            os.environ.pop("ORT_ENABLE_XQA", None)
        else:
            os.environ["ORT_ENABLE_XQA"] = self._prev_enable_xqa
        if torch.cuda.is_available():
            torch.cuda.synchronize()
            torch.cuda.empty_cache()
        gc.collect()
 
    @parameterized.expand(gqa_xqa_per_channel_scale_test_cases())
    def test_xqa_per_channel_scale_parity(self, name, config, torch_type, ort_type):
        """Test XQA quantized parity with per-channel k/v dequantization scales."""
        type_str = "bf16" if torch_type == torch.bfloat16 else "fp16"
        rtol_key = f"{config.kv_cache_type}_{type_str}"
 
        def run_parity_check():
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device="cuda",
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=rtol[rtol_key],
                atol=atol[rtol_key],
                std=0.1,
            )
 
        # Per-channel scales must reach XQA instead of the dequantize-the-whole-cache fallback.
        self.assertEqual("XQA", get_sdpa_kernel_from_debug_info(run_parity_check))
 
 
@unittest.skipIf(not has_flash_attention(), "Flash Attention is not available, skipping tests.")
@unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV Cache is not available, skipping tests.")
class TestGQARegressions(unittest.TestCase):
    """Specific regression tests for historical bugs."""
 
    def test_gqa_cuda_rejects_zero_local_window_size(self):
        if not has_cuda_provider():
            self.skipTest("CUDA required")
 
        config = GQAConfig(
            batch_size=1,
            num_heads=4,
            kv_num_heads=4,
            head_size=64,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=0,
            buffer_sequence_length=1,
            local_window_size=0,
            share_buffer=True,
        )
        onnx_model_str = create_group_query_attention_graph_prompt(config, TensorProto.FLOAT16)
 
        with self.assertRaisesRegex(Exception, "local_window_size must be -1 or greater than 0"):
            InferenceSession(
                onnx_model_str,
                SessionOptions(),
                providers=[resolve_cuda_plugin_ep("CUDAExecutionProvider")],
            )
 
    def test_gqa_rope_separate_qkv_bug(self):
        """
        Regression test for separate QKV + RoPE + FlashAttention bug.
        The bug caused q_out to be nullptr when unpacking separate QKV with only Q rotation (standard GQA),
        leading to unrotated Q being used in Attention.
        """
        if not has_cuda_provider():
            self.skipTest("CUDA required")
 
        # Config that triggers the path: Prompt phase, Separate QKV inputs, RoPE enabled
        config = GQAConfig(
            batch_size=1,
            num_heads=4,
            kv_num_heads=4,
            head_size=128,
            q_sequence_length=16,
            kv_sequence_length=16,
            past_kv_sequence_length=0,
            buffer_sequence_length=16,
            rotary=True,
            rotary_interleaved=False,
            share_buffer=True,
        )
 
        torch_type = torch.float16
        ort_type = TensorProto.FLOAT16
        device = "cuda"
 
        parity_check_gqa_prompt(
            config=config,
            ep="CUDAExecutionProvider",
            device=device,
            torch_type=torch_type,
            ort_type=ort_type,
            causal=True,
            rtol=1e-3,
            atol=1e-3,
            std=1.0,
        )
 
    def test_gqa_int8_large_seq_batch4(self):
        """
        Regression test for batch_size=4 + max_seq_len=8192 + int8 KV cache crash.
        This reproduces a CUDA illegal memory access due to scratch size under-allocation.
        """
        if not has_cuda_provider():
            self.skipTest("CUDA required")
 
        # Config that triggers the crash: batch=4, large max_seq_len, int8 kv
        config = GQAConfig(
            batch_size=4,
            num_heads=32,
            kv_num_heads=8,
            head_size=128,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=8191,
            buffer_sequence_length=8192,
            rotary=True,
            rotary_interleaved=False,
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_TENSOR",
            kv_cache_type="int8",
            share_buffer=True,
            share_kv_scale=True,
        )
 
        torch_type = torch.float16
        ort_type = TensorProto.FLOAT16
        device = "cuda"
 
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device=device,
            torch_type=torch_type,
            ort_type=ort_type,
            causal=True,
            rtol=5e-2,
            atol=5e-2,
        )
 
    def test_gqa_local_window_large_context_decode(self):
        """
        Regression test for FlashDecode split planning with a local attention window.
 
        Mirrors a gpt-oss-style decode step: a large past KV context combined with a small
        sliding (local) window. The split-K planning is clamped to the local window length,
        so only the windowed portion of the KV cache participates in the decode. This verifies
        that the narrowed split planning still produces correct results.
        """
        if not has_flash_attention():
            self.skipTest("Flash Attention is not available")
 
        # Decode (q_sequence_length=1) with a large past context but a small local window.
        config = GQAConfig(
            batch_size=2,
            num_heads=64,
            kv_num_heads=8,
            head_size=64,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=4096,
            buffer_sequence_length=4096 + 8,
            local_window_size=128,
            rotary=True,
            rotary_interleaved=False,
            share_buffer=True,
        )
 
        torch_type = torch.float16
        ort_type = TensorProto.FLOAT16
        device = "cuda"
 
        with scoped_env_var("ORT_DISABLE_FLASH_ATTENTION", "0"):
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device=device,
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=rtol["fp16"],
                atol=atol["fp16"],
            )
 
    @unittest.skipIf(not has_cuda_device(89) or not has_fp8_kv_cache, "FP8 KV cache is not available, skipping tests.")
    def test_gqa_fp8_kv_cache(self):
        """
        Test GQA with FP8 E4M3 quantized KV cache.
        Requires SM89+ (Ada Lovelace or newer) and USE_FP8_KV_CACHE build flag.
        """
        config = GQAConfig(
            batch_size=2,
            num_heads=32,
            kv_num_heads=8,
            head_size=128,
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=127,
            buffer_sequence_length=128,
            rotary=True,
            rotary_interleaved=False,
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_TENSOR",
            kv_cache_type="fp8",
            share_buffer=True,
            share_kv_scale=True,
        )
 
        torch_type = torch.float16
        ort_type = TensorProto.FLOAT16
        device = "cuda"
 
        try:
            parity_check_gqa_past(
                config=config,
                ep="CUDAExecutionProvider",
                device=device,
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=5e-2,
                atol=5e-2,
            )
        except Exception as e:
            # FP8 may not be built, skip if kernel not registered
            if "Float8E4M3FN" in str(e) or "fp8" in str(e).lower():
                self.skipTest(f"FP8 KV cache not available: {e}")
            raise
 
    @unittest.skipIf(not has_cuda_device(89) or not has_fp8_kv_cache, "FP8 KV cache is not available, skipping tests.")
    def test_gqa_fp8_prompt(self):
        """
        Test GQA Prompt phase with FP8 E4M3 quantized KV cache.
        """
        config = GQAConfig(
            batch_size=2,
            num_heads=32,
            kv_num_heads=8,
            head_size=128,
            q_sequence_length=128,
            kv_sequence_length=128,
            past_kv_sequence_length=0,
            buffer_sequence_length=128,
            rotary=True,
            rotary_interleaved=False,
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_TENSOR",
            kv_cache_type="fp8",
            share_buffer=True,
            share_kv_scale=True,
            kv_cache_bit_width=8,
        )
 
        torch_type = torch.float16
        ort_type = TensorProto.FLOAT16
        device = "cuda"
 
        try:
            parity_check_gqa_prompt(
                config=config,
                ep="CUDAExecutionProvider",
                device=device,
                torch_type=torch_type,
                ort_type=ort_type,
                causal=True,
                rtol=5e-2,
                atol=5e-2,
            )
        except Exception as e:
            if "Float8E4M3FN" in str(e) or "fp8" in str(e).lower():
                self.skipTest(f"FP8 KV cache not available: {e}")
            raise
 
    @unittest.skipIf(not has_cuda_device(89) or not has_fp8_kv_cache, "FP8 KV cache is not available, skipping tests.")
    @unittest.skipIf(quick_build, "Quick build only has hdim128 flash attention kernels; head_size=48 needs hdim64.")
    def test_gqa_fp8_fallback_unsupported_head_size(self):
        """
        Test GQA with FP8 KV cache on a head size not supported by XQA.
        This forces fallback to the generic generic kernel (if available) or ensures graceful failure/correctness.
        """
        config = GQAConfig(
            batch_size=2,
            num_heads=32,
            kv_num_heads=8,
            head_size=48,  # Valid head size (multiple of 16) but not supported by XQA (supports 64, 128, 256)
            q_sequence_length=1,
            kv_sequence_length=1,
            past_kv_sequence_length=64,
            buffer_sequence_length=128,
            rotary=True,
            rotary_interleaved=False,
            k_quant_type="PER_TENSOR",
            v_quant_type="PER_TENSOR",
            kv_cache_type="fp8",
            share_buffer=True,
            share_kv_scale=True,
        )
 
        torch_type = torch.float16
        ort_type = TensorProto.FLOAT16
        device = "cuda"
 
        parity_check_gqa_past(
            config=config,
            ep="CUDAExecutionProvider",
            device=device,
            torch_type=torch_type,
            ort_type=ort_type,
            causal=True,
            rtol=5e-2,
            atol=5e-2,
        )
 
    # ------------------------------------------------------------------------
    # Gemma 4 global attention layers (issue #28195): num_attention_heads=8,
    # num_key_value_heads=4, head_dim=512. The unfused CUDA runner produced
    # NaN at head_dim=512, scale=1.0 because raw Q*K^T overflowed fp16 even
    # though cuBLAS accumulated in FP32 (output C was fp16). The new GQA
    # unfused kernel writes QK to an FP32 scratch and fixes this.
    # ------------------------------------------------------------------------
    def _run_gemma4_gqa(
        self,
        torch_type,
        ort_type,
        q_sequence_length,
        past_kv_sequence_length,
        is_prompt,
        local_window_size=-1,
        softcap=0.0,
    ):
        if not has_cuda_provider():
            self.skipTest("CUDA required")
        if torch_type == torch.bfloat16 and not torch.cuda.is_bf16_supported():
            self.skipTest("BFloat16 not supported on this device")
 
        # Force the unfused path: disable Flash (doesn't support head_size>256)
        # and Memory-Efficient Attention (cutlass FMHA caps at head_size 256 too).
        os.environ["ORT_DISABLE_FLASH_ATTENTION"] = "1"
        os.environ["ORT_DISABLE_MEMORY_EFFICIENT_ATTENTION"] = "1"
        self.addCleanup(os.environ.pop, "ORT_DISABLE_FLASH_ATTENTION", None)
        self.addCleanup(os.environ.pop, "ORT_DISABLE_MEMORY_EFFICIENT_ATTENTION", None)
 
        config = GQAConfig(
            batch_size=1,
            num_heads=8,
            kv_num_heads=4,
            head_size=512,
            q_sequence_length=q_sequence_length,
            kv_sequence_length=q_sequence_length,
            past_kv_sequence_length=past_kv_sequence_length,
            buffer_sequence_length=q_sequence_length + past_kv_sequence_length + 8,
            local_window_size=local_window_size,
            rotary=False,
            rotary_interleaved=False,
            packed=False,
            share_buffer=True,
            softcap=softcap,
            use_smooth_softmax=False,
            has_head_sink=False,
            has_position_ids=False,
        )
 
        dtype_key = "fp16" if ort_type == TensorProto.FLOAT16 else "bf16"
        check = parity_check_gqa_prompt if is_prompt else parity_check_gqa_past
        check(
            config=config,
            ep="CUDAExecutionProvider",
            device="cuda",
            torch_type=torch_type,
            ort_type=ort_type,
            causal=True,
            rtol=rtol[dtype_key],
            atol=atol[dtype_key],
        )
 
    def test_gqa_gemma4_global_prompt_fp16(self):
        """#28195 exact repro: fp16 prompt with head_dim=512, Gemma 4 head config."""
        self._run_gemma4_gqa(
            torch.float16, TensorProto.FLOAT16, q_sequence_length=16, past_kv_sequence_length=0, is_prompt=True
        )
 
    def test_gqa_gemma4_global_decode_fp16(self):
        """#28195: fp16 decode with past KV at head_dim=512."""
        self._run_gemma4_gqa(
            torch.float16, TensorProto.FLOAT16, q_sequence_length=1, past_kv_sequence_length=64, is_prompt=False
        )
 
    def test_gqa_gemma4_global_decode_fp16_long(self):
        """Gemma 4 global attention with longer past at head_dim=512."""
        self._run_gemma4_gqa(
            torch.float16, TensorProto.FLOAT16, q_sequence_length=1, past_kv_sequence_length=2048, is_prompt=False
        )
 
    def test_gqa_gemma4_global_prompt_bf16(self):
        """Gemma 4 global attention in bf16 prompt phase at head_dim=512."""
        self._run_gemma4_gqa(
            torch.bfloat16, TensorProto.BFLOAT16, q_sequence_length=16, past_kv_sequence_length=0, is_prompt=True
        )
 
    def test_gqa_gemma4_global_decode_bf16(self):
        """Gemma 4 global attention in bf16 decode phase at head_dim=512."""
        self._run_gemma4_gqa(
            torch.bfloat16, TensorProto.BFLOAT16, q_sequence_length=1, past_kv_sequence_length=64, is_prompt=False
        )
 
    def test_gqa_gemma4_global_prompt_fp16_softcap(self):
        """Gemma 4 global attention with softcap (Gemma family uses logit softcap)."""
        self._run_gemma4_gqa(
            torch.float16,
            TensorProto.FLOAT16,
            q_sequence_length=16,
            past_kv_sequence_length=0,
            is_prompt=True,
            softcap=50.0,
        )
 
    def test_gqa_gemma4_local_window_decode_fp16(self):
        """
        Gemma 4 has mixed global + sliding-window (local) attention layers. This
        exercises the unfused kernel's sliding-window mask at head_dim=512.
        """
        self._run_gemma4_gqa(
            torch.float16,
            TensorProto.FLOAT16,
            q_sequence_length=1,
            past_kv_sequence_length=256,
            is_prompt=False,
            local_window_size=128,
        )
 
 
# #################################################################################################
#  Windowed (cache-relative) KV cache: sliding_window_cache=1
# #################################################################################################
 
 
def _windowed_make_session(config: GQAConfig, ort_type, providers=None):
    onnx_model_str = create_group_query_attention_graph_past(config, ort_type=ort_type, share_buffer=True)
    if providers is None:
        providers = [resolve_cuda_plugin_ep("CUDAExecutionProvider")]
    return InferenceSession(onnx_model_str, SessionOptions(), providers=providers)
 
 
def _windowed_resident_count(total_length: int, capacity: int, window: int) -> int:
    """`L(T)` from the operator spec: the number of KV positions resident after a step."""
    if total_length <= capacity:
        return total_length
    gap = capacity - window + 1
    overflow = total_length - capacity
    return total_length - gap * ((overflow + gap - 1) // gap)
 
 
def _windowed_run_steps(
    base_config: GQAConfig,
    buffer_sequence_length: int,
    sliding_window_cache: int,
    step_lengths,
    q_all,
    k_all,
    v_all,
    cos,
    sin,
    device,
    ort_type,
    torch_type,
    head_sink=None,
    attention_bias_all=None,
    position_ids_all=None,
    k_scale=None,
    v_scale=None,
    providers=None,
):
    """Drives a GroupQueryAttention node token-chunk by token-chunk over a shared past/present buffer.
 
    `q_all`/`k_all`/`v_all` hold the whole sequence in BSNH layout, so the same inputs can be replayed
    against a full-length cache and against a windowed one. Returns the per-step `output` tensors
    together with the final `present_key` / `present_value` buffers.
    """
    batch_size = base_config.batch_size
    kv_hidden_size = base_config.kv_num_heads * base_config.head_size
    q_hidden_size = base_config.num_heads * base_config.head_size
 
    cache_torch_type = TORCH_DTYPE_MAP[base_config.kv_cache_type] if base_config.kv_cache_type else torch_type
    cache_ort_type = ONNX_TENSOR_TYPE_MAP[base_config.kv_cache_type] if base_config.kv_cache_type else ort_type
    dense_head_size = base_config.head_size // 2 if base_config.kv_cache_type == "int4" else base_config.head_size
    cache_shape = (batch_size, base_config.kv_num_heads, buffer_sequence_length, dense_head_size)
    cache_k = torch.zeros(cache_shape, dtype=cache_torch_type, device=device)
    cache_v = torch.zeros(cache_shape, dtype=cache_torch_type, device=device)
 
    sessions = {}
    outputs = []
    past_length = 0
 
    for step_length in step_lengths:
        config = deepcopy(base_config)
        config.q_sequence_length = step_length
        config.kv_sequence_length = step_length
        config.past_kv_sequence_length = past_length
        config.buffer_sequence_length = buffer_sequence_length
        config.sliding_window_cache = sliding_window_cache
 
        if step_length not in sessions:
            sessions[step_length] = _windowed_make_session(config, ort_type, providers=providers)
        session = sessions[step_length]
 
        io_binding = session.io_binding()
 
        q = q_all[:, past_length : past_length + step_length].reshape(batch_size, step_length, q_hidden_size)
        k = k_all[:, past_length : past_length + step_length].reshape(batch_size, step_length, kv_hidden_size)
        v = v_all[:, past_length : past_length + step_length].reshape(batch_size, step_length, kv_hidden_size)
        # Keep references: io_binding only records data pointers, so temporaries would be freed.
        q, k, v = q.contiguous(), k.contiguous(), v.contiguous()
        bind_tensor(io_binding, "query", q, device, ort_type)
        bind_tensor(io_binding, "key", k, device, ort_type)
        bind_tensor(io_binding, "value", v, device, ort_type)
        bind_tensor(io_binding, "past_key", cache_k, device, cache_ort_type)
        bind_tensor(io_binding, "past_value", cache_v, device, cache_ort_type)
 
        total_length = past_length + step_length
        seqlens_k = torch.full((batch_size,), total_length - 1, dtype=torch.int32, device=device)
        bind_tensor(io_binding, "seqlens_k", seqlens_k, device, TensorProto.INT32)
        cpu_device = torch.device("cpu")
        # Keep a reference: io_binding only records the data pointer, so a temporary would be freed.
        total_sequence_length = torch.tensor([total_length], dtype=torch.int32, device=cpu_device)
        bind_tensor(
            io_binding,
            "total_sequence_length",
            total_sequence_length,
            cpu_device,
            TensorProto.INT32,
        )
 
        if cos is not None:
            bind_tensor(io_binding, "cos_cache", cos, device, ort_type)
            bind_tensor(io_binding, "sin_cache", sin, device, ort_type)
 
        if position_ids_all is not None:
            position_ids = position_ids_all[:, past_length:total_length].contiguous()
            bind_tensor(io_binding, "position_ids", position_ids, device, TensorProto.INT64)
 
        if attention_bias_all is not None:
            attention_bias = attention_bias_all[:, :, past_length:total_length, :total_length].contiguous()
            bind_tensor(io_binding, "attention_bias", attention_bias, device, ort_type)
 
        if head_sink is not None:
            bind_tensor(io_binding, "head_sink", head_sink, device, ort_type)
 
        if k_scale is not None:
            bind_tensor(io_binding, "k_scale", k_scale, device, TensorProto.FLOAT)
            bind_tensor(io_binding, "v_scale", v_scale, device, TensorProto.FLOAT)
 
        out = torch.zeros((batch_size, step_length, q_hidden_size), dtype=torch_type, device=device)
        bind_output_tensor(io_binding, "output", out, device, ort_type)
        io_binding.bind_output("present_key", device, 0, cache_ort_type, tuple(cache_k.shape), cache_k.data_ptr())
        io_binding.bind_output("present_value", device, 0, cache_ort_type, tuple(cache_v.shape), cache_v.data_ptr())
 
        io_binding.synchronize_inputs()
        session.run_with_iobinding(io_binding)
        io_binding.synchronize_outputs()
 
        outputs.append(out.clone())
        past_length = total_length
 
    return outputs, cache_k, cache_v
 
 
class TestGQAWindowedKvCache(unittest.TestCase):
    """`sliding_window_cache=1` stores only the most recent `capacity` positions of a sliding-window
    layer, in cache-relative coordinates. Because RoPE stays absolute and the retained positions are
    exactly those the window can attend to, results must match a full-length cache."""
 
    max_length = 1024
    window_size = 128
    # CUDA requires the cache capacity to equal local_window_size; the CPU subclass overrides this.
    slack = 0
 
    device = "cuda"
    torch_type = torch.float16
    ort_type = TensorProto.FLOAT16
    providers = None  # None -> resolve the CUDA (plugin) EP.
 
    def _require_ep(self):
        if not has_flash_attention():
            self.skipTest("Flash Attention is not available, skipping test.")
 
    def _base_config(self, **overrides):
        config = GQAConfig(
            batch_size=2,
            q_sequence_length=1,
            kv_sequence_length=1,
            num_heads=8,
            kv_num_heads=2,
            head_size=64,
            local_window_size=self.window_size,
            share_buffer=True,
            rope_cache_length=self.max_length,
        )
        for name, value in overrides.items():
            setattr(config, name, value)
        return config
 
    def _check_parity(self, base_config, step_lengths, rtol=1e-3, atol=1e-3, buffer_sequence_length=None):
        self._require_ep()
 
        device = self.device
        torch_type = self.torch_type
        ort_type = self.ort_type
        capacity = buffer_sequence_length or min(self.max_length, self.window_size + self.slack)
        total_length = sum(step_lengths)
        self.assertLessEqual(total_length, self.max_length)
 
        torch.manual_seed(0)
        shape = (base_config.batch_size, total_length, base_config.num_heads, base_config.head_size)
        kv_shape = (base_config.batch_size, total_length, base_config.kv_num_heads, base_config.head_size)
        q_all = torch.randn(shape, device=device, dtype=torch_type) * 0.2
        k_all = torch.randn(kv_shape, device=device, dtype=torch_type) * 0.2
        v_all = torch.randn(kv_shape, device=device, dtype=torch_type) * 0.2
 
        cos, sin = None, None
        if base_config.rotary:
            rotary_dim = math.floor(base_config.head_size / 16) * 16
            angle = torch.rand(self.max_length, rotary_dim // 2, device=device) * 2 * math.pi
            cos = torch.cos(angle).to(dtype=torch_type)
            sin = torch.sin(angle).to(dtype=torch_type)
 
        head_sink = None
        if base_config.has_head_sink:
            head_sink = torch.rand(base_config.num_heads, dtype=torch_type, device=device)
 
        attention_bias_all = None
        if base_config.has_attention_bias:
            bias_shape = (
                1 if base_config.attention_bias_broadcast_dim_0 else base_config.batch_size,
                base_config.num_heads if base_config.attention_bias_per_head else 1,
                total_length,
                total_length,
            )
            attention_bias_all = torch.randn(bias_shape, dtype=torch_type, device=device) * 0.5
 
        position_ids_all = None
        if base_config.has_position_ids:
            position_ids_all = (torch.arange(total_length, dtype=torch.int64, device=device) * 7) % self.max_length
            position_ids_all = position_ids_all.unsqueeze(0)
            position_ids_all = position_ids_all.expand(base_config.batch_size, -1).contiguous()
 
        k_scale, v_scale = None, None
        if base_config.k_quant_type != "NONE":
            k_scale, v_scale = get_static_scale(base_config, device, torch_type, 0.2)
            k_scale = k_scale.to(torch.float32).contiguous()
            v_scale = v_scale.to(torch.float32).contiguous()
 
        common = {
            "step_lengths": step_lengths,
            "q_all": q_all,
            "k_all": k_all,
            "v_all": v_all,
            "cos": cos,
            "sin": sin,
            "device": device,
            "ort_type": ort_type,
            "torch_type": torch_type,
            "head_sink": head_sink,
            "attention_bias_all": attention_bias_all,
            "position_ids_all": position_ids_all,
            "k_scale": k_scale,
            "v_scale": v_scale,
            "providers": self.providers,
        }
        reference, reference_cache_k, reference_cache_v = _windowed_run_steps(base_config, self.max_length, 0, **common)
        if base_config.k_quant_type != "NONE" and any(torch.isnan(step).any() for step in reference):
            # A quantized KV cache is only read correctly by the flash-attention prefill kernels.
            # Builds without them route the first prompt through memory-efficient attention, which
            # reinterprets the quantized cache as unquantized and produces NaN for both the
            # windowed and the full-length run, so there is nothing to compare.
            self.skipTest("quantized prefill needs a build with flash attention enabled")
        windowed, cache_k, cache_v = _windowed_run_steps(base_config, capacity, 1, **common)
 
        for step_index, (expected, actual) in enumerate(zip(reference, windowed, strict=True)):
            numpy.testing.assert_allclose(
                actual.float().cpu().numpy(),
                expected.float().cpu().numpy(),
                rtol=rtol,
                atol=atol,
                err_msg=f"mismatch at step {step_index} (step_lengths={step_lengths})",
            )
 
        # Layout contract: rows [0, L) of present_key/present_value hold the L most recent positions
        # in increasing position order. The full-length reference run stores every position at its
        # absolute row, so its tail is the exact byte-for-byte expectation for the windowed rows --
        # this holds for RoPE'd and quantized caches too, because both runs write the same values.
        resident = _windowed_resident_count(total_length, capacity, base_config.local_window_size)
        for name, actual_cache, reference_cache in (
            ("present_key", cache_k, reference_cache_k),
            ("present_value", cache_v, reference_cache_v),
        ):
            numpy.testing.assert_array_equal(
                actual_cache[:, :, :resident].cpu().numpy(),
                reference_cache[:, :, total_length - resident : total_length].cpu().numpy(),
                err_msg=f"{name} resident range mismatch (L={resident}, T={total_length}, C={capacity})",
            )
 
    def test_prompt_shorter_than_capacity_then_decode(self):
        # Prompt fits in the cache; eviction only starts once the window slides past the capacity.
        steps = [64, *([1] * 400)]
        self._check_parity(self._base_config(), steps)
 
    def test_prompt_longer_than_capacity_then_decode(self):
        # Prompt exceeds the capacity, so the first call must attend over the full prompt while
        # seeding the cache with only the tail. Exercises the windowed first-prompt path.
        steps = [512, *([1] * 200)]
        self._check_parity(self._base_config(), steps)
 
    def test_chunked_prefill(self):
        # Multi-token chunks arriving on a partially filled cache.
        # GroupQueryAttention only allows a subsequent prompt (1 < S < T) at batch_size 1.
        steps = [128] * 6 + [1] * 32
        self._check_parity(self._base_config(batch_size=1), steps)
 
    def test_eviction_boundaries(self):
        # Land exactly on capacity - 1, capacity and capacity + 1 with single-token steps.
        capacity = self.window_size + self.slack
        steps = [capacity - 2, *([1] * 8)]
        self._check_parity(self._base_config(), steps)
 
    def test_with_rotary(self):
        # RoPE positions stay absolute even though the cache is indexed relative to its start.
        steps = [64, *([1] * 400)]
        self._check_parity(self._base_config(rotary=True), steps)
 
    def test_gpt_oss_shape_with_head_sink(self):
        # gpt-oss: attention sinks, RoPE, and alternating 128-token sliding-window layers.
        steps = [512, *([1] * 200)]
        self._check_parity(
            self._base_config(num_heads=8, kv_num_heads=2, head_size=64, rotary=True, has_head_sink=True), steps
        )
 
    @unittest.skipIf(not has_quantized_kv_cache(), "Quantized KV cache is not available, skipping test.")
    def test_int8_quantized_cache(self):
        # gpt-oss stores the cache as PER_CHANNEL int8; eviction and staging must move the
        # quantized rows around without dequantizing them.
        steps = [512, *([1] * 200)]
        self._check_parity(
            self._base_config(
                num_heads=8,
                kv_num_heads=2,
                head_size=64,
                rotary=True,
                has_head_sink=True,
                kv_cache_type="int8",
                k_quant_type="PER_CHANNEL",
                v_quant_type="PER_CHANNEL",
                kv_cache_bit_width=8,
            ),
            steps,
            rtol=5e-2,
            atol=1e-1,
        )
 
    def test_batch_one_packed_head_layout(self):
        steps = [200, *([1] * 300)]
        self._check_parity(self._base_config(batch_size=1, num_heads=4, kv_num_heads=4, head_size=128), steps)
 
    def test_capacity_equal_to_window_size(self):
        # C == W leaves no slack, so a multi-token step needs more entries than the cache can hold.
        # The op stages such a step, so this must still match a full cache exactly.
        capacity = self.window_size
        self._check_parity(
            self._base_config(batch_size=1), step_lengths=[32, 16, 1, 1], buffer_sequence_length=capacity
        )
 
    def test_capacity_larger_than_window(self):
        # CUDA evicts the minimum number of rows per step, which reproduces the documented layout
        # only when there is no slack above the window, so C > W is rejected.
        self._require_ep()
 
        with self.assertRaisesRegex(Exception, "requires the KV cache capacity.*to equal local_window_size"):
            self._check_parity(
                self._base_config(batch_size=1),
                step_lengths=[32, 1, 1],
                buffer_sequence_length=self.window_size + 8,
            )
 
    def test_capacity_too_small_is_rejected(self):
        self._require_ep()
 
        device = self.device
        torch_type = self.torch_type
        ort_type = self.ort_type
        # A cache shorter than the attention window can never hold everything the window covers.
        capacity = self.window_size - 1
        config = self._base_config(rope_cache_length=capacity)
        with self.assertRaisesRegex(Exception, "sliding_window_cache"):
            _windowed_run_steps(
                config,
                capacity,
                1,
                step_lengths=[32, 16],
                q_all=torch.zeros(
                    (config.batch_size, 48, config.num_heads, config.head_size), device=device, dtype=torch_type
                ),
                k_all=torch.zeros(
                    (config.batch_size, 48, config.kv_num_heads, config.head_size), device=device, dtype=torch_type
                ),
                v_all=torch.zeros(
                    (config.batch_size, 48, config.kv_num_heads, config.head_size), device=device, dtype=torch_type
                ),
                cos=None,
                sin=None,
                device=device,
                ort_type=ort_type,
                torch_type=torch_type,
                providers=self.providers,
            )
 
    def test_requires_local_window_size(self):
        self._require_ep()
 
        config = self._base_config(
            local_window_size=-1,
            sliding_window_cache=1,
            buffer_sequence_length=self.window_size + self.slack,
            rope_cache_length=self.window_size + self.slack,
        )
        with self.assertRaisesRegex(Exception, "sliding_window_cache"):
            _windowed_make_session(config, self.ort_type, providers=self.providers)
 
 
class TestGQAWindowedKvCacheCpu(TestGQAWindowedKvCache):
    """Same parity contract as the CUDA suite, run against the CPU GroupQueryAttention kernel."""
 
    device = "cpu"
    torch_type = torch.float32
    ort_type = TensorProto.FLOAT
    providers: typing.ClassVar[list[str]] = ["CPUExecutionProvider"]
    # The CPU kernel accepts any capacity at or above the window and uses the slack to amortize
    # compaction, so it is exercised with a capacity well above local_window_size.
    slack = 256
 
    def _require_ep(self):
        pass
 
    def _base_config(self, **overrides):
        # The float32 CPU kernel keeps an unquantized float32 cache by default.
        overrides.setdefault("kv_cache_type", "float32")
        return super()._base_config(**overrides)
 
    def test_capacity_larger_than_window(self):
        # CPU accepts slack above the window; the resident count then sawtooths between W and C
        # instead of staying at min(T, C). Exercised in depth by the two small-slack tests below.
        self._check_parity(
            self._base_config(batch_size=1),
            step_lengths=[32, 1, 1],
            buffer_sequence_length=self.window_size + 8,
        )
 
    def test_small_slack_many_compactions(self):
        # C == W + 8 reclaims only 9 rows per compaction, so a long decode run crosses the
        # compaction boundary dozens of times instead of once or twice.
        self._check_parity(
            self._base_config(), step_lengths=[64, *([1] * 400)], buffer_sequence_length=self.window_size + 8
        )
 
    def test_chunked_prefill_small_slack(self):
        # 32-token chunks onto a cache with 9 free rows: once the cache has filled, every chunk
        # drops rows its own first query still reads, so it must stage from a drifted append point.
        # GroupQueryAttention only allows a subsequent prompt (1 < S < T) at batch_size 1.
        self._check_parity(
            self._base_config(batch_size=1),
            step_lengths=[32] * 10 + [1] * 20,
            buffer_sequence_length=self.window_size + 8,
        )
 
    def test_attention_bias_with_position_ids(self):
        self._check_parity(
            self._base_config(
                rotary=True,
                has_position_ids=True,
                has_attention_bias=True,
                attention_bias_per_head=True,
            ),
            step_lengths=[64, *([1] * 400)],
        )
 
    def test_attention_bias_with_position_ids_non_flash(self):
        with scoped_env_var("ORT_GQA_DISABLE_FLASH_ATTENTION", "1"):
            self._check_parity(
                self._base_config(
                    rotary=True,
                    has_position_ids=True,
                    has_attention_bias=True,
                    attention_bias_per_head=True,
                ),
                step_lengths=[self.window_size + self.slack, 1, 1],
            )
 
 
if __name__ == "__main__":
    unittest.main()