Исходный код СУБД 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
#!/usr/bin/env python
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from __future__ import annotations
 
import os
import tempfile
import unittest
from pathlib import Path
 
import numpy as np
import onnx
from onnx import TensorProto, helper, numpy_helper
from op_test_utils import (
    TestDataFeeds,
    check_model_correctness,
    check_op_type_count,
    check_op_type_order,
    create_clip_node,
    get_tensor_consumers_and_producers,
)
 
import onnxruntime as ort
from onnxruntime.quantization import QDQQuantizer, QuantFormat, QuantType, quantize_static, write_calibration_table
from onnxruntime.quantization.calibrate import CalibrationMethod, TensorData, TensorsData
from onnxruntime.quantization.quant_utils import quantize_nparray
 
 
# TODO(titaiwang and justinchuby): What is the recommendation here after onnx deleted this function?
def _unpack_single_4bitx2(x: np.ndarray | np.dtype | float, signed: bool) -> tuple[np.ndarray, np.ndarray]:
    def unpack_signed(x):
        return np.where((x >> 3) == 0, x, x | 0xF0)
 
    """Unpack a single byte 4bitx2 to two 4 bit elements
    Args:
        x: Input data
        signed: boolean, whether to interpret as signed int4.
    Returns:
        A tuple of ndarrays containing int4 elements (sign-extended to int8/uint8)
    """
    if not isinstance(x, np.ndarray):
        x = np.asarray(x)
    x_low = x & 0x0F
    x_high = x >> 4
    x_low = unpack_signed(x_low) if signed else x_low
    x_high = unpack_signed(x_high) if signed else x_high
    dtype = np.int8 if signed else np.uint8
    return (x_low.astype(dtype), x_high.astype(dtype))
 
 
class TestQDQFormat(unittest.TestCase):
    def input_feeds(self, n, name2shape, np_float_type=np.float32):
        input_data_list = []
        for _i in range(n):
            inputs = {}
            for name, shape in name2shape.items():
                inputs.update({name: np.random.randint(-1, 2, shape).astype(np_float_type)})
            input_data_list.extend([inputs])
        dr = TestDataFeeds(input_data_list)
        return dr
 
 
class TestQDQExtraOptions(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.qdq.extra_options_")
 
        # Note: swap with the commented line if you want to see the models in local test dir.
        cls._tmp_dir_path = cls._tmp_model_dir.name
        # cls._tmp_dir_path = "."
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def test_qdq_extra_options(self):
        #   (input)
        #      |
        #     Add
        #      |
        #     ReduceMean
        #      |
        #     Add
        #      |
        #   (output)
 
        initializers = []
 
        input_tensor = helper.make_tensor_value_info("L", TensorProto.FLOAT, [5, 5])
        output_tensor = helper.make_tensor_value_info("O", TensorProto.FLOAT, [5, 5])
 
        add_weight_data_1 = np.random.normal(0, 0.1, [5, 5]).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(add_weight_data_1, name="M"))
        add_weight_data_2 = np.random.normal(0, 0.1, [5, 5]).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(add_weight_data_2, name="N"))
 
        add_node_1 = onnx.helper.make_node("Add", ["L", "M"], ["P"], name="Add1")
        reduce_mean_node = onnx.helper.make_node("ReduceMean", ["P"], ["Q"], keepdims=1, name="ReduceMean")
        add_node_2 = onnx.helper.make_node("Add", ["Q", "N"], ["O"], name="Add2")
 
        graph = helper.make_graph(
            [add_node_1, reduce_mean_node, add_node_2],
            "QDQ_Test_Finetune",
            [input_tensor],
            [output_tensor],
            initializer=initializers,
        )
        model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
        test_model_path = "./test_qdq_finetune.onnx"
        onnx.save(model, test_model_path)
 
        def td(vals):
            return TensorData(lowest=np.array(vals[0], dtype=np.float32), highest=np.array(vals[1], dtype=np.float32))
 
        compute_data = {
            "P": td([0.1, 0.1]),
            "Q": td([0.1, 0.1]),
            "M": td([0.1, 0.1]),
            "N": td([0.1, 0.1]),
            "L": td([0.1, 0.1]),
            "O": td([0.1, 0.1]),
        }
 
        op_types_to_quantize = ["Add"]
 
        model = onnx.load_model(test_model_path)
        quantizer = QDQQuantizer(
            model,
            True,  # per_channel
            False,  # reduce_range
            QuantType.QInt8,  # weight_type
            QuantType.QInt8,  # activation_type
            compute_data,
            [],  # nodes_to_quantize
            ["Add2"],  # nodes_to_exclude
            op_types_to_quantize,
            {
                "ActivationSymmetric": True,
                "AddQDQPairToWeight": True,
                "OpTypesToExcludeOutputQuantization": [],
            },
        )  # extra_options
        quantizer.quantize_model()
        qdq_model_path = "./test_qdq_finetune_qdq.onnx"
        quantizer.model.save_model_to_file(qdq_model_path, False)
 
        # QDQ pair should be added to Add1 but not Add2
        # QDQ pair shoud be added to Add1 output as well.
        qdq_added_to_node_output_flag = False
        for node in quantizer.model.nodes():
            if node.name == "Add1":
                for input in node.input:
                    self.assertTrue("DequantizeLinear" in input)
                for output in node.output:
                    self.assertTrue("QuantizeLinear" not in output)
 
            if node.name == "Add2":
                for input in node.input:
                    self.assertTrue("DequantizeLinear" not in input)
                for output in node.output:
                    self.assertTrue("QuantizeLinear" not in output)
 
            # This QuantizeLinear node should be followed by Add1
            if node.name == "P_QuantizeLinear":
                qdq_added_to_node_output_flag = True
                self.assertTrue(node.input[0] == "P")
 
        self.assertTrue(qdq_added_to_node_output_flag)
 
    def test_qdq_extra_options_2(self):
        #         (input)
        #           |
        #          Add
        #       /   |   \
        #  MatMul MatMul MatMul
        #     |     |      |
        # (output)(output)(output)
 
        initializers = []
 
        input_tensor = helper.make_tensor_value_info("L", TensorProto.FLOAT, [5, 5])
        output_tensor1 = helper.make_tensor_value_info("M", TensorProto.FLOAT, [5, 5])
        output_tensor2 = helper.make_tensor_value_info("N", TensorProto.FLOAT, [5, 5])
        output_tensor3 = helper.make_tensor_value_info("O", TensorProto.FLOAT, [5, 5])
 
        add_weight_data = np.random.normal(0, 0.1, [5, 5]).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(add_weight_data, name="P"))
        matmul_weight_data_1 = np.random.normal(0, 0.1, [5, 5]).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(matmul_weight_data_1, name="Q"))
        matmul_weight_data_2 = np.random.normal(0, 0.1, [5, 5]).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(matmul_weight_data_2, name="R"))
        initializers.append(onnx.numpy_helper.from_array(matmul_weight_data_2, name="S"))
 
        add_node = onnx.helper.make_node("Add", ["L", "P"], ["T"], name="Add")
        matmul_node_1 = onnx.helper.make_node("MatMul", ["T", "Q"], ["M"], name="MatMul1")
        matmul_node_2 = onnx.helper.make_node("MatMul", ["T", "R"], ["N"], name="MatMul2")
        matmul_node_3 = onnx.helper.make_node("MatMul", ["T", "S"], ["O"], name="MatMul3")
 
        graph = helper.make_graph(
            [add_node, matmul_node_1, matmul_node_2, matmul_node_3],
            "QDQ_Test_Finetune_2",
            [input_tensor],
            [output_tensor1, output_tensor2, output_tensor3],
            initializer=initializers,
        )
        model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
        test_model_path = "./test_qdq_finetune_2.onnx"
        onnx.save(model, test_model_path)
 
        def td(vals):
            return TensorData(lowest=np.array(vals[0], dtype=np.float32), highest=np.array(vals[1], dtype=np.float32))
 
        compute_data = {
            "L": td([0.1, 0.1]),
            "M": td([0.1, 0.1]),
            "N": td([0.1, 0.1]),
            "O": td([0.1, 0.1]),
            "P": td([0.1, 0.1]),
            "Q": td([0.1, 0.1]),
            "R": td([0.1, 0.1]),
            "S": td([0.1, 0.1]),
            "T": td([0.1, 0.1]),
        }
 
        op_types_to_quantize = ["Add", "MatMul"]
 
        model = onnx.load_model(test_model_path)
        quantizer = QDQQuantizer(
            model,
            True,  # per_channel
            False,  # reduce_range
            QuantType.QInt8,  # weight_type
            QuantType.QInt8,  # activation_type
            compute_data,
            [],  # nodes_to_quantize
            ["Add"],  # nodes_to_exclude
            op_types_to_quantize,
            {
                "ActivationSymmetric": True,
                "AddQDQPairToWeight": True,
                "OpTypesToExcludeOutputQuantization": op_types_to_quantize,
                "DedicatedQDQPair": True,
            },
        )  # extra_options
        quantizer.quantize_model()
        qdq_model_path = "./test_qdq_finetune_qdq_2.onnx"
        quantizer.model.save_model_to_file(qdq_model_path, False)
 
        # Three dedicated QDQ pair should be generated and feed into each MatMul node
        # Also QDQ pair should not be added to Add node
        # QDQ pair shoud not be added to node's output
        for node in quantizer.model.nodes():
            if node.name == "MatMul1":
                self.assertIn("T_DequantizeLinear_Output_1", node.input)
            elif node.name == "MatMul2":
                self.assertIn("T_DequantizeLinear_Output_2", node.input)
            elif node.name == "MatMul3":
                self.assertIn("T_DequantizeLinear_Output_3", node.input)
            elif node.name == "Add":
                self.assertNotIn("L_DequantizeLinear_Output", node.input)
 
            # QDQ pair shoud not be added to MatMul's output
            if node.op_type == "QuantizeLinear":
                self.assertNotIn(
                    node.input[0],
                    {
                        "M_QuantizeLinear_Input",
                        "N_QuantizeLinear_Input",
                        "O_QuantizeLinear_Input",
                    },
                )
 
    def test_qdq_keep_removable_activations_option(self):
        #
        # Create f32 model with Relu and Clip.
        # input0 ---> Conv ---> Relu ---> Conv ---> Clip ---> output
        #
        shape1 = (1, 1, 3, 3)
        w_shape1 = (2, 1, 2, 2)
        w_shape2 = (2, 2, 2, 2)
        shape3 = (1, 2, 1, 1)
 
        input0 = onnx.helper.make_tensor_value_info("input0", onnx.TensorProto.FLOAT, shape1)
        output = onnx.helper.make_tensor_value_info("output", onnx.TensorProto.FLOAT, shape3)
 
        # Conv1
        weight1_data = np.random.normal(-1.0, 1.0, w_shape1).astype(np.float32)
        weight1_const = onnx.numpy_helper.from_array(weight1_data, "weight1_const")
        conv1_node = onnx.helper.make_node("Conv", ["input0", "weight1_const"], ["conv1_out"], name="conv1_node")
 
        # Relu1
        relu1_node = onnx.helper.make_node("Relu", ["conv1_out"], ["relu1_out"], name="relu1_node")
 
        # Conv2
        weight2_data = np.random.normal(-1.8, 1.8, w_shape2).astype(np.float32)
        weight2_const = onnx.numpy_helper.from_array(weight2_data, "weight2_const")
        conv2_node = onnx.helper.make_node("Conv", ["relu1_out", "weight2_const"], ["conv2_out"], name="conv2_node")
 
        # Clip1
        min_const = onnx.numpy_helper.from_array(np.array(0.0, dtype=np.float32), "min_const")
        max_const = onnx.numpy_helper.from_array(np.array(0.5, dtype=np.float32), "max_const")
        clip1_node = onnx.helper.make_node(
            "Clip", ["conv2_out", "min_const", "max_const"], ["output"], name="clip1_node"
        )
 
        graph = onnx.helper.make_graph(
            [conv1_node, relu1_node, conv2_node, clip1_node],
            "keep_qdq_activations",
            [input0],
            [output],
            initializer=[weight1_const, weight2_const, min_const, max_const],
        )
        opset_imports = [
            onnx.helper.make_opsetid("", 18),
        ]
        f32_model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        f32_model = onnx.shape_inference.infer_shapes(f32_model)
        f32_model_path = os.path.join(self._tmp_dir_path, "keep.act.model.onnx")
        onnx.save_model(f32_model, f32_model_path)
 
        # Create a data reader.
        input_data_list = []
        for _ in range(5):
            inputs = {"input0": np.random.randint(-10, 10, shape1).astype(np.float32)}
            input_data_list.extend([inputs])
        data_reader = TestDataFeeds(input_data_list)
 
        #
        # Quantize model with extra option to KEEP removable activations.
        #
        qdq_model_path = os.path.join(self._tmp_dir_path, "keep.act.model.qdq.onnx")
 
        # Create u8_act/u8_wgt qdq model
        quantize_static(
            f32_model_path,
            qdq_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt8,
            weight_type=QuantType.QUInt8,
            op_types_to_quantize=[node.op_type for node in f32_model.graph.node],
            extra_options={"QDQKeepRemovableActivations": True},
        )
 
        has_relu = False
        has_clip = False
 
        qdq_model = onnx.load_model(qdq_model_path)
 
        for node in qdq_model.graph.node:
            if node.op_type == "Relu":
                has_relu = True
            if node.op_type == "Clip":
                has_clip = True
 
        self.assertTrue(has_relu)
        self.assertTrue(has_clip)
 
        #
        # Quantize model without extra option. Clip and Relu should be removed by default.
        #
        qdq_model_path = os.path.join(self._tmp_dir_path, "nokeep.act.model.qdq.onnx")
        data_reader.rewind()
 
        # Create u8_act/u8_wgt qdq model
        quantize_static(
            f32_model_path,
            qdq_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt8,
            weight_type=QuantType.QUInt8,
            op_types_to_quantize=[node.op_type for node in f32_model.graph.node],
        )
 
        has_relu = False
        has_clip = False
 
        qdq_model = onnx.load_model(qdq_model_path)
 
        for node in qdq_model.graph.node:
            if node.op_type == "Relu":
                has_relu = True
            if node.op_type == "Clip":
                has_clip = True
 
        self.assertFalse(has_relu)
        self.assertFalse(has_clip)
 
 
class TestQDQFormatConv(TestQDQFormat):
    def check_per_channel_counts(self, model_path, channel_count: int, axis: int = 0):
        model = onnx.load(Path(model_path))
        for initializer in model.graph.initializer:
            dims = initializer.dims
            # skip if initializer is not a weight
            if len(dims) > 0:
                self.assertGreater(len(dims), axis)
                self.assertEqual(channel_count, dims[axis])
 
    def construct_model_conv(self, output_model_path, input_shape, weight_shape, output_shape, has_bias):
        #    (input)
        #      |
        #     Conv
        #      |
        #    (output)
        input_name = "input"
        output_name = "output"
        initializers = []
 
        # make Conv node
        weight_name = "conv_weight"
        bias_name = "conv_bias"
        conv_inputs = [input_name, weight_name]
        conv_outputs = [output_name]
        conv_name = "conv_node"
        conv_weight_data = np.random.normal(0, 0.1, weight_shape).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(conv_weight_data, name=weight_name))
        if has_bias:
            conv_inputs.append(bias_name)
            bias_data = np.random.normal(0, 0.05, (weight_shape[0])).astype(np.float32)
            initializers.append(onnx.numpy_helper.from_array(bias_data, name=bias_name))
        conv_node = onnx.helper.make_node("Conv", conv_inputs, conv_outputs, name=conv_name)
 
        # make graph
        input_tensor = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, input_shape)
        output_tensor = helper.make_tensor_value_info(output_name, TensorProto.FLOAT, output_shape)
        graph_name = "QDQ_Test_Conv"
        graph = helper.make_graph(
            [conv_node],
            graph_name,
            [input_tensor],
            [output_tensor],
            initializer=initializers,
        )
        model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
        model.ir_version = 7  # use stable onnx ir version
 
        onnx.save(model, output_model_path)
 
    def verify_quantize_conv(self, has_bias, per_channel, is_quant_type_int8=False):
        np.random.seed(1)
        model_fp32_path = f"conv_fp32.{has_bias}.{per_channel}.onnx"
        model_int8_qdq_path = f"conv_quant_qdq.{has_bias}.{per_channel}.onnx"
        model_int8_qop_path = f"conv_quant_qop.{has_bias}.{per_channel}.onnx"
        channel_count = 16
        data_reader = self.input_feeds(1, {"input": [1, 8, 33, 33]})
        self.construct_model_conv(model_fp32_path, [1, 8, 33, 33], [channel_count, 8, 3, 3], [1, 16, 31, 31], has_bias)
        quantize_static(
            model_fp32_path,
            model_int8_qdq_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            per_channel=per_channel,
            reduce_range=per_channel,
            activation_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
            weight_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
        )
        data_reader.rewind()
        qdq_nodes = {
            "Conv": 1,
            "QuantizeLinear": 2,
            "DequantizeLinear": 4 if has_bias else 3,
        }
        check_op_type_count(self, model_int8_qdq_path, **qdq_nodes)
        if per_channel:
            self.check_per_channel_counts(model_int8_qdq_path, channel_count)
        check_model_correctness(self, model_fp32_path, model_int8_qdq_path, data_reader.get_next())
 
        data_reader.rewind()
        quantize_static(
            model_fp32_path,
            model_int8_qop_path,
            data_reader,
            quant_format=QuantFormat.QOperator,
            per_channel=per_channel,
            reduce_range=per_channel,
            activation_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
            weight_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
        )
        data_reader.rewind()
        qop_nodes = {"QLinearConv": 1, "QuantizeLinear": 1, "DequantizeLinear": 1}
        check_op_type_count(self, model_int8_qop_path, **qop_nodes)
        check_model_correctness(self, model_fp32_path, model_int8_qop_path, data_reader.get_next())
 
    def test_quantize_conv_without_bias(self):
        # only test cases per_channel=True and reduce_range=True to avoid saturation on avx2 and avx512 for weight type int8
        self.verify_quantize_conv(False, True, True)  # has_bias:False, per_channel:True, is_quant_type_int8:True
        self.verify_quantize_conv(True, True, True)  # has_bias:True, per_channel:True, is_quant_type_int8:True
 
        self.verify_quantize_conv(False, False, False)  # has_bias:False, per_channel:False, is_quant_type_int8:False
        self.verify_quantize_conv(True, False, False)  # has_bias:True, per_channel:False, is_quant_type_int8:False
        self.verify_quantize_conv(False, True, False)  # has_bias:False, per_channel:True, is_quant_type_int8:False
        self.verify_quantize_conv(True, True, False)  # has_bias:True, per_channel:True, is_quant_type_int8:False
 
 
class TestQDQFormatConvClip(TestQDQFormat):
    def construct_model_conv_clip(self, output_model_path, input_shape, weight_shape, output_shape):
        #    (input)
        #      |
        #     Conv
        #      |
        #     Clip
        #      |
        #   Reshape
        #      |
        #    (output)
        input_name = "input"
        output_name = "output"
        initializers = []
 
        # make Conv node
        weight_name = "conv_weight"
        conv_inputs = [input_name, weight_name]
        conv_outputs = ["conv_output"]
        conv_name = "conv_node"
        conv_weight_data = np.random.normal(0, 0.1, weight_shape).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(conv_weight_data, name=weight_name))
        conv_node = onnx.helper.make_node("Conv", conv_inputs, conv_outputs, name=conv_name)
 
        # make Clip node
        clip_node = create_clip_node(conv_outputs[0], "clip_output", "clip_node", initializers)
 
        # make Identity node
        reshape_name = "reshape_node"
        reshape_shape = "reshape_shape"
        initializers.append(onnx.numpy_helper.from_array(np.array([-1], dtype=np.int64), name=reshape_shape))
        reshape_node = onnx.helper.make_node(
            "Reshape", ["clip_output", reshape_shape], [output_name], name=reshape_name
        )
 
        # make graph
        input_tensor = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, input_shape)
        output_tensor = helper.make_tensor_value_info(output_name, TensorProto.FLOAT, output_shape)
        graph_name = "QDQ_Test_Conv_clip"
        graph = helper.make_graph(
            [conv_node, clip_node, reshape_node],
            graph_name,
            [input_tensor],
            [output_tensor],
            initializer=initializers,
        )
        model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
        model.ir_version = 7  # use stable onnx ir version
 
        onnx.save(model, output_model_path)
 
    def verify(self, per_channel, is_quant_type_int8):
        np.random.seed(1)
        model_fp32_path = f"conv_clip_fp32.{per_channel}.onnx"
        model_int8_qdq_path = f"conv_clip_quant_qdq.{per_channel}.onnx"
        model_int8_qop_path = f"conv_clip_quant_qop.{per_channel}.onnx"
        data_reader = self.input_feeds(1, {"input": [1, 8, 33, 33]})
        self.construct_model_conv_clip(model_fp32_path, [1, 8, 33, 33], [16, 8, 3, 3], [15376])
        quantize_static(
            model_fp32_path,
            model_int8_qdq_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            per_channel=per_channel,
            reduce_range=per_channel,
            activation_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
            weight_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
        )
        data_reader.rewind()
        # topo sort check
        check_op_type_order(
            self,
            model_int8_qdq_path,
            [
                "DequantizeLinear",
                "QuantizeLinear",
                "DequantizeLinear",
                "Conv",
                "QuantizeLinear",
                "DequantizeLinear",
                "Reshape",
                "QuantizeLinear",
                "DequantizeLinear",
            ],
        )
        check_model_correctness(self, model_fp32_path, model_int8_qdq_path, data_reader.get_next())
 
        data_reader.rewind()
        quantize_static(
            model_fp32_path,
            model_int8_qop_path,
            data_reader,
            quant_format=QuantFormat.QOperator,
            per_channel=per_channel,
            reduce_range=per_channel,
            activation_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
            weight_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
        )
        data_reader.rewind()
        qop_nodes = {"QLinearConv": 1, "QuantizeLinear": 1, "DequantizeLinear": 1}
        check_op_type_count(self, model_int8_qop_path, **qop_nodes)
        check_model_correctness(self, model_fp32_path, model_int8_qop_path, data_reader.get_next())
 
    def test_quantize_conv_without_bias(self):
        # only test cases per_channel=True and reduce_range=True to avoid saturation on avx2 and avx512 for weight type int8
        self.verify(True, True)  # per_channel:False, is_quant_type_int8:True
 
        self.verify(False, False)  # per_channel:False, is_quant_type_int8:False
        self.verify(True, False)  # per_channel:True, is_quant_type_int8:False
 
 
def generate_input_initializer(tensor_shape, tensor_dtype, input_name):
    """
    Helper function to generate initializers for test inputs
    """
    tensor = np.random.normal(0, 0.3, tensor_shape).astype(tensor_dtype)
    init = numpy_helper.from_array(tensor, input_name)
    return init
 
 
def construct_relu_conv_model(test_model_path: str) -> None:
    """ Create an ONNX model shaped as:
    ```
       (input)
          |
         Relu1
         /   \
      Conv1   \
        |      \
      Relu2  Conv3
        |      |
      Conv2    |
        \\      /
          Add
           |
          (AddOut)
    ```
    """
 
    input_vi = helper.make_tensor_value_info("input", TensorProto.FLOAT, [1, 3, 1, 3])
    output_vi = helper.make_tensor_value_info("AddOut", TensorProto.FLOAT, [1, 3, 1, 3])
    w1 = generate_input_initializer([3, 3, 1, 1], np.float32, "W1")
    b1 = generate_input_initializer([3], np.float32, "B1")
    w3 = generate_input_initializer([3, 3, 1, 1], np.float32, "W3")
    b3 = generate_input_initializer([3], np.float32, "B3")
    w5 = generate_input_initializer([3, 3, 1, 1], np.float32, "W5")
    b5 = generate_input_initializer([3], np.float32, "B5")
    relu_node_1 = helper.make_node("Relu", ["input"], ["Relu1Out"], name="Relu1")
    conv_node_1 = helper.make_node("Conv", ["Relu1Out", "W1", "B1"], ["Conv1Out"], name="Conv1")
    relu_node_2 = helper.make_node("Relu", ["Conv1Out"], ["Relu2Out"], name="Relu2")
    conv_node_2 = helper.make_node("Conv", ["Relu2Out", "W3", "B3"], ["Conv2Out"], name="Conv2")
    conv_node_3 = helper.make_node("Conv", ["Relu1Out", "W5", "B5"], ["Conv3Out"], name="Conv3")
    add_node = helper.make_node("Add", ["Conv2Out", "Conv3Out"], ["AddOut"], name="Add")
 
    graph = helper.make_graph(
        [relu_node_1, conv_node_1, relu_node_2, conv_node_2, conv_node_3, add_node],
        "test_graph_4",
        [input_vi],
        [output_vi],
    )
    graph.initializer.add().CopyFrom(w1)
    graph.initializer.add().CopyFrom(b1)
    graph.initializer.add().CopyFrom(w3)
    graph.initializer.add().CopyFrom(b3)
    graph.initializer.add().CopyFrom(w5)
    graph.initializer.add().CopyFrom(b5)
    model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
    onnx.save(model, test_model_path)
 
 
class TestQDQFormatConvRelu(TestQDQFormat):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="test_qdq_format_conv_relu")
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def construct_model_conv_relu(
        self, output_model_path, input_shape, weight_shape, output_shape, opset=13, ir_version=7
    ):
        #    (input)
        #      |
        #     Conv
        #      |
        #     Relu
        #      |
        #    (output)
        input_name = "input"
        output_name = "output"
        initializers = []
 
        # make Conv node
        weight_name = "conv_weight"
        conv_inputs = [input_name, weight_name]
        conv_outputs = ["conv_output"]
        conv_name = "conv_node"
        conv_weight_data = np.random.normal(0, 0.1, weight_shape).astype(np.float32)
        initializers.append(onnx.numpy_helper.from_array(conv_weight_data, name=weight_name))
        conv_node = onnx.helper.make_node("Conv", conv_inputs, conv_outputs, name=conv_name)
 
        # make Relu node
        relu_node = onnx.helper.make_node("Relu", conv_outputs, [output_name], name="Relu")
 
        # make graph
        input_tensor = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, input_shape)
        output_tensor = helper.make_tensor_value_info(output_name, TensorProto.FLOAT, output_shape)
        graph_name = "QDQ_Test_Conv_Relu"
        graph = helper.make_graph(
            [conv_node, relu_node],
            graph_name,
            [input_tensor],
            [output_tensor],
            initializer=initializers,
        )
        model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", opset)])
        model.ir_version = ir_version
 
        onnx.save(model, output_model_path)
 
    def verify_qdq(
        self,
        per_channel,
        activation_type,
        weight_type,
        extra_options=None,
        opset=13,
        ir_version=7,
        rtol=1e-2,
        atol=0.05,
    ):
        np.random.seed(1)
        model_fp32_path = str(Path(self._tmp_model_dir.name) / f"conv_relu_fp32.{per_channel}.onnx")
        model_qdq_path = str(
            Path(self._tmp_model_dir.name) / f"conv_relu_quant_qdq.{activation_type}.{weight_type}.{per_channel}.onnx"
        )
        data_reader = self.input_feeds(1, {"input": [1, 8, 33, 33]})
        self.construct_model_conv_relu(
            model_fp32_path, [1, 8, 33, 33], [16, 8, 3, 3], [1, 16, 31, 31], opset=opset, ir_version=ir_version
        )
        quantize_static(
            model_fp32_path,
            model_qdq_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            per_channel=per_channel,
            reduce_range=per_channel,
            activation_type=activation_type,
            weight_type=weight_type,
            extra_options=extra_options,
        )
        data_reader.rewind()
        # topo sort check
        check_op_type_order(
            self,
            model_qdq_path,
            [
                "DequantizeLinear",
                "QuantizeLinear",
                "DequantizeLinear",
                "Conv",
                "QuantizeLinear",
                "DequantizeLinear",
            ],
        )
 
        # checks that the qdq model has INT4 or INT16 types when expected
        with open(model_qdq_path, "rb") as f:
            qdq_model = onnx.load(f)
        inits = {init.name: init for init in qdq_model.graph.initializer}
        zero_types = []
        for node in qdq_model.graph.node:
            print(node.op_type)
            if node.op_type not in {"QuantizeLinear", "DequantizeLinear"}:
                continue
            zp = inits[node.input[2]]
            zero_types.append(zp.data_type)
 
        to_tensor_types = {
            QuantType.QInt4: TensorProto.INT4,
            QuantType.QUInt4: TensorProto.UINT4,
            QuantType.QInt16: TensorProto.INT16,
            QuantType.QUInt16: TensorProto.UINT16,
        }
        assert weight_type not in to_tensor_types or to_tensor_types[weight_type] in zero_types, (
            f"weight_type={weight_type} not in zero_types={zero_types}"
        )
        assert activation_type not in to_tensor_types or to_tensor_types[activation_type] in zero_types, (
            f"activation_type={activation_type} not in zero_types={zero_types}"
        )
 
        check_model_correctness(self, model_fp32_path, model_qdq_path, data_reader.get_next(), rtol=rtol, atol=atol)
 
        # If the model uses Q/DQ ops with "com.microsoft" domain (e.g., for int16 support),
        # then ensure the model has the appropriate opset import.
        if extra_options and extra_options.get("UseQDQContribOps", False):
            qdq_model = onnx.load_model(model_qdq_path)
            ms_opset = next((opset for opset in qdq_model.opset_import if opset.domain == "com.microsoft"), None)
            self.assertIsNot(ms_opset, None)
 
    def verify_qop(self, per_channel, is_quant_type_int8):
        np.random.seed(1)
        model_fp32_path = str(Path(self._tmp_model_dir.name) / f"conv_relu_fp32.{per_channel}.onnx")
        model_int8_qop_path = str(Path(self._tmp_model_dir.name) / f"conv_relu_quant_qop.{per_channel}.onnx")
        data_reader = self.input_feeds(1, {"input": [1, 8, 33, 33]})
        self.construct_model_conv_relu(model_fp32_path, [1, 8, 33, 33], [16, 8, 3, 3], [1, 16, 31, 31])
 
        quantize_static(
            model_fp32_path,
            model_int8_qop_path,
            data_reader,
            quant_format=QuantFormat.QOperator,
            per_channel=per_channel,
            reduce_range=per_channel,
            activation_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
            weight_type=QuantType.QInt8 if is_quant_type_int8 else QuantType.QUInt8,
        )
        data_reader.rewind()
        qop_nodes = {"QLinearConv": 1, "QuantizeLinear": 1, "DequantizeLinear": 1}
        check_op_type_count(self, model_int8_qop_path, **qop_nodes)
        check_model_correctness(self, model_fp32_path, model_int8_qop_path, data_reader.get_next())
 
    def test_quantize_conv_without_bias(self):
        # only test cases per_channel=True and reduce_range=True to avoid saturation on avx2 and avx512 for weight type int8
        self.verify_qdq(True, QuantType.QInt8, QuantType.QInt8)  # per_channel:True
        self.verify_qop(True, True)  # per_channel:True, is_quant_type_int8:True
 
        self.verify_qdq(False, QuantType.QUInt8, QuantType.QUInt8)  # per_channel:False
        self.verify_qop(False, False)  # per_channel:False, is_quant_type_int8:False
 
        self.verify_qdq(True, QuantType.QUInt8, QuantType.QUInt8)  # per_channel:True
        self.verify_qop(True, False)  # per_channel:True, is_quant_type_int8:False
 
        # 16-bit QDQ via contrib ops
        self.verify_qdq(False, QuantType.QUInt16, QuantType.QUInt16, {"UseQDQContribOps": True})
        self.verify_qdq(False, QuantType.QInt16, QuantType.QInt16, {"UseQDQContribOps": True})
        self.verify_qdq(False, QuantType.QUInt16, QuantType.QUInt8, {"UseQDQContribOps": True})
        self.verify_qdq(False, QuantType.QInt16, QuantType.QInt8, {"UseQDQContribOps": True})
 
        self.verify_qdq(True, QuantType.QUInt16, QuantType.QUInt16, {"UseQDQContribOps": True})
        self.verify_qdq(True, QuantType.QInt16, QuantType.QInt16, {"UseQDQContribOps": True})
        self.verify_qdq(True, QuantType.QUInt16, QuantType.QUInt8, {"UseQDQContribOps": True})
        self.verify_qdq(True, QuantType.QInt16, QuantType.QInt8, {"UseQDQContribOps": True})
 
        # 4-bit QDQ - per tensor
        self.verify_qdq(False, QuantType.QInt16, QuantType.QInt4, opset=21, ir_version=10, atol=0.4)  # per-tensor
        self.verify_qdq(
            False, QuantType.QInt16, QuantType.QInt4, {"UseQDQContribOps": True}, opset=21, ir_version=10, atol=0.4
        )
 
        # 4-bit QDQ - per channel
        self.verify_qdq(True, QuantType.QInt16, QuantType.QInt4, opset=21, ir_version=10, atol=0.6)
        self.verify_qdq(
            True, QuantType.QInt16, QuantType.QInt4, {"UseQDQContribOps": True}, opset=21, ir_version=10, atol=0.6
        )
 
    def test_quantize_relu_conv(self):
        float_model_path = str(Path(self._tmp_model_dir.name) / "float_relu_convs_model.onnx")
        construct_relu_conv_model(float_model_path)
        data_reader = self.input_feeds(2, {"input": [1, 3, 1, 3]})
 
        qdq_model_path = str(Path(self._tmp_model_dir.name) / "qdq_relu_convs_model.onnx")
        quantize_static(
            float_model_path,
            qdq_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            per_channel=False,
            reduce_range=False,
            activation_type=QuantType.QInt8,
            weight_type=QuantType.QInt8,
        )
 
 
class TestQDQRemovableActivation(TestQDQFormat):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.quant.activation")
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def construct_model_clip_relu(self, output_model_path, input_shape, output_shape):
        #    (input)
        #      |
        #     Clip
        #      |
        #     Relu
        #      |
        #    (output)
        input_name = "input"
        output_name = "output"
        initializers = []
 
        # make Clip node
        clip_output_name = "clip_output"
        clip_node = create_clip_node(input_name, clip_output_name, "clip_node", initializers)
 
        # make Relu node
        relu_node = onnx.helper.make_node("Relu", [clip_output_name], [output_name], name="Relu")
 
        # make graph
        input_tensor = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, input_shape)
        output_tensor = helper.make_tensor_value_info(output_name, TensorProto.FLOAT, output_shape)
        graph_name = "QDQ_Test_Clip_Relu"
        graph = helper.make_graph(
            [clip_node, relu_node],
            graph_name,
            [input_tensor],
            [output_tensor],
            initializer=initializers,
        )
        model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
        model.ir_version = 7  # use stable onnx ir version
 
        onnx.save(model, output_model_path)
 
    def test_activation_only(self):
        float_model_path = str(Path(self._tmp_model_dir.name) / "float_relu_convs_model.onnx")
        self.construct_model_clip_relu(float_model_path, [1, 3, 1, 3], [1, 3, 1, 3])
        data_reader = self.input_feeds(2, {"input": [1, 3, 1, 3]})
 
        qdq_model_path = str(Path(self._tmp_model_dir.name) / "qdq_relu_convs_model.onnx")
        quantize_static(float_model_path, qdq_model_path, data_reader)
 
        qop_nodes = {"Clip": 1, "Relu": 1, "QuantizeLinear": 0, "DequantizeLinear": 0}
        check_op_type_count(self, qdq_model_path, **qop_nodes)
 
 
class TestQDQMixedPrecision(TestQDQFormat):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.qdq.mixed_prec_")
 
        # Note: swap with the commented line if you want to see the models in local test dir.
        cls._tmp_dir_path = cls._tmp_model_dir.name
        # cls._tmp_dir_path = "."
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def build_test_model_for_add_qdq_ops(
        self,
        num_consumers: int,
        is_graph_output: bool,
        float_type: onnx.TensorProto.DataType = onnx.TensorProto.FLOAT,
        op0_transpose: bool = False,
    ):
        """
        Builds a float32 model with a single producer node and a configurable number of consumer nodes.
        The tensor between the producer and consumers can be optionally made a graph output.
        op_0 can optionally be made a Transpose node to test sharing qparams across the input and output.
 
                           +-> op_0_out (optional graph output)
                           |
        input_0 --> op_0 --+-> op_1 --> output_0
                           |
                           +-> op_2 --> output_1
                           |
                           ...
                           |
                           +-> op_{n} --> output_{n-1}
        """
        shape = (1, 2, 3)
        shape_t = (1, 3, 2)
        input_0 = onnx.helper.make_tensor_value_info("input_0", float_type, shape)
        output_shape = shape if not op0_transpose else shape_t
 
        outputs = []
        for i in range(num_consumers):
            outputs.append(onnx.helper.make_tensor_value_info(f"output_{i}", float_type, output_shape))
 
        if is_graph_output:
            outputs.append(onnx.helper.make_tensor_value_info("op_0_out", float_type, output_shape))
 
        nodes = []
        if op0_transpose:
            nodes.append(onnx.helper.make_node("Transpose", ["input_0"], ["op_0_out"], perm=[0, 2, 1], name="op_0"))
        else:
            nodes.append(onnx.helper.make_node("Sigmoid", ["input_0"], ["op_0_out"], name="op_0"))
 
        for i in range(num_consumers):
            op_index = i + 1
            nodes.append(onnx.helper.make_node("Cos", ["op_0_out"], [f"output_{i}"], name=f"op_{op_index}"))
 
        graph = onnx.helper.make_graph(
            nodes,
            "test_add_qdq_ops_for_converted_activation",
            [input_0],
            outputs,
        )
        opset_imports = [
            onnx.helper.make_opsetid("", 18),
        ]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        return onnx.shape_inference.infer_shapes(model)
 
    def test_add_tensor_qdq_ops_case_1(self):
        """
        Tensor T is not a graph output; all consumers use the converted type
        <Producer> ---> Q1 ---> DQ1 ---> Q2 ---> DQ2 ---> <Consumers>
        """
        # Test configurations (qparam_sharing, float_type)
        subtest_configs = [
            (False, onnx.TensorProto.FLOAT, np.float32),
            (False, onnx.TensorProto.FLOAT16, np.float16),
            (True, onnx.TensorProto.FLOAT, np.float32),
            (True, onnx.TensorProto.FLOAT16, np.float16),
        ]
        for test_qparam_sharing, float_type, np_float_type in subtest_configs:
            with self.subTest(test_qparam_sharing=test_qparam_sharing, float_type=float_type):
                label = f"_share{test_qparam_sharing}_f{float_type}"
                float_model_path = os.path.join(self._tmp_dir_path, f"case_1{label}.onnx")
                qdq_model_path = os.path.join(self._tmp_dir_path, f"case_1{label}.qdq.onnx")
                float_model = self.build_test_model_for_add_qdq_ops(
                    2, False, float_type=float_type, op0_transpose=test_qparam_sharing
                )
                onnx.save_model(float_model, float_model_path)
 
                data_reader = self.input_feeds(3, {"input_0": (1, 2, 3)}, np_float_type)
 
                mixed_prec_overrides = {
                    "op_0_out": [
                        {
                            "quant_type": QuantType.QUInt8,
                            "convert": {"quant_type": QuantType.QUInt16, "recv_nodes": {"op_1", "op_2"}},
                        }
                    ],
                    "output_0": [{"quant_type": QuantType.QUInt16}],
                    "output_1": [{"quant_type": QuantType.QUInt16}],
                }
                quantize_static(
                    float_model_path,
                    qdq_model_path,
                    data_reader,
                    quant_format=QuantFormat.QDQ,
                    activation_type=QuantType.QUInt8,
                    op_types_to_quantize=[node.op_type for node in float_model.graph.node],
                    extra_options={
                        "TensorQuantOverrides": mixed_prec_overrides,
                        "ForceQuantizeNoInputCheck": test_qparam_sharing,  # To ensure Transpose is wrapped in DQ/Q
                    },
                )
 
                # Expect the following QDQ model:
                # input_0 --> Q --> DQ --> op_0 --> Q_8 --> DQ_8 --> Q_16 --> DQ_16 -+-> op_1 --> Q --> DQ --> output_0
                #                                                                    |
                #                                                                    +-> op_2 --> Q --> DQ --> output_1
                qdq_node_counts = {"QuantizeLinear": 5, "DequantizeLinear": 5}
                check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
                qdq_model = onnx.load_model(qdq_model_path)
                onnx.checker.check_model(qdq_model, True)
 
                initializers = {init.name: init for init in qdq_model.graph.initializer}
 
                # Check zero-point data types
                orig_zp_init = None
                if test_qparam_sharing:
                    # op_0_out_zero_point should not be in the model because the Transpose output is sharing
                    # qparams from the Transpose input.
                    self.assertNotIn("op_0_out_zero_point", initializers)
                    orig_zp_init = initializers["input_0_zero_point"]
                else:
                    orig_zp_init = initializers["op_0_out_zero_point"]
 
                self.assertEqual(orig_zp_init.data_type, onnx.TensorProto.UINT8)
                convert_zp_init = initializers["op_0_out_zero_point_convert"]
                self.assertEqual(convert_zp_init.data_type, onnx.TensorProto.UINT16)
                output_0_zp_init = initializers["output_0_zero_point"]
                self.assertEqual(output_0_zp_init.data_type, onnx.TensorProto.UINT16)
                output_1_zp_init = initializers["output_1_zero_point"]
                self.assertEqual(output_1_zp_init.data_type, onnx.TensorProto.UINT16)
 
                # Check scale data types
                orig_scale_init = None
                if test_qparam_sharing:
                    self.assertNotIn("op_0_out_scale", initializers)
                    orig_scale_init = initializers["input_0_scale"]
                else:
                    orig_scale_init = initializers["op_0_out_scale"]
 
                self.assertEqual(orig_scale_init.data_type, float_type)
                convert_scale_init = initializers["op_0_out_scale_convert"]
                self.assertEqual(convert_scale_init.data_type, float_type)
                output_0_scale_init = initializers["output_0_scale"]
                self.assertEqual(output_0_scale_init.data_type, float_type)
                output_1_scale_init = initializers["output_1_scale"]
                self.assertEqual(output_1_scale_init.data_type, float_type)
 
    def test_add_tensor_qdq_ops_case_2(self):
        """
        Tensor T is not a graph output; some consumers use the original type, others use the converted type
        <Producer> ---> Q1 -+-> DQ1 ---> <Consumers of original type>
                            |
                            +-> DQ1' ---> Q2 ---> DQ2 ---> <Consumers of converted type>
        """
        # Test configurations (qparam_sharing, float_type)
        subtest_configs = [
            (False, onnx.TensorProto.FLOAT, np.float32),
            (False, onnx.TensorProto.FLOAT16, np.float16),
            (True, onnx.TensorProto.FLOAT, np.float32),
            (True, onnx.TensorProto.FLOAT16, np.float16),
        ]
        for test_qparam_sharing, float_type, np_float_type in subtest_configs:
            with self.subTest(test_qparam_sharing=test_qparam_sharing, float_type=float_type):
                label = f"_share{test_qparam_sharing}_f{float_type}"
                float_model_path = os.path.join(self._tmp_dir_path, f"case_2{label}.onnx")
                qdq_model_path = os.path.join(self._tmp_dir_path, f"case_2{label}.qdq.onnx")
                float_model = self.build_test_model_for_add_qdq_ops(
                    4, False, float_type=float_type, op0_transpose=test_qparam_sharing
                )
                onnx.save_model(float_model, float_model_path)
 
                data_reader = self.input_feeds(3, {"input_0": (1, 2, 3)}, np_float_type)
 
                mixed_prec_overrides = {
                    "op_0_out": [
                        {
                            "quant_type": QuantType.QUInt8,
                            "convert": {"quant_type": QuantType.QUInt16, "recv_nodes": {"op_3", "op_4"}},
                        }
                    ],
                    "output_2": [{"quant_type": QuantType.QUInt16}],
                    "output_3": [{"quant_type": QuantType.QUInt16}],
                }
                quantize_static(
                    float_model_path,
                    qdq_model_path,
                    data_reader,
                    quant_format=QuantFormat.QDQ,
                    activation_type=QuantType.QUInt8,
                    op_types_to_quantize=[node.op_type for node in float_model.graph.node],
                    extra_options={
                        "TensorQuantOverrides": mixed_prec_overrides,
                        "ForceQuantizeNoInputCheck": test_qparam_sharing,  # To ensure Transpose is wrapped in DQ/Q
                    },
                )
 
                # Expect the following QDQ model:
                # input_0 --> Q --> DQ --> op_0 --> Q_8 -+-> DQ_8 -+-> op_1 --> Q --> DQ --> output_0
                #                                        |         |
                #                                        |         +-> op_2 --> Q --> DQ --> output_1
                #                                        |
                #                                        +-> DQ_8' --> Q_16 --> DQ_16 -+-> op_3 --> Q --> DQ --> output_2
                #                                                                      |
                #                                                                      +-> op_4 --> Q --> DQ --> output_3
                qdq_node_counts = {"QuantizeLinear": 7, "DequantizeLinear": 8}
                check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
                qdq_model = onnx.load_model(qdq_model_path)
                onnx.checker.check_model(qdq_model, True)
 
                initializers = {init.name: init for init in qdq_model.graph.initializer}
 
                # Check zero-point data types
                orig_zp_init = None
                if test_qparam_sharing:
                    # op_0_out_zero_point should not be in the model because the Transpose output is sharing
                    # qparams from the Transpose input.
                    self.assertNotIn("op_0_out_zero_point", initializers)
                    orig_zp_init = initializers["input_0_zero_point"]
                else:
                    orig_zp_init = initializers["op_0_out_zero_point"]
 
                self.assertEqual(orig_zp_init.data_type, onnx.TensorProto.UINT8)
                convert_zp_init = initializers["op_0_out_zero_point_convert"]
                self.assertEqual(convert_zp_init.data_type, onnx.TensorProto.UINT16)
                output_0_zp_init = initializers["output_0_zero_point"]
                self.assertEqual(output_0_zp_init.data_type, onnx.TensorProto.UINT8)
                output_1_zp_init = initializers["output_1_zero_point"]
                self.assertEqual(output_1_zp_init.data_type, onnx.TensorProto.UINT8)
                output_2_zp_init = initializers["output_2_zero_point"]
                self.assertEqual(output_2_zp_init.data_type, onnx.TensorProto.UINT16)
                output_3_zp_init = initializers["output_3_zero_point"]
                self.assertEqual(output_3_zp_init.data_type, onnx.TensorProto.UINT16)
 
                # Check scale data types
                orig_scale_init = None
                if test_qparam_sharing:
                    self.assertNotIn("op_0_out_scale", initializers)
                    orig_scale_init = initializers["input_0_scale"]
                else:
                    orig_scale_init = initializers["op_0_out_scale"]
 
                self.assertEqual(orig_scale_init.data_type, float_type)
                convert_scale_init = initializers["op_0_out_scale_convert"]
                self.assertEqual(convert_scale_init.data_type, float_type)
                output_0_scale_init = initializers["output_0_scale"]
                self.assertEqual(output_0_scale_init.data_type, float_type)
                output_1_scale_init = initializers["output_1_scale"]
                self.assertEqual(output_1_scale_init.data_type, float_type)
                output_2_scale_init = initializers["output_2_scale"]
                self.assertEqual(output_2_scale_init.data_type, float_type)
                output_3_scale_init = initializers["output_3_scale"]
                self.assertEqual(output_3_scale_init.data_type, float_type)
 
    def test_add_tensor_qdq_ops_case_3(self):
        """
        Tensor T is a graph output; all consumers use the converted type
        <Producer> ---> Q1 ---> DQ1 ---> Q2 ---> DQ2 -+-> <Consumers>
                                                      |
                                                      +-> <Graph output>
        """
        # Test configurations (qparam_sharing, float_type)
        subtest_configs = [
            (False, onnx.TensorProto.FLOAT, np.float32),
            (False, onnx.TensorProto.FLOAT16, np.float16),
            (True, onnx.TensorProto.FLOAT, np.float32),
            (True, onnx.TensorProto.FLOAT16, np.float16),
        ]
        for test_qparam_sharing, float_type, np_float_type in subtest_configs:
            with self.subTest(test_qparam_sharing=test_qparam_sharing, float_type=float_type):
                label = f"_share{test_qparam_sharing}_f{float_type}"
                float_model_path = os.path.join(self._tmp_dir_path, f"case_3{label}.onnx")
                qdq_model_path = os.path.join(self._tmp_dir_path, f"case_3{label}.qdq.onnx")
                float_model = self.build_test_model_for_add_qdq_ops(
                    2, True, float_type=float_type, op0_transpose=test_qparam_sharing
                )
                onnx.save_model(float_model, float_model_path)
 
                data_reader = self.input_feeds(3, {"input_0": (1, 2, 3)}, np_float_type)
 
                mixed_prec_overrides = {
                    "op_0_out": [
                        {
                            "quant_type": QuantType.QUInt8,
                            "convert": {"quant_type": QuantType.QUInt16, "recv_nodes": {"op_1", "op_2"}},
                        }
                    ],
                    "output_0": [{"quant_type": QuantType.QUInt16}],
                    "output_1": [{"quant_type": QuantType.QUInt16}],
                }
                quantize_static(
                    float_model_path,
                    qdq_model_path,
                    data_reader,
                    quant_format=QuantFormat.QDQ,
                    activation_type=QuantType.QUInt8,
                    op_types_to_quantize=[node.op_type for node in float_model.graph.node],
                    extra_options={
                        "TensorQuantOverrides": mixed_prec_overrides,
                        "ForceQuantizeNoInputCheck": test_qparam_sharing,  # To ensure Transpose is wrapped in DQ/Q
                    },
                )
 
                # Expect the following QDQ model:
                # input_0 --> Q --> DQ --> op_0 --> Q_8 --> DQ_8 --> Q_16 --> DQ_16 -+-> op_1 --> Q --> DQ --> output_0
                #                                                                    |
                #                                                                    +-> op_2 --> Q --> DQ --> output_1
                #                                                                    |
                #                                                                    +--> op_0_out (is graph output)
                qdq_node_counts = {"QuantizeLinear": 5, "DequantizeLinear": 5}
                check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
                qdq_model = onnx.load_model(qdq_model_path)
                onnx.checker.check_model(qdq_model, True)
 
                initializers = {init.name: init for init in qdq_model.graph.initializer}
                graph_outputs = {g_output.name: g_output for g_output in qdq_model.graph.output}
 
                # Check zero-point data types
                orig_zp_init = None
                if test_qparam_sharing:
                    # op_0_out_zero_point should not be in the model because the Transpose output is sharing
                    # qparams from the Transpose input.
                    self.assertNotIn("op_0_out_zero_point", initializers)
                    self.assertNotIn("op_0_out_scale", initializers)
                    orig_zp_init = initializers["input_0_zero_point"]
                else:
                    orig_zp_init = initializers["op_0_out_zero_point"]
 
                self.assertEqual(orig_zp_init.data_type, onnx.TensorProto.UINT8)
                convert_zp_init = initializers["op_0_out_zero_point_convert"]
                self.assertEqual(convert_zp_init.data_type, onnx.TensorProto.UINT16)
                output_0_zp_init = initializers["output_0_zero_point"]
                self.assertEqual(output_0_zp_init.data_type, onnx.TensorProto.UINT16)
                output_1_zp_init = initializers["output_1_zero_point"]
                self.assertEqual(output_1_zp_init.data_type, onnx.TensorProto.UINT16)
 
                # Check scale data types
                orig_scale_init = None
                if test_qparam_sharing:
                    self.assertNotIn("op_0_out_scale", initializers)
                    orig_scale_init = initializers["input_0_scale"]
                else:
                    orig_scale_init = initializers["op_0_out_scale"]
 
                self.assertEqual(orig_scale_init.data_type, float_type)
                convert_scale_init = initializers["op_0_out_scale_convert"]
                self.assertEqual(convert_scale_init.data_type, float_type)
                output_0_scale_init = initializers["output_0_scale"]
                self.assertEqual(output_0_scale_init.data_type, float_type)
                output_1_scale_init = initializers["output_1_scale"]
                self.assertEqual(output_1_scale_init.data_type, float_type)
 
                self.assertIn("op_0_out", graph_outputs)
 
    def test_add_tensor_qdq_ops_case_4(self):
        """
        Tensor T is a graph output; some consumers use the original type, others use the converted type
        <Producer> ---> Q1 -+-> DQ1 -+-> <Consumers of original type>
                            |        |
                            |        +-> <Graph output>
                            |
                            +-> DQ1' ---> Q2 ---> DQ2 ---> <Consumers of converted type>
        """
        # Test configurations (qparam_sharing, float_type)
        subtest_configs = [
            (False, onnx.TensorProto.FLOAT, np.float32),
            (False, onnx.TensorProto.FLOAT16, np.float16),
            (True, onnx.TensorProto.FLOAT, np.float32),
            (True, onnx.TensorProto.FLOAT16, np.float16),
        ]
        for test_qparam_sharing, float_type, np_float_type in subtest_configs:
            with self.subTest(test_qparam_sharing=test_qparam_sharing, float_type=float_type):
                label = f"_share{test_qparam_sharing}_f{float_type}"
                float_model_path = os.path.join(self._tmp_dir_path, f"case_4{label}.onnx")
                qdq_model_path = os.path.join(self._tmp_dir_path, f"case_4{label}.qdq.onnx")
                float_model = self.build_test_model_for_add_qdq_ops(
                    4, True, float_type=float_type, op0_transpose=test_qparam_sharing
                )
                onnx.save_model(float_model, float_model_path)
 
                data_reader = self.input_feeds(3, {"input_0": (1, 2, 3)}, np_float_type)
 
                mixed_prec_overrides = {
                    "op_0_out": [
                        {
                            "quant_type": QuantType.QUInt8,
                            "convert": {"quant_type": QuantType.QUInt16, "recv_nodes": {"op_3", "op_4"}},
                        }
                    ],
                    "output_2": [{"quant_type": QuantType.QUInt16}],
                    "output_3": [{"quant_type": QuantType.QUInt16}],
                }
                quantize_static(
                    float_model_path,
                    qdq_model_path,
                    data_reader,
                    quant_format=QuantFormat.QDQ,
                    activation_type=QuantType.QUInt8,
                    op_types_to_quantize=[node.op_type for node in float_model.graph.node],
                    extra_options={
                        "TensorQuantOverrides": mixed_prec_overrides,
                        "ForceQuantizeNoInputCheck": test_qparam_sharing,  # To ensure Transpose is wrapped in DQ/Q
                    },
                )
 
                # Expect the following QDQ model:
                # input_0 --> Q --> DQ --> op_0 --> Q_8 -+-> DQ_8 -+-> op_1 --> Q --> DQ --> output_0
                #                                        |         |
                #                                        |         +-> op_2 --> Q --> DQ --> output_1
                #                                        |         |
                #                                        |         +-> op_0_out (is graph output)
                #                                        |
                #                                        +-> DQ_8' --> Q_16 --> DQ_16 -+-> op_3 --> Q --> DQ --> output_2
                #                                                                      |
                #                                                                      +-> op_4 --> Q --> DQ --> output_3
                qdq_node_counts = {"QuantizeLinear": 7, "DequantizeLinear": 8}
                check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
                qdq_model = onnx.load_model(qdq_model_path)
                onnx.checker.check_model(qdq_model, True)
 
                initializers = {init.name: init for init in qdq_model.graph.initializer}
                graph_outputs = {g_output.name: g_output for g_output in qdq_model.graph.output}
 
                # Check zero-point data types
                orig_zp_init = None
                if test_qparam_sharing:
                    # op_0_out_zero_point should not be in the model because the Transpose output is sharing
                    # qparams from the Transpose input.
                    self.assertNotIn("op_0_out_zero_point", initializers)
                    orig_zp_init = initializers["input_0_zero_point"]
                else:
                    orig_zp_init = initializers["op_0_out_zero_point"]
 
                self.assertEqual(orig_zp_init.data_type, onnx.TensorProto.UINT8)
                convert_zp_init = initializers["op_0_out_zero_point_convert"]
                self.assertEqual(convert_zp_init.data_type, onnx.TensorProto.UINT16)
                output_0_zp_init = initializers["output_0_zero_point"]
                self.assertEqual(output_0_zp_init.data_type, onnx.TensorProto.UINT8)
                output_1_zp_init = initializers["output_1_zero_point"]
                self.assertEqual(output_1_zp_init.data_type, onnx.TensorProto.UINT8)
                output_2_zp_init = initializers["output_2_zero_point"]
                self.assertEqual(output_2_zp_init.data_type, onnx.TensorProto.UINT16)
                output_3_zp_init = initializers["output_3_zero_point"]
                self.assertEqual(output_3_zp_init.data_type, onnx.TensorProto.UINT16)
 
                # Check scale data types
                orig_scale_init = None
                if test_qparam_sharing:
                    self.assertNotIn("op_0_out_scale", initializers)
                    orig_scale_init = initializers["input_0_scale"]
                else:
                    orig_scale_init = initializers["op_0_out_scale"]
 
                self.assertEqual(orig_scale_init.data_type, float_type)
                convert_scale_init = initializers["op_0_out_scale_convert"]
                self.assertEqual(convert_scale_init.data_type, float_type)
                output_0_scale_init = initializers["output_0_scale"]
                self.assertEqual(output_0_scale_init.data_type, float_type)
                output_1_scale_init = initializers["output_1_scale"]
                self.assertEqual(output_1_scale_init.data_type, float_type)
                output_2_scale_init = initializers["output_2_scale"]
                self.assertEqual(output_2_scale_init.data_type, float_type)
                output_3_scale_init = initializers["output_3_scale"]
                self.assertEqual(output_3_scale_init.data_type, float_type)
 
                self.assertIn("op_0_out", graph_outputs)
 
    def test_add_tensor_qdq_ops_case_5(self):
        """
        Tensor T is a graph output without any consumers.
        <Producer> ---> Q1 ---> DQ1 ---> Q2 ---> DQ2 ---> <Graph output>
        """
        float_model_path = os.path.join(self._tmp_dir_path, "case_5.onnx")
        qdq_model_path = os.path.join(self._tmp_dir_path, "case_5.qdq.onnx")
 
        # Build model with input_0 -> op_0 -> op_0_out
        # The graph output has no consumers.
        float_model = self.build_test_model_for_add_qdq_ops(0, True)
        onnx.save_model(float_model, float_model_path)
 
        data_reader = self.input_feeds(3, {"input_0": (1, 2, 3)}, np.float32)
 
        mixed_prec_overrides = {
            "input_0": [{"quant_type": QuantType.QUInt16}],
            "op_0_out": [
                {
                    "quant_type": QuantType.QUInt16,
                    "convert": {"quant_type": QuantType.QUInt8},
                }
            ],
        }
        quantize_static(
            float_model_path,
            qdq_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt8,
            op_types_to_quantize=[node.op_type for node in float_model.graph.node],
            extra_options={
                "TensorQuantOverrides": mixed_prec_overrides,
            },
        )
 
        # Expect the following QDQ model:
        # input_0 --> Q_16 --> DQ_16 --> op_0 --> Q_16 --> DQ_16 --> Q_8 --> DQ_8 --> output_0
        qdq_node_counts = {"QuantizeLinear": 3, "DequantizeLinear": 3}
        check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
        qdq_model = onnx.load_model(qdq_model_path)
        onnx.checker.check_model(qdq_model, True)
 
        initializers = {init.name: init for init in qdq_model.graph.initializer}
 
        # Check zero-point data types
        orig_zp_init = initializers["op_0_out_zero_point"]
        self.assertEqual(orig_zp_init.data_type, onnx.TensorProto.UINT16)
        convert_zp_init = initializers["op_0_out_zero_point_convert"]
        self.assertEqual(convert_zp_init.data_type, onnx.TensorProto.UINT8)
 
    def build_test_model_1(self, shape):
        """
        Returns the following float32 model.
 
        input_0 --> op1 --> op3 --> op5 --> op6 --> output_0
                                     ^
                                     |
        input_1 --> op2 -+-> op4 ----+
                         |
                         +-> op7 --> output_1
                         |
                         +-> op8 --> output_2
        """
        input_0 = onnx.helper.make_tensor_value_info("input_0", onnx.TensorProto.FLOAT, shape)
        input_1 = onnx.helper.make_tensor_value_info("input_1", onnx.TensorProto.FLOAT, shape)
        output_0 = onnx.helper.make_tensor_value_info("output_0", onnx.TensorProto.FLOAT, shape)
        output_1 = onnx.helper.make_tensor_value_info("output_1", onnx.TensorProto.FLOAT, shape)
        output_2 = onnx.helper.make_tensor_value_info("output_2", onnx.TensorProto.FLOAT, shape)
 
        op1_node = onnx.helper.make_node("Sigmoid", ["input_0"], ["op1_out"], name="op1")
        op2_node = onnx.helper.make_node("Cos", ["input_1"], ["op2_out"], name="op2")
        op3_node = onnx.helper.make_node("Sin", ["op1_out"], ["op3_out"], name="op3")
        op4_node = onnx.helper.make_node("Tanh", ["op2_out"], ["op4_out"], name="op4")
        op5_node = onnx.helper.make_node("Mul", ["op3_out", "op4_out"], ["op5_out"], name="op5")
        op6_node = onnx.helper.make_node("Relu", ["op5_out"], ["output_0"], name="op6")
        op7_node = onnx.helper.make_node("Cos", ["op2_out"], ["output_1"], name="op7")
        op8_node = onnx.helper.make_node("Sigmoid", ["op2_out"], ["output_2"], name="op8")
 
        graph = onnx.helper.make_graph(
            [
                op1_node,
                op2_node,
                op3_node,
                op4_node,
                op5_node,
                op6_node,
                op7_node,
                op8_node,
            ],
            "mixed_prec_test",
            [input_0, input_1],
            [output_0, output_1, output_2],
        )
        opset_imports = [
            onnx.helper.make_opsetid("", 18),
        ]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        return onnx.shape_inference.infer_shapes(model)
 
    def test_16bit_subgraph(self):
        """
        Test correctness of a qdq model that uses a default 8-bit quantization type and contains
        a subgraph that uses 16-bit activations.
        """
        shape = (1, 2, 3)
        f32_model_path = os.path.join(self._tmp_dir_path, "model.onnx")
        qdq_model_path = os.path.join(self._tmp_dir_path, "model.qdq.onnx")
        qdq_mixed_model_path = os.path.join(self._tmp_dir_path, "model.mixed.qdq.onnx")
        f32_model = self.build_test_model_1(shape)
        onnx.save_model(f32_model, f32_model_path)
 
        data_reader = self.input_feeds(3, {"input_0": shape, "input_1": shape})
 
        # Create pure 8-bit qdq model
        quantize_static(
            f32_model_path,
            qdq_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt8,
            op_types_to_quantize=[node.op_type for node in f32_model.graph.node],
        )
 
        # Create mixed precision 8-bit/16-bit qdq model
        mixed_prec_overrides = {
            "op2_out": [
                {"quant_type": QuantType.QUInt8, "convert": {"quant_type": QuantType.QUInt16, "recv_nodes": {"op4"}}}
            ],
            "op3_out": [
                {"quant_type": QuantType.QUInt8, "convert": {"quant_type": QuantType.QUInt16, "recv_nodes": {"op5"}}}
            ],
            "op4_out": [{"quant_type": QuantType.QUInt16}],
            "op5_out": [{"quant_type": QuantType.QUInt16}],
            "output_0": [{"quant_type": QuantType.QUInt16}],
        }
        data_reader.rewind()
        quantize_static(
            f32_model_path,
            qdq_mixed_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt8,
            op_types_to_quantize=[node.op_type for node in f32_model.graph.node],
            extra_options={"TensorQuantOverrides": mixed_prec_overrides},
        )
 
        qop_nodes = {"Relu": 0, "QuantizeLinear": 11, "DequantizeLinear": 12}
        check_op_type_count(self, qdq_mixed_model_path, **qop_nodes)
        data_reader.rewind()
        check_model_correctness(self, f32_model_path, qdq_mixed_model_path, data_reader.get_next())
        data_reader.rewind()
        check_model_correctness(self, f32_model_path, qdq_model_path, data_reader.get_next())
 
 
class TestQDQ4bit(TestQDQFormat):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.qdq.4bit_")
 
        # Note: swap with the commented line if you want to see the models in local test dir.
        cls._tmp_dir_path = cls._tmp_model_dir.name
        # cls._tmp_dir_path = "."
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def build_conv_test_model(
        self,
        inp_shape: list[int],
        weight_data: np.ndarray,
        bias_data: np.ndarray,
    ):
        input_0 = onnx.helper.make_tensor_value_info("input_0", onnx.TensorProto.FLOAT, inp_shape)
        output_0 = onnx.helper.make_tensor_value_info("output_0", onnx.TensorProto.FLOAT, None)
        weight = onnx.numpy_helper.from_array(weight_data, "weight")
        bias = onnx.numpy_helper.from_array(bias_data, "bias")
 
        conv_node = onnx.helper.make_node("Conv", ["input_0", "weight", "bias"], ["output_0"], name="Conv0")
        graph = onnx.helper.make_graph(
            [conv_node],
            "Convf32",
            [input_0],
            [output_0],
            initializer=[weight, bias],
        )
        opset_imports = [onnx.helper.make_opsetid("", 21)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
 
        return onnx.shape_inference.infer_shapes(model)
 
    def test_int4_qdq_conv(self):
        """
        Test quantization of int4 conv weight.
        """
        float_model_path = os.path.join(self._tmp_dir_path, "conv_int4.f32.onnx")
        qdq_model_path = os.path.join(self._tmp_dir_path, "conv_int4.qdq.onnx")
 
        inp_shape = [1, 2, 100, 100]
        weight_shape = [2, 2, 20, 20]
 
        # range = 3.0, scale = 3/15, zp = 0
        weight_data = np.linspace(-1.5, 1.5, num=1600, dtype=np.float32).reshape(weight_shape)
        bias_data = np.array([-10.0, 10.0], dtype=np.float32)
        float_model = self.build_conv_test_model(inp_shape, weight_data, bias_data)
 
        onnx.checker.check_model(float_model, True)
        onnx.save_model(float_model, float_model_path)
 
        data_reader = self.input_feeds(3, {"input_0": inp_shape}, np.float32)
 
        tensor_quant_overrides = {
            "weight": [{"quant_type": QuantType.QInt4}],  # Quantize weights to INT4
        }
        quantize_static(
            float_model_path,
            qdq_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt16,
            weight_type=QuantType.QUInt8,
            op_types_to_quantize=[node.op_type for node in float_model.graph.node],
            extra_options={
                "TensorQuantOverrides": tensor_quant_overrides,
            },
        )
 
        qdq_node_counts = {"QuantizeLinear": 2, "DequantizeLinear": 4}
        check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
        qdq_model = onnx.load_model(qdq_model_path)
        onnx.checker.check_model(qdq_model, True)
 
        initializers = {init.name: init for init in qdq_model.graph.initializer}
 
        # Check the the weight's zero-point data type is INT4 and has expected value
        zp_val = 0
        weight_zp_init = initializers["weight_zero_point"]
        self.assertEqual(weight_zp_init.data_type, onnx.TensorProto.INT4)
        self.assertEqual(weight_zp_init.int32_data[0], zp_val)
 
        # Check for the expected scale value
        weight_scale_init = initializers["weight_scale"]
        scale_val = np.float32(3.0 / 15)
        self.assertEqual(weight_scale_init.data_type, onnx.TensorProto.FLOAT)
        self.assertEqual(weight_scale_init.float_data[0], scale_val)
 
        # Check that INT4 weights take up approximately 50% the size of INT8 weights.
        # Using protobuf's ByteSize() is not exact because it includes other fields in the proto message.
        unpacked_size = 1
        for dim in weight_shape:
            unpacked_size *= dim
 
        weight_quant_init = initializers["weight_quantized"]
        size_ratio = weight_quant_init.ByteSize() / unpacked_size
        self.assertLess(size_ratio, 0.55)
 
        # Check that the quantized weight values are correct.
        if weight_quant_init.HasField("raw_data"):
            float_data = weight_data.flatten().tolist()
            for index, float_val in enumerate(float_data):
                expected_int4_val = np.clip(np.float32(float_val / scale_val).round() + zp_val, -8, 7)
                int4_pair = _unpack_single_4bitx2(weight_quant_init.raw_data[index >> 1], True)
                int4_val = int4_pair[index & 0x1]
 
                self.assertEqual(np.float32(int4_val), expected_int4_val)
 
    def test_int4_qdq_per_channel_conv(self):
        """
        Test per-channel quantization of int4 conv weight.
        """
        float_model_path = os.path.join(self._tmp_dir_path, "conv_int4_per_chan.f32.onnx")
        qdq_model_path = os.path.join(self._tmp_dir_path, "conv_int4_per_chan.qdq.onnx")
 
        inp_shape = [1, 2, 100, 100]
        weight_shape = [2, 2, 20, 20]
 
        weight_data = np.linspace(-1.5, 1.5, num=1600, dtype=np.float32).reshape(weight_shape)
        bias_data = np.array([-10.0, 10.0], dtype=np.float32)
        float_model = self.build_conv_test_model(inp_shape, weight_data, bias_data)
 
        onnx.checker.check_model(float_model, True)
        onnx.save_model(float_model, float_model_path)
 
        data_reader = self.input_feeds(3, {"input_0": inp_shape}, np.float32)
 
        per_chan_axis = 0
        tensor_quant_overrides = {
            "weight": [{"quant_type": QuantType.QInt4, "axis": per_chan_axis}],  # Quantize weight to INT4 (per-channel)
        }
        quantize_static(
            float_model_path,
            qdq_model_path,
            data_reader,
            quant_format=QuantFormat.QDQ,
            activation_type=QuantType.QUInt16,
            weight_type=QuantType.QUInt8,
            op_types_to_quantize=[node.op_type for node in float_model.graph.node],
            extra_options={
                "TensorQuantOverrides": tensor_quant_overrides,
            },
        )
 
        qdq_node_counts = {"QuantizeLinear": 2, "DequantizeLinear": 4}
        check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
        qdq_model = onnx.load_model(qdq_model_path)
        onnx.checker.check_model(qdq_model, True)
 
        initializers = {init.name: init for init in qdq_model.graph.initializer}
 
        # Check that the weight's zero-point data type is INT4 and has 2 elems
        weight_zp_init = initializers["weight_zero_point"]
        self.assertEqual(weight_zp_init.data_type, onnx.TensorProto.INT4)
        self.assertEqual(weight_zp_init.dims[0], 2)
 
        # Check that the weight's scale data type is FLOAT and has 2 elems
        weight_scale_init = initializers["weight_scale"]
        self.assertEqual(weight_scale_init.data_type, onnx.TensorProto.FLOAT)
        self.assertEqual(weight_scale_init.dims[0], 2)
 
        # Check that INT4 weights take up approximately 50% the size of INT8 weights.
        # Using protobuf's ByteSize() is not exact because it includes other fields in the proto message.
        unpacked_size = 1
        for dim in weight_shape:
            unpacked_size *= dim
 
        weight_quant_init = initializers["weight_quantized"]
        size_ratio = weight_quant_init.ByteSize() / unpacked_size
        self.assertLess(size_ratio, 0.55)
 
    def test_json_serialization(self):
        td = TensorData(lowest=np.array([0.1], dtype=np.float32), highest=np.array([1.1], dtype=np.float32))
        new_calibrate_tensors_range = TensorsData(CalibrationMethod.MinMax, {"td": td})
        write_calibration_table(new_calibrate_tensors_range)
 
 
class TestAdjustWeightScaleForInt32Bias(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.qdq.adj_int32_bias_")
 
        # Note: swap with the commented line if you want to see the models in local test dir.
        cls._tmp_dir_path = cls._tmp_model_dir.name
        # cls._tmp_dir_path = "."
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def build_conv_test_model(
        self,
        input0_shape: list[int],
        weight_shape: list[int],
        onnx_float_type: onnx.TensorProto.DataType,
    ):
        np_float_type = onnx.helper.tensor_dtype_to_np_dtype(onnx_float_type)
        input_0 = onnx.helper.make_tensor_value_info("input_0", onnx_float_type, input0_shape)
        output_0 = onnx.helper.make_tensor_value_info("output_0", onnx_float_type, None)
 
        tiny_value = 1e-7 if np_float_type == np.float32 else 0.007782
        # weight_scale = 2*tiny_value / 255.0 = 7.84313725490196e-10
 
        weight_data = np.full(weight_shape, tiny_value, dtype=np_float_type)
        with np.nditer(weight_data, op_flags=["readwrite"]) as it:
            for i, x in enumerate(it):
                if i % 2 == 0:
                    x[...] = -x
 
        weight = onnx.numpy_helper.from_array(weight_data, "weight")
 
        # if we set input_scale to 0.05, then normally bias_scale would be
        # (input_scale * weight_scale) => (0.05 * 7.84314e-10) => 3.9215686274509805e-11
        #
        # If we quantize the f32 bias with this bias_scale, we get
        # [5.0/bias_scale, 4.0/bias_scale] = [127500000000, 102000000000]. These quantized bias values exceed the
        # range of int32.
        #
        # The ORT quantization tool will clamp these out-of-bounds values to int32::max(),
        # which can be very inaccurate.
        bias_shape = [weight_shape[0]]
        bias_data = np.ones(bias_shape, dtype=np_float_type)
        with np.nditer(bias_data, op_flags=["readwrite"]) as it:
            for i, x in enumerate(it):
                if i % 2 == 0:
                    x[...] = 5.0 if np_float_type == np.float32 else 1400
                else:
                    x[...] = -4.5 if np_float_type == np.float32 else -1200
 
        bias = onnx.numpy_helper.from_array(bias_data, "bias")
 
        conv_node = onnx.helper.make_node("Conv", ["input_0", "weight", "bias"], ["output_0"], name="Conv0")
        graph = onnx.helper.make_graph(
            [conv_node],
            "Convfloat",
            [input_0],
            [output_0],
            initializer=[weight, bias],
        )
        opset_imports = [onnx.helper.make_opsetid("", 21)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        model = onnx.shape_inference.infer_shapes(model)
        onnx.checker.check_model(model, True)
        return model
 
    def test_adjust_weight_scale_for_int32_bias(self):
        """
        Test adjustment of weight input's scale to ensure int32 bias's scale is not too small.
        """
        test_configs = [
            (onnx.TensorProto.FLOAT, True),
            (onnx.TensorProto.FLOAT, False),
            (onnx.TensorProto.FLOAT16, True),
            (onnx.TensorProto.FLOAT16, False),
        ]
 
        for float_type, per_channel in test_configs:
            with self.subTest(float_type=float_type, per_channel=per_channel):
                label = f"_f{float_type}_perchannel{per_channel}"
                float_model_path = os.path.join(self._tmp_dir_path, f"conv{label}.float.onnx")
                qdq_model_path = os.path.join(self._tmp_dir_path, f"conv{label}.qdq.onnx")
 
                # Create float model with a Conv that has tiny weight values.
                # This tiny weight scale would normally create a very small bias scale that will saturate
                # bias's int32 range. But, the qdq_quantizer adjusts the weight's scale to ensure this doesn't happen.
                input0_shape = [1, 2, 4, 4]
                weight_shape = [2, 2, 2, 2]
                float_model = self.build_conv_test_model(input0_shape, weight_shape, float_type)
                onnx.save_model(float_model, float_model_path)
 
                # Create a data reader
                np_float_type = onnx.helper.tensor_dtype_to_np_dtype(float_type)
                input0_rmin = 0.0
                input0_scale = 0.05 if float_type == onnx.TensorProto.FLOAT else 0.01
                input0_rmax = (input0_scale * 255.0) + input0_rmin
                input_data_list = [
                    {"input_0": np.full(input0_shape, input0_rmin, dtype=np_float_type)},
                    {"input_0": np.full(input0_shape, (input0_rmax - input0_rmin) / 2.0, dtype=np_float_type)},
                    {"input_0": np.full(input0_shape, input0_rmax, dtype=np_float_type)},
                ]
                data_reader = TestDataFeeds(input_data_list)
 
                # quantize model to QDQ
                quantize_static(
                    float_model_path,
                    qdq_model_path,
                    data_reader,
                    activation_type=QuantType.QUInt8,
                    weight_type=QuantType.QInt8,
                    per_channel=per_channel,
                )
 
                # Check correctness
                data_reader.rewind()
                check_model_correctness(self, float_model_path, qdq_model_path, data_reader.get_next())
 
    def build_model_convs_share_bias(
        self,
        input0_shape: list[int],
        weight_shape: list[int],
        onnx_float_type: onnx.TensorProto.DataType,
    ):
        np_float_type = onnx.helper.tensor_dtype_to_np_dtype(onnx_float_type)
        input_0 = onnx.helper.make_tensor_value_info("input_0", onnx_float_type, input0_shape)
        output_0 = onnx.helper.make_tensor_value_info("output_0", onnx_float_type, None)
        output_1 = onnx.helper.make_tensor_value_info("output_1", onnx_float_type, None)
 
        weight_0_data = np.ones(weight_shape, dtype=np_float_type)
        weight_0 = onnx.numpy_helper.from_array(weight_0_data, "weight_0")
 
        weight_1_data = np.full(weight_shape, 0.5, dtype=np_float_type)
        weight_1 = onnx.numpy_helper.from_array(weight_1_data, "weight_1")
 
        bias_shape = [weight_shape[0]]
        bias_data = np.ones(bias_shape, dtype=np_float_type)
        bias_shared = onnx.numpy_helper.from_array(bias_data, "bias_shared")
 
        conv_0_node = onnx.helper.make_node("Conv", ["input_0", "weight_0", "bias_shared"], ["output_0"], name="Conv0")
        conv_1_node = onnx.helper.make_node("Conv", ["input_0", "weight_1", "bias_shared"], ["output_1"], name="Conv1")
        graph = onnx.helper.make_graph(
            [conv_0_node, conv_1_node],
            "ConvWithSharedBiasToDup",
            [input_0],
            [output_0, output_1],
            initializer=[weight_0, weight_1, bias_shared],
        )
        opset_imports = [onnx.helper.make_opsetid("", 21)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        model = onnx.shape_inference.infer_shapes(model)
        onnx.checker.check_model(model, True)
        return model
 
    def test_dup_shared_bias(self):
        """
        Test duplicating a bias that is shared by two nodes that want to quantize their bias to int32.
        """
        float_model_path = os.path.join(self._tmp_dir_path, "convs_share_bias.float.onnx")
        qdq_model_path = os.path.join(self._tmp_dir_path, "convs_share_bias.qdq.onnx")
 
        # Create float model with a Convs that share a bias input. The QDQ quantizer should add a
        # duplicate bias so that each node has its own.
        input0_shape = [1, 2, 4, 4]
        weight_shape = [2, 2, 2, 2]
        float_model = self.build_model_convs_share_bias(input0_shape, weight_shape, onnx.TensorProto.FLOAT)
        onnx.save_model(float_model, float_model_path)
 
        # Create a data reader
        input0_rmin = 0.0
        input0_scale = 0.05
        input0_rmax = (input0_scale * 255.0) + input0_rmin
        input_data_list = [
            {"input_0": np.full(input0_shape, input0_rmin, dtype=np.float32)},
            {"input_0": np.full(input0_shape, (input0_rmax - input0_rmin) / 2.0, dtype=np.float32)},
            {"input_0": np.full(input0_shape, input0_rmax, dtype=np.float32)},
        ]
        data_reader = TestDataFeeds(input_data_list)
 
        # quantize model to QDQ
        quantize_static(
            float_model_path,
            qdq_model_path,
            data_reader,
            activation_type=QuantType.QUInt8,
            weight_type=QuantType.QInt8,
        )
 
        qdq_model = onnx.load_model(qdq_model_path)
        bias_names = set()
 
        for node in qdq_model.graph.node:
            if node.op_type == "DequantizeLinear" and node.input[0].startswith("bias_shared"):
                bias_names.add(node.input[0])
 
        self.assertEqual(len(bias_names), 2)
 
 
class TestQDQPrequantWeights(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.qdq.prequant_weight")
 
        # Note: swap with the commented line if you want to see the models in local test dir.
        cls._tmp_dir_path = cls._tmp_model_dir.name
        # cls._tmp_dir_path = "."
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def build_conv_model(
        self,
        inp_shape: list[int],
        weight_quant_data: np.ndarray,
        weight_scale_data: np.ndarray,
        weight_zp_data: np.ndarray,
        bias_data: np.ndarray,
        float_type: onnx.TensorProto.DataType = onnx.TensorProto.FLOAT,
    ):
        """
        Builds a model with a Conv that has a pre-quantized constant weight input.
        """
        input_0 = onnx.helper.make_tensor_value_info("input_0", float_type, inp_shape)
        output_0 = onnx.helper.make_tensor_value_info("output_0", float_type, None)
        weight_quant = onnx.numpy_helper.from_array(weight_quant_data, "weight_quant")
        weight_scale = onnx.numpy_helper.from_array(weight_scale_data, "weight_scale")
        weight_zp = onnx.numpy_helper.from_array(weight_zp_data, "weight_zp")
        bias = onnx.numpy_helper.from_array(bias_data, "bias")
 
        dq_node = onnx.helper.make_node(
            "DequantizeLinear", ["weight_quant", "weight_scale", "weight_zp"], ["weight_dequant"], name="DQ0"
        )
        conv_node = onnx.helper.make_node("Conv", ["input_0", "weight_dequant", "bias"], ["output_0"], name="Conv0")
        graph = onnx.helper.make_graph(
            [dq_node, conv_node],
            "ConvPreQuantWeight",
            [input_0],
            [output_0],
            initializer=[weight_quant, weight_scale, weight_zp, bias],
        )
        opset_imports = [onnx.helper.make_opsetid("", 21)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
 
        return onnx.shape_inference.infer_shapes(model)
 
    def build_conv_dynamic_weight_model(
        self,
        input_quant_data: np.ndarray,
        input_scale_data: np.ndarray,
        input_zp_data: np.ndarray,
        weight_shape: list[int],
        bias_data: np.ndarray,
        float_type: onnx.TensorProto.DataType = onnx.TensorProto.FLOAT,
    ):
        """
        Builds a model with a Conv that has a dynamic float weight input, but a constant
        pre-quantized input[0].
        """
        dyn_weight = onnx.helper.make_tensor_value_info("dyn_weight", float_type, weight_shape)
        output_0 = onnx.helper.make_tensor_value_info("output_0", float_type, None)
        input_quant = onnx.numpy_helper.from_array(input_quant_data, "input_quant")
        input_scale = onnx.numpy_helper.from_array(input_scale_data, "input_scale")
        input_zp = onnx.numpy_helper.from_array(input_zp_data, "input_zp")
        bias = onnx.numpy_helper.from_array(bias_data, "bias")
 
        dq_node = onnx.helper.make_node(
            "DequantizeLinear", ["input_quant", "input_scale", "input_zp"], ["input_dequant"], name="DQ0"
        )
        conv_node = onnx.helper.make_node("Conv", ["input_dequant", "dyn_weight", "bias"], ["output_0"], name="Conv0")
        graph = onnx.helper.make_graph(
            [dq_node, conv_node],
            "ConvPreQuantInput_DynamicWeight",
            [dyn_weight],
            [output_0],
            initializer=[input_quant, input_scale, input_zp, bias],
        )
        opset_imports = [onnx.helper.make_opsetid("", 21)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
 
        return onnx.shape_inference.infer_shapes(model)
 
    def test_quantize_with_prequantized_weights(self):
        """
        Test quantization of Conv with pre-quantized weights.
        """
        rng = np.random.default_rng(123)
        test_configs = [onnx.TensorProto.FLOAT, onnx.TensorProto.FLOAT16]
 
        for float_type in test_configs:
            with self.subTest(float_type=float_type):
                label = f"_{onnx.TensorProto.DataType.Name(float_type)}"
                float_model_path = os.path.join(self._tmp_dir_path, f"conv.f32.prequant_weight{label}.onnx")
                qdq_model_path = os.path.join(self._tmp_dir_path, f"conv.prequant_weight{label}.qdq.onnx")
 
                inp_shape = [1, 2, 100, 100]
                weight_shape = [2, 2, 20, 20]
                np_dtype = onnx.helper.tensor_dtype_to_np_dtype(float_type)
 
                # range = 2.0, scale = 2/254, zp = 0
                weight_scale_data = np.array(2 / 254, dtype=np_dtype)
                weight_zp_data = np.array(0, dtype=np.int8)
                weight_data = np.linspace(-1.0, 1.0, num=1600, dtype=np_dtype).reshape(weight_shape)
                weight_quant_data = quantize_nparray(
                    onnx.TensorProto.INT8, weight_data, weight_scale_data, weight_zp_data
                )
 
                bias_data = np.array([-10.0, 10.0], dtype=np_dtype)
                float_model = self.build_conv_model(
                    inp_shape, weight_quant_data, weight_scale_data, weight_zp_data, bias_data, float_type
                )
 
                onnx.checker.check_model(float_model, True)
                onnx.save_model(float_model, float_model_path)
 
                # Check that the input model only has a pre-quantized weight and save its scale/zero-point
                # to check that it doesn't change after quantization.
                float_node_counts = {"QuantizeLinear": 0, "DequantizeLinear": 1}
                check_op_type_count(self, float_model_path, **float_node_counts)
                conv_node_original = next((node for node in float_model.graph.node if node.op_type == "Conv"), None)
                self.assertNotEqual(conv_node_original, None)
 
                _, producers_original = get_tensor_consumers_and_producers(float_model)
                weight_dq_node_original = producers_original.get(conv_node_original.input[1], None)
                initializers_original = {initializer.name: initializer for initializer in float_model.graph.initializer}
                scale_name_original = weight_dq_node_original.input[1]
                scale_val_original = onnx.numpy_helper.to_array(initializers_original[scale_name_original])
                zp_name_original = weight_dq_node_original.input[2]
                zp_val_original = onnx.numpy_helper.to_array(initializers_original[zp_name_original])
 
                input_data_list = [
                    {"input_0": rng.uniform(-10.0, 10.0, inp_shape).astype(np_dtype)},
                ]
                data_reader = TestDataFeeds(input_data_list)
 
                quantize_static(
                    float_model_path,
                    qdq_model_path,
                    data_reader,
                    quant_format=QuantFormat.QDQ,
                    activation_type=QuantType.QUInt8,
                    weight_type=QuantType.QInt8,
                    op_types_to_quantize=["Conv"],
                )
 
                # The final model should have everything quantized
                qdq_node_counts = {"QuantizeLinear": 2, "DequantizeLinear": 4}
                check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
                # Check that the pre-quantized weight still has the same scale/zp after quantization
                qdq_model = onnx.load_model(qdq_model_path)
                conv_node = next((node for node in qdq_model.graph.node if node.op_type == "Conv"), None)
                self.assertNotEqual(conv_node, None)
 
                _, producers = get_tensor_consumers_and_producers(qdq_model)
                weight_dq_node = producers.get(conv_node.input[1], None)
                initializers = {initializer.name: initializer for initializer in qdq_model.graph.initializer}
 
                scale_name = weight_dq_node.input[1]
                self.assertEqual(scale_name, scale_name_original)
                scale_val = onnx.numpy_helper.to_array(initializers[scale_name])
                self.assertEqual(scale_val, scale_val_original)
 
                zp_name = weight_dq_node.input[2]
                self.assertEqual(zp_name, zp_name_original)
                zp_val = onnx.numpy_helper.to_array(initializers[zp_name])
                self.assertEqual(zp_val, zp_val_original)
 
    def test_quantize_with_prequantized_input(self):
        """
        Test quantization of Conv with pre-quantized input and dynamic weight.
        """
        rng = np.random.default_rng(123)
        test_configs = [
            (onnx.TensorProto.FLOAT, False),
            (onnx.TensorProto.FLOAT16, False),
            (onnx.TensorProto.FLOAT, True),
            (onnx.TensorProto.FLOAT16, True),
        ]
 
        for float_type, convert_weight_qtype in test_configs:
            with self.subTest(float_type=float_type):
                convert_label = "_convert_qtype" if convert_weight_qtype else ""
                label = f"_{onnx.TensorProto.DataType.Name(float_type)}{convert_label}"
                float_model_path = os.path.join(self._tmp_dir_path, f"conv.f32.prequant_input{label}.onnx")
                qdq_model_path = os.path.join(self._tmp_dir_path, f"conv.prequant_input{label}.qdq.onnx")
 
                inp_shape = [1, 2, 40, 40]
                weight_shape = [2, 2, 20, 20]
                np_dtype = onnx.helper.tensor_dtype_to_np_dtype(float_type)
 
                # range = 3.0, scale = 3/255, zp = 127
                input_scale_data = np.array(3 / 255, dtype=np_dtype)
                input_zp_data = np.array(127, dtype=np.uint8)
                input_data = np.linspace(-1.5, 1.5, num=3200, dtype=np_dtype).reshape(inp_shape)
                input_quant_data = quantize_nparray(onnx.TensorProto.UINT8, input_data, input_scale_data, input_zp_data)
 
                bias_data = np.array([-10.0, 10.0], dtype=np_dtype)
                float_model = self.build_conv_dynamic_weight_model(
                    input_quant_data, input_scale_data, input_zp_data, weight_shape, bias_data, float_type
                )
 
                onnx.checker.check_model(float_model, True)
                onnx.save_model(float_model, float_model_path)
 
                # Check that the input model only has a pre-quantized input and save its scale/zero-point
                # to check that it doesn't change after quantization.
                float_node_counts = {"QuantizeLinear": 0, "DequantizeLinear": 1}
                check_op_type_count(self, float_model_path, **float_node_counts)
                conv_node_original = next((node for node in float_model.graph.node if node.op_type == "Conv"), None)
                self.assertNotEqual(conv_node_original, None)
 
                _, producers_original = get_tensor_consumers_and_producers(float_model)
                input_dq_node_original = producers_original.get(conv_node_original.input[0], None)
                initializers_original = {initializer.name: initializer for initializer in float_model.graph.initializer}
                scale_name_original = input_dq_node_original.input[1]
                scale_val_original = onnx.numpy_helper.to_array(initializers_original[scale_name_original])
                zp_name_original = input_dq_node_original.input[2]
                zp_val_original = onnx.numpy_helper.to_array(initializers_original[zp_name_original])
 
                # Create data reader with random input calibration data.
                dyn_weight_data_list = [
                    {"dyn_weight": rng.uniform(-10.0, 10.0, weight_shape).astype(np_dtype)},
                ]
                data_reader = TestDataFeeds(dyn_weight_data_list)
 
                extra_options = {}
                if convert_weight_qtype:
                    # Test converting the dynamic weight's quantization type, which results in
                    # dyn_weight -> Q(u16) -> DQ(f32) -> Q(u8) -> DQ(f32) -> Conv
                    extra_options["TensorQuantOverrides"] = {
                        "dyn_weight": [{"quant_type": QuantType.QUInt16, "convert": {"quant_type": QuantType.QUInt8}}],
                    }
 
                quantize_static(
                    float_model_path,
                    qdq_model_path,
                    data_reader,
                    quant_format=QuantFormat.QDQ,
                    activation_type=QuantType.QUInt8,
                    weight_type=QuantType.QInt8,
                    op_types_to_quantize=["Conv"],
                    extra_options=extra_options,
                )
 
                # The final model should have everything quantized
                qdq_node_counts = {"QuantizeLinear": 2, "DequantizeLinear": 4}
                if convert_weight_qtype:
                    qdq_node_counts["QuantizeLinear"] += 1
                    qdq_node_counts["DequantizeLinear"] += 1
 
                check_op_type_count(self, qdq_model_path, **qdq_node_counts)
 
                # Check that the pre-quantized input still has the same scale/zp after quantization
                qdq_model = onnx.load_model(qdq_model_path)
                conv_node = next((node for node in qdq_model.graph.node if node.op_type == "Conv"), None)
                self.assertNotEqual(conv_node, None)
 
                _, producers = get_tensor_consumers_and_producers(qdq_model)
                input_dq_node = producers.get(conv_node.input[0], None)
                initializers = {initializer.name: initializer for initializer in qdq_model.graph.initializer}
 
                scale_name = input_dq_node.input[1]
                self.assertEqual(scale_name, scale_name_original)
                scale_val = onnx.numpy_helper.to_array(initializers[scale_name])
                self.assertEqual(scale_val, scale_val_original)
 
                zp_name = input_dq_node.input[2]
                self.assertEqual(zp_name, zp_name_original)
                zp_val = onnx.numpy_helper.to_array(initializers[zp_name])
                self.assertEqual(zp_val, zp_val_original)
 
 
class TestConvBiasScaleValidation(unittest.TestCase):
    """Tests that QDQ Conv -> QLinearConv fusion is skipped when bias scale does not match
    input_scale * weight_scale, as required by the ONNX QLinearConv specification."""
 
    @classmethod
    def setUpClass(cls):
        cls._tmp_model_dir = tempfile.TemporaryDirectory(prefix="ort.qdq.bias_scale_validation_")
        # Note: swap with the commented line if you want to see the models in local test dir.
        cls._tmp_dir_path = cls._tmp_model_dir.name
        # cls._tmp_dir_path = "."
 
    @classmethod
    def tearDownClass(cls):
        cls._tmp_model_dir.cleanup()
 
    def build_qdq_conv_model(
        self,
        inp_shape: list[int],
        weight_shape: list[int],
        x_scale: float,
        w_scale: float,
        b_scale: float,
        x_zp: int = 128,
        w_zp: int = 0,
        b_zp_val: int = 0,
    ) -> onnx.ModelProto:
        """Builds a QDQ Conv model (DQ->Conv->Q) with the given quantization scales.
 
        The bias is encoded as int32 with the provided b_scale. The model is
        non-conformant — and fusion must be skipped — in two distinct cases:
 
        - ``b_scale != x_scale * w_scale``: violates the ONNX QLinearConv bias-scale
          constraint (bias_scale must equal input_scale * weight_scale).
        - ``b_zp_val != 0``: QLinearConv has no bias_zero_point input, so a nonzero
          b_zp would produce silently shifted outputs if fusion were allowed.
        """
        num_out_channels = weight_shape[0]
        np_x_scale = np.float32(x_scale)
        np_w_scale = np.float32(w_scale)
        np_b_scale = np.float32(b_scale)
 
        # --- Quantized input (graph input: uint8) ---
        input_q = onnx.helper.make_tensor_value_info("input_q", onnx.TensorProto.UINT8, inp_shape)
 
        # --- Weight: random int8 constant ---
        rng = np.random.default_rng(42)
        weight_quant_data = rng.integers(-5, 6, size=weight_shape, dtype=np.int8)
        weight_quant = onnx.numpy_helper.from_array(weight_quant_data, "weight_q")
 
        # --- Scales / zero-points as scalar constants ---
        x_scale_tensor = onnx.numpy_helper.from_array(np.array(np_x_scale, dtype=np.float32), "x_scale")
        x_zp_tensor = onnx.numpy_helper.from_array(np.array(x_zp, dtype=np.uint8), "x_zp")
        w_scale_tensor = onnx.numpy_helper.from_array(np.array(np_w_scale, dtype=np.float32), "w_scale")
        w_zp_tensor = onnx.numpy_helper.from_array(np.array(w_zp, dtype=np.int8), "w_zp")
        b_scale_tensor = onnx.numpy_helper.from_array(np.array(np_b_scale, dtype=np.float32), "b_scale")
        b_zp_tensor = onnx.numpy_helper.from_array(np.array(b_zp_val, dtype=np.int32), "b_zp")
 
        # Bias as int32 (quantized with b_scale)
        bias_float = np.ones(num_out_channels, dtype=np.float32)
        bias_q_data = np.round(bias_float / np_b_scale).astype(np.int32)
        bias_q = onnx.numpy_helper.from_array(bias_q_data, "bias_q")
 
        # Output scale/zp for Q node
        out_scale_val = np.float32(x_scale)
        out_zp_val = np.uint8(128)
        out_scale_tensor = onnx.numpy_helper.from_array(np.array(out_scale_val, dtype=np.float32), "out_scale")
        out_zp_tensor = onnx.numpy_helper.from_array(np.array(out_zp_val, dtype=np.uint8), "out_zp")
 
        # Nodes: DQ(input) -> | -> Conv -> Q(output)
        #        DQ(weight) -/
        #        DQ(bias)  -/
        dq_input = onnx.helper.make_node(
            "DequantizeLinear", ["input_q", "x_scale", "x_zp"], ["input_f"], name="DQ_input"
        )
        dq_weight = onnx.helper.make_node(
            "DequantizeLinear", ["weight_q", "w_scale", "w_zp"], ["weight_f"], name="DQ_weight"
        )
        dq_bias = onnx.helper.make_node("DequantizeLinear", ["bias_q", "b_scale", "b_zp"], ["bias_f"], name="DQ_bias")
        conv_node = onnx.helper.make_node("Conv", ["input_f", "weight_f", "bias_f"], ["conv_out"], name="Conv0")
        q_output = onnx.helper.make_node(
            "QuantizeLinear", ["conv_out", "out_scale", "out_zp"], ["output_q"], name="Q_output"
        )
 
        output_q = onnx.helper.make_tensor_value_info("output_q", onnx.TensorProto.UINT8, None)
 
        graph = onnx.helper.make_graph(
            [dq_input, dq_weight, dq_bias, conv_node, q_output],
            "QDQConvBiasScaleTest",
            [input_q],
            [output_q],
            initializer=[
                weight_quant,
                x_scale_tensor,
                x_zp_tensor,
                w_scale_tensor,
                w_zp_tensor,
                b_scale_tensor,
                b_zp_tensor,
                bias_q,
                out_scale_tensor,
                out_zp_tensor,
            ],
        )
        opset_imports = [onnx.helper.make_opsetid("", 21)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        model = onnx.shape_inference.infer_shapes(model)
        return model
 
    def _run_model(self, model_path: str, inputs: dict, optimize: bool, optimized_save_path: str | None = None) -> list:
        """Run model with the given optimization level and return outputs.
 
        If ``optimized_save_path`` is provided and ``optimize`` is True, the
        optimized graph is saved there so callers can inspect the resulting
        op set (e.g., assert whether QLinearConv fusion fired).
        """
        sess_opts = ort.SessionOptions()
        if optimize:
            sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
            if optimized_save_path is not None:
                sess_opts.optimized_model_filepath = optimized_save_path
        else:
            sess_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
        sess = ort.InferenceSession(model_path, sess_options=sess_opts, providers=["CPUExecutionProvider"])
        return sess.run(None, inputs)
 
    @staticmethod
    def _op_counts(model_path: str) -> dict[str, int]:
        m = onnx.load(model_path)
        counts: dict[str, int] = {}
        for n in m.graph.node:
            counts[n.op_type] = counts.get(n.op_type, 0) + 1
        return counts
 
    def test_mismatched_bias_scale_skips_fusion(self):
        """When bias_scale != input_scale * weight_scale, fusion must be skipped.
 
        The outputs of the optimized and unoptimized sessions should match, proving
        that no silent numerical corruption occurred.
        """
        inp_shape = [1, 1, 4, 4]
        weight_shape = [1, 1, 1, 1]
 
        x_scale = 0.05
        w_scale = 0.02
        # Intentionally wrong bias scale: 2x the correct value
        correct_b_scale = x_scale * w_scale
        wrong_b_scale = 2.0 * correct_b_scale
 
        model = self.build_qdq_conv_model(inp_shape, weight_shape, x_scale, w_scale, wrong_b_scale)
        model_path = os.path.join(self._tmp_dir_path, "conv_mismatched_bias_scale.qdq.onnx")
        onnx.save_model(model, model_path)
 
        # Build a representative input
        rng = np.random.default_rng(0)
        input_data = rng.integers(100, 200, size=inp_shape, dtype=np.uint8)
        inputs = {"input_q": input_data}
 
        optimized_path = os.path.join(self._tmp_dir_path, "conv_mismatched_bias_scale.opt.onnx")
        out_optimized = self._run_model(model_path, inputs, optimize=True, optimized_save_path=optimized_path)
        out_unoptimized = self._run_model(model_path, inputs, optimize=False)
 
        # Both should produce the same uint8 output (fusion was skipped or fallback path is correct).
        np.testing.assert_array_equal(
            out_optimized[0],
            out_unoptimized[0],
            err_msg="Mismatched bias scale: optimized and unoptimized outputs differ, "
            "indicating silent numerical corruption from incorrect fusion.",
        )
 
        # Direct check: fusion must NOT have produced a QLinearConv when bias scale is wrong.
        op_counts = self._op_counts(optimized_path)
        self.assertEqual(
            op_counts.get("QLinearConv", 0),
            0,
            f"Expected no QLinearConv when bias scale is mismatched, got: {op_counts}",
        )
 
    def test_matching_bias_scale_allows_fusion(self):
        """When bias_scale == input_scale * weight_scale, fusion should be allowed.
 
        Both optimized and unoptimized sessions must produce identical outputs.
        """
        inp_shape = [1, 1, 4, 4]
        weight_shape = [1, 1, 1, 1]
 
        x_scale = 0.05
        w_scale = 0.02
        correct_b_scale = x_scale * w_scale  # exactly matching
 
        model = self.build_qdq_conv_model(inp_shape, weight_shape, x_scale, w_scale, correct_b_scale)
        model_path = os.path.join(self._tmp_dir_path, "conv_matching_bias_scale.qdq.onnx")
        onnx.save_model(model, model_path)
 
        rng = np.random.default_rng(0)
        input_data = rng.integers(100, 200, size=inp_shape, dtype=np.uint8)
        inputs = {"input_q": input_data}
 
        optimized_path = os.path.join(self._tmp_dir_path, "conv_matching_bias_scale.opt.onnx")
        out_optimized = self._run_model(model_path, inputs, optimize=True, optimized_save_path=optimized_path)
        out_unoptimized = self._run_model(model_path, inputs, optimize=False)
 
        np.testing.assert_array_equal(
            out_optimized[0],
            out_unoptimized[0],
            err_msg="Matching bias scale: optimized and unoptimized outputs differ.",
        )
 
        # Direct check: fusion DID produce a QLinearConv (and removed the QDQ/Conv group).
        op_counts = self._op_counts(optimized_path)
        self.assertGreaterEqual(
            op_counts.get("QLinearConv", 0),
            1,
            f"Expected QLinearConv after fusion when bias scale matches, got: {op_counts}",
        )
        self.assertEqual(
            op_counts.get("Conv", 0),
            0,
            f"Expected the float Conv to be consumed by QLinearConv fusion, got: {op_counts}",
        )
 
    def test_nonzero_bias_zp_skips_fusion(self):
        """When bias_zp != 0 (even if bias_scale is correct), fusion must be skipped.
 
        QLinearConv has no bias_zero_point input, so a nonzero b_zp would produce silently
        shifted outputs if fusion were allowed. The optimizer must conservatively reject it.
        """
        inp_shape = [1, 1, 4, 4]
        weight_shape = [1, 1, 1, 1]
 
        x_scale = 0.05
        w_scale = 0.02
        correct_b_scale = x_scale * w_scale  # scale is correct — only zp is wrong
        # Any nonzero value triggers the check; 1 is the minimal representable nonzero int32.
        nonzero_b_zp = 1
 
        model = self.build_qdq_conv_model(
            inp_shape, weight_shape, x_scale, w_scale, correct_b_scale, b_zp_val=nonzero_b_zp
        )
        model_path = os.path.join(self._tmp_dir_path, "conv_nonzero_bias_zp.qdq.onnx")
        onnx.save_model(model, model_path)
 
        rng = np.random.default_rng(0)
        input_data = rng.integers(100, 200, size=inp_shape, dtype=np.uint8)
        inputs = {"input_q": input_data}
 
        optimized_path = os.path.join(self._tmp_dir_path, "conv_nonzero_bias_zp.opt.onnx")
        out_optimized = self._run_model(model_path, inputs, optimize=True, optimized_save_path=optimized_path)
        out_unoptimized = self._run_model(model_path, inputs, optimize=False)
 
        # --- Primary structural check ---
        # This is the definitive guard: fusion to QLinearConv must be rejected when the
        # bias zero-point is nonzero. ConvMoves discards the bias zero-point during the
        # rewrite (QLinearConv has no bias_zp input). A nonzero b_zp would otherwise
        # produce silently shifted outputs.
        op_counts = self._op_counts(optimized_path)
        self.assertEqual(
            op_counts.get("QLinearConv", 0),
            0,
            "Fusion to QLinearConv must be rejected when bias zero-point is nonzero, "
            "because ConvMoves discards the bias zero-point during the rewrite "
            "(QLinearConv has no bias_zp input). A nonzero b_zp would otherwise "
            f"produce silently shifted outputs. Op counts: {op_counts}",
        )
 
        # --- Secondary defense-in-depth: numeric regression guard ---
        # Requires the C++ fix to be present. Intentionally weaker than the structural
        # check above: for small b_zp and b_scale the numeric divergence may not survive
        # uint8 requantization, so this assertion can pass even when fusion incorrectly
        # fires on certain inputs.
        np.testing.assert_array_equal(
            out_optimized[0],
            out_unoptimized[0],
            err_msg="Nonzero bias zp: optimized and unoptimized outputs differ, "
            "indicating silent numerical corruption from incorrect fusion.",
        )
 
    def test_per_channel_nonfinite_w_scale_skips_fusion(self):
        """Per-channel w_scale containing a non-finite value must prevent fusion.
 
        When w_scale is a 1-D tensor (one value per output channel) and any
        element is NaN or Inf, the bias-scale validator must return false and
        fusion to QLinearConv must be skipped.
        """
        inp_shape = [1, 4, 4, 4]
        weight_shape = [4, 4, 1, 1]
        num_out_channels = weight_shape[0]
 
        x_scale = np.float32(0.05)
        # Per-channel w_scale: channels 0-2 are valid, channel 3 is non-finite (NaN).
        w_scale_arr = np.array([0.02, 0.03, 0.04, float("nan")], dtype=np.float32)
        # b_scale matches x_scale * w_scale for the finite channels (doesn't matter
        # for the non-finite channel since we expect early rejection).
        b_scale_arr = (x_scale * w_scale_arr).astype(np.float32)
 
        # Build scales / zero-points as initializer tensors.
        x_scale_tensor = onnx.numpy_helper.from_array(np.array(x_scale, dtype=np.float32), "x_scale")
        x_zp_tensor = onnx.numpy_helper.from_array(np.array(128, dtype=np.uint8), "x_zp")
        w_scale_tensor = onnx.numpy_helper.from_array(w_scale_arr, "w_scale")
        w_zp_tensor = onnx.numpy_helper.from_array(np.zeros(num_out_channels, dtype=np.int8), "w_zp")
        b_scale_tensor = onnx.numpy_helper.from_array(b_scale_arr, "b_scale")
        b_zp_tensor = onnx.numpy_helper.from_array(np.zeros(num_out_channels, dtype=np.int32), "b_zp")
        out_scale_tensor = onnx.numpy_helper.from_array(np.array(x_scale, dtype=np.float32), "out_scale")
        out_zp_tensor = onnx.numpy_helper.from_array(np.array(128, dtype=np.uint8), "out_zp")
 
        # Random int8 weights (shape [C_out, C_in/group, kH, kW]).
        rng = np.random.default_rng(7)
        weight_quant_data = rng.integers(-5, 6, size=weight_shape, dtype=np.int8)
        weight_quant = onnx.numpy_helper.from_array(weight_quant_data, "weight_q")
 
        # Bias as int32 (per-channel, one element per output channel).
        bias_float = np.ones(num_out_channels, dtype=np.float32)
        # Use channel-0 b_scale for encoding (non-finite channel is still skipped).
        bias_q_data = np.round(bias_float / np.float32(0.001)).astype(np.int32)
        bias_q = onnx.numpy_helper.from_array(bias_q_data, "bias_q")
 
        input_q = onnx.helper.make_tensor_value_info("input_q", onnx.TensorProto.UINT8, inp_shape)
        output_q = onnx.helper.make_tensor_value_info("output_q", onnx.TensorProto.UINT8, None)
 
        dq_input = onnx.helper.make_node(
            "DequantizeLinear", ["input_q", "x_scale", "x_zp"], ["input_f"], name="DQ_input"
        )
        dq_weight = onnx.helper.make_node(
            "DequantizeLinear", ["weight_q", "w_scale", "w_zp"], ["weight_f"], name="DQ_weight", axis=0
        )
        dq_bias = onnx.helper.make_node(
            "DequantizeLinear", ["bias_q", "b_scale", "b_zp"], ["bias_f"], name="DQ_bias", axis=0
        )
        conv_node = onnx.helper.make_node("Conv", ["input_f", "weight_f", "bias_f"], ["conv_out"], name="Conv0")
        q_output = onnx.helper.make_node(
            "QuantizeLinear", ["conv_out", "out_scale", "out_zp"], ["output_q"], name="Q_output"
        )
 
        graph = onnx.helper.make_graph(
            [dq_input, dq_weight, dq_bias, conv_node, q_output],
            "QDQConvPerChannelNonFiniteTest",
            [input_q],
            [output_q],
            initializer=[
                weight_quant,
                x_scale_tensor,
                x_zp_tensor,
                w_scale_tensor,
                w_zp_tensor,
                b_scale_tensor,
                b_zp_tensor,
                bias_q,
                out_scale_tensor,
                out_zp_tensor,
            ],
        )
        opset_imports = [onnx.helper.make_opsetid("", 21)]
        model = onnx.helper.make_model(graph, opset_imports=opset_imports)
        model = onnx.shape_inference.infer_shapes(model)
 
        model_path = os.path.join(self._tmp_dir_path, "conv_per_channel_nonfinite_w_scale.qdq.onnx")
        onnx.save_model(model, model_path)
 
        rng2 = np.random.default_rng(0)
        input_data = rng2.integers(100, 200, size=inp_shape, dtype=np.uint8)
        inputs = {"input_q": input_data}
 
        optimized_path = os.path.join(self._tmp_dir_path, "conv_per_channel_nonfinite_w_scale.opt.onnx")
        self._run_model(model_path, inputs, optimize=True, optimized_save_path=optimized_path)
 
        # Fusion must be rejected: a non-finite w_scale element means the
        # bias-scale validator must return false and QLinearConv must not appear.
        op_counts = self._op_counts(optimized_path)
        self.assertEqual(
            op_counts.get("QLinearConv", 0),
            0,
            f"Expected no QLinearConv when per-channel w_scale contains NaN, got: {op_counts}",
        )
 
 
if __name__ == "__main__":
    unittest.main()