Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
/*++
 
Copyright (c) Microsoft Corporation. All rights reserved.
 
Licensed under the MIT License.
 
Module Name:
 
    q4_dq.cpp
 
Abstract:
 
    This module contains the data structures and implementations
    for blocked int4 quantization and dequantization.
 
    Int4 block quantization is used to compress weight tensors of large
    language models.
 
--*/
 
#include "q4common.h"
 
template<typename T>
constexpr
size_t
BlkQ4BufSize(size_t N, size_t K)
{
    const size_t KBlocks = MlasDivRoundup(K, T::BlkLen);
    return N * KBlocks * T::BlobSize;
}
 
size_t
MLASCALL
MlasQ4GemmPackBSize(MLAS_BLK_QUANT_TYPE QType, size_t N, size_t K)
{
    if (GetMlasPlatform().FpQ4GemmDispatch == nullptr) {
        return 0;
    }
 
    switch (QType) {
        case BlkQ4Sym:
            return BlkQ4BufSize<MLAS_Q4TYPE_BLK0>(N, K);
        case BlkQ4Sym64:
            return BlkQ4BufSize<MLAS_Q4TYPE_BLK2>(N, K);
        case BlkQ4Sym128:
            return BlkQ4BufSize<MLAS_Q4TYPE_BLK4>(N, K);
        default:
            return BlkQ4BufSize<MLAS_Q4TYPE_BLK1>(N, K);
    }
}
 
 
template<typename T>
MLAS_FORCEINLINE
void
MlasQ4GemmPackBImpl(void* PackedBuf, const float* FpData, size_t N, size_t K, size_t ldb)
{
    auto* dst_ptr = reinterpret_cast<uint8_t*>(PackedBuf);
 
    for (size_t n = 0; n < N; n ++) {
        const float* src = FpData; // starting from top of the column
 
        for (size_t k = 0; k < K; k += T::BlkLen) {
            size_t klen = std::min(size_t(T::BlkLen), K - k);
            float amax = 0.0f; // abs(max)
            float max = 0.0f;
 
            for (size_t l = 0; l < klen; l++) {
                const float v = src[ldb * l];
                if (amax < fabsf(v)) {
                    amax = fabsf(v);
                    max = v;
                }
            }
 
            const float scale = max / (-8);
            const float reciprocal_scale = scale ? 1.0f / scale : 0.0f;
            MlasQ4BlkScale<T>(dst_ptr) = scale;
            uint8_t* data = MlasQ4BlkData<T>(dst_ptr);
 
            for (size_t kk = 0; kk < klen; kk += 32) {
                size_t kklen = std::min((size_t)32, klen - kk);
                for (size_t l = 0; l < 16; l++) {
                    const float v0 = l < kklen ? src[ldb * (kk + l)] * reciprocal_scale : 0;
                    const uint8_t vi0 = (uint8_t)std::min(15.0f, std::max(0.0f, v0 + 8.5f));
 
                    const size_t l1 = l + 16;
                    const float v1 = (l1 < kklen) ? src[ldb * (kk + l1)] * reciprocal_scale : 0;
                    const uint8_t vi1 = (uint8_t)std::min(15.0f, std::max(0.0f, v1 + 8.5f));
 
                    data[l] = vi0 | (vi1 << 4);
                }
                data += 16;
            }
 
            // Move to next block of values in this column
            dst_ptr += T::BlobSize;
            src += ldb * klen;
        }
 
        FpData++; // move to next column
    }
}
 
template<>
MLAS_FORCEINLINE
void
MlasQ4GemmPackBImpl<MLAS_Q4TYPE_BLK1>(
    void* PackedBuf, const float* FpData, size_t N, size_t K, size_t ldb)
{
    auto* dst_ptr = reinterpret_cast<uint8_t*>(PackedBuf);
 
    for (size_t n = 0; n < N; n++) {
        const float* src = FpData; // starting from top of the column
 
        for (size_t k = 0; k < K; k += MLAS_Q4TYPE_BLK1::BlkLen) {
            size_t klen = std::min(MLAS_Q4TYPE_BLK1::BlkLen, K - k);
            float min = std::numeric_limits<float>::max();
            float max = -min;
 
            for (size_t l = 0; l < klen; l++) {
                const float v = src[ldb * l];
                if (v < min) min = v;
                if (v > max) max = v;
            }
            min = std::min(min, 0.0f);
            max = std::max(max, 0.0f);
 
            const float scale = (max - min) / ((1 << 4) - 1);
            const float reciprocal_scale = scale ? 1.0f / scale : 0.0f;
            float zero_point_fp = min;
            if (scale != 0.0f) {
                zero_point_fp = 0.f - min / scale;
            }
 
            // Handle any clamping
            uint8_t& zp = MlasQ4BlkZeroPoint<MLAS_Q4TYPE_BLK1>(dst_ptr);
            if (zero_point_fp < 0.0f) {
                zp = 0;
            } else if (zero_point_fp > 15.0f) {
                zp = 15;
            } else {
                zp = (uint8_t)roundf(zero_point_fp);
            }
            MlasQ4BlkScale<MLAS_Q4TYPE_BLK1>(dst_ptr) = scale;
            uint8_t* data = MlasQ4BlkData<MLAS_Q4TYPE_BLK1>(dst_ptr);
 
            for (size_t kk = 0; kk < klen; kk += 32) {
                size_t kklen = std::min((size_t)32, klen - kk);
                for (size_t l = 0; l < 16; l++) {
                    const float v0 = l < kklen ? src[ldb * (kk + l)] : 0;
                    const uint8_t vi0 = (uint8_t)std::min(
                        15.0f, std::max(0.0f, roundf(v0 * reciprocal_scale + zp)));
 
                    const size_t l1 = l + 16;
                    const float v1 = (l1 < kklen) ? src[ldb * (kk + l1)] : 0;
                    const uint8_t vi1 = (uint8_t)std::min(
                        15.0f, std::max(0.0f, roundf(v1 * reciprocal_scale + zp)));
 
                    data[l] = vi0 | (vi1 << 4);
                }
                data += 16;
            }
            // move to next block of values in this column
            dst_ptr += MLAS_Q4TYPE_BLK1::BlobSize;
            src += ldb * klen;
        }
        FpData++; // move to next column
    }
}
 
void
MLASCALL
MlasQ4GemmPackB(
    MLAS_BLK_QUANT_TYPE QType,
    void* PackedBuf,
    const float* FpData,
    size_t N,
    size_t K,
    size_t ldb
    )
{
    switch (QType) {
        case BlkQ4Sym:
            return MlasQ4GemmPackBImpl<MLAS_Q4TYPE_BLK0>(PackedBuf, FpData, N, K, ldb);
        case BlkQ4Sym64:
            return MlasQ4GemmPackBImpl<MLAS_Q4TYPE_BLK2>(PackedBuf, FpData, N, K, ldb);
        case BlkQ4Sym128:
            return MlasQ4GemmPackBImpl<MLAS_Q4TYPE_BLK4>(PackedBuf, FpData, N, K, ldb);
        default:
            return MlasQ4GemmPackBImpl<MLAS_Q4TYPE_BLK1>(PackedBuf, FpData, N, K, ldb);
    }
}
 
template<typename T>
MLAS_FORCEINLINE
void
MlasQ4GemmUnPackBImpl(float* FpData, const void* PackedBuf, size_t N, size_t K, size_t ldb)
{
    const auto* src = reinterpret_cast<const uint8_t*>(PackedBuf);
    for (size_t n = 0; n < N; n++) {
        for (size_t k = 0; k < K; k += T::BlkLen) {
            size_t CountK = std::min(K - k, T::BlkLen);
 
            float* dest = FpData + ldb * k + n;
            const float scale = MlasQ4BlkScale<T>(src);
            const uint8_t* data = MlasQ4BlkData<T>(src);
 
            for (size_t kk = 0; kk < CountK; kk += 32) {
                size_t kklen = std::min((size_t)32, CountK - kk);
                for (size_t l = 0; l < 16; l++) {
                    const uint8_t vi = data[l];
 
                    if (l < kklen) {
                        const int vi0 = (vi & 0x0F) - 8;
                        const float v0 = vi0 * scale;
                        dest[ldb * (kk + l)] = v0;
                    }
 
                    const size_t l1 = l + 16;
                    if (l1 < kklen) {
                        const int vi1 = (vi >> 4) - 8;
                        const float v1 = vi1 * scale;
                        dest[ldb * (kk + l1)] = v1;
                    }
                }
                data += 16;
            }
            src += T::BlobSize;
        }
    }
}
 
template<>
MLAS_FORCEINLINE
void
MlasQ4GemmUnPackBImpl<MLAS_Q4TYPE_BLK1>(
    float* FpData, const void* PackedBuf, size_t N, size_t K, size_t ldb)
{
    const auto* src = reinterpret_cast<const uint8_t*>(PackedBuf);
    for (size_t n = 0; n < N; n++) {
        for (size_t k = 0; k < K; k += MLAS_Q4TYPE_BLK1::BlkLen) {
            size_t CountK = std::min(K - k, MLAS_Q4TYPE_BLK1::BlkLen);
 
            float* dest = FpData + ldb * k + n;
            const float s = MlasQ4BlkScale<MLAS_Q4TYPE_BLK1>(src);
            const uint8_t z = MlasQ4BlkZeroPoint<MLAS_Q4TYPE_BLK1>(src);
            const uint8_t* pp = MlasQ4BlkData<MLAS_Q4TYPE_BLK1>(src);
 
            for (size_t kk = 0; kk < CountK; kk += 32) {
                size_t kklen = std::min((size_t)32, CountK - kk);
                for (size_t l = 0; l < 16; l++) {
                    const uint8_t vi = pp[l];
 
                    if (l < kklen) {
                        const int8_t vi0 = vi & 0x0F;
                        const float v0 = (vi0 - z) * s;
                        dest[ldb * (kk + l)] = v0;
                    }
 
                    size_t l1 = l + 16;
                    if (l1 < kklen) {
                        const int8_t vi1 = vi >> 4;
                        const float v1 = (vi1 - z) * s;
                        dest[ldb * (kk + l1)] = v1;
                    }
                }
                pp += 16;
            }
            src += MLAS_Q4TYPE_BLK1::BlobSize;
        }
    }
}
 
void
MLASCALL
MlasQ4GemmUnPackB(
    MLAS_BLK_QUANT_TYPE QType,
    float* FpData,
    const void* PackedBuf,
    size_t N,
    size_t K,
    size_t ldb
    )
{
    switch (QType) {
        case BlkQ4Sym:
            return MlasQ4GemmUnPackBImpl<MLAS_Q4TYPE_BLK0>(FpData, PackedBuf, N, K, ldb);
        case BlkQ4Sym64:
            return MlasQ4GemmUnPackBImpl<MLAS_Q4TYPE_BLK2>(FpData, PackedBuf, N, K, ldb);
        case BlkQ4Sym128:
            return MlasQ4GemmUnPackBImpl<MLAS_Q4TYPE_BLK4>(FpData, PackedBuf, N, K, ldb);
        default:
            return MlasQ4GemmUnPackBImpl<MLAS_Q4TYPE_BLK1>(FpData, PackedBuf, N, K, ldb);
    }
}
 
 
 
/***************************************************************
 * The quantization format that pack data and quantization
 * parameters into separate buffers.
 */
 
 
template <
    int Row_,    ///< rows of a matrix
    int Column_  ///< columns of a matrix
    >
struct Shape2D {
    static int const kRow = Row_;              ///< rows of a matrix
    static int const kColumn = Column_;        ///< columns of a matrix
    static int const kCount = Row_ * Column_;  ///< total number of elements in a matrix
};
 
 
template <int qbits, bool signed_quant>
struct BitsTraits {
    static_assert(qbits <= 8, "Only BitsTraits are for small number of bits!");
 
    static constexpr int kBits = qbits;
    static constexpr int kMax = signed_quant ? (1 << (qbits -1)) - 1 : (1 << qbits) - 1;
    static constexpr int kMid = signed_quant ? 0 : (1 << (qbits - 1));
    static constexpr int kMin = signed_quant ? -(1 << (qbits - 1)) : 0;
    static constexpr float kMaxFp = static_cast<float>(kMax);
    static constexpr float kMinFp = static_cast<float>(kMin);
    static constexpr float fullRange = kMaxFp - kMinFp;
    static constexpr float halfRange = static_cast<float>(kMid - kMin);
 
    // number of qbit elements to pack into whole bytes
    static constexpr int kPackSize = (qbits == 8) ? 1 : ((qbits == 4) ? 2 : ((qbits == 2) ? 4 : 0));
    static_assert(kPackSize != 0, "Packing to whole bytes not supported for this qbits!");
};
 
 
/**
 * @brief Rectify min/max from a set of weights, and convert to scale and zero point
 *        for quantization.
 * @tparam ScaleT        type of scale, usually floating point of various bits
 * @tparam qbits         number of int bits used for zero point value
 * @tparam signed_quant  output quantized type is signed
 * @param[in]   min
 * @param[in]   max
 * @param[out]  scale
 * @param[out]  zp
 */
template <typename ScaleT, int qbits, bool signed_quant>
MLAS_FORCEINLINE
void
range2scalezp(float min, float max, ScaleT& scale, uint8_t& zp)
{
    min = std::min(min, 0.0f);
    max = std::max(max, 0.0f);
 
    float scale_f = (max - min) / BitsTraits<qbits, signed_quant>::fullRange;
 
    float zero_point_fp = min;
    if (scale_f != 0.0f) {
        zero_point_fp = BitsTraits<qbits, signed_quant>::kMinFp - min / scale_f;
    }
 
    if (zero_point_fp < BitsTraits<qbits, signed_quant>::kMinFp) {
        zp = static_cast<uint8_t>(BitsTraits<qbits, signed_quant>::kMin);
    } else if (zero_point_fp > BitsTraits<qbits, signed_quant>::kMaxFp) {
        zp = static_cast<uint8_t>(BitsTraits<qbits, signed_quant>::kMax);
    } else {
        zp = (uint8_t)roundf(zero_point_fp);
    }
    scale = ScaleT(scale_f);
}
 
/**
 * @brief Rectify min/max from a set of symmetric weights, and convert
 *        to scale for quantization.
 */
template <typename ScaleT, int qbits, bool signed_quant>
MLAS_FORCEINLINE
void
range2scale(float min, float max, ScaleT& scale)
{
    max = fabsf(max) > fabsf(min) ? max : min;
    // !!Note: in the quantized space, abs of min -8 > abs of max 7.
    // Therefore map the larger half FP space to [-8, 0].
    // Minus sign achieves this purpose.
    scale = ScaleT(-max / BitsTraits<qbits, signed_quant>::halfRange);
};
 
 
/**
 * TODO(fajin): use int4/8 for symmetric quantization so the (vq - zp) operation in MatMulNBits can be saved.
 * @brief Blockwise quantization methods. Source is row major. Dest, scale and zp are column major.
 *        Always quantize to unsigned int.
 * @tparam ElementT       source data type, e.g. fp32/fp16
 * @tparam block_size     number of elemenets quantized together
 * @tparam qbits          number of bits in each quantized element
 * @tparam Columnwise     true:  quantize along src column, pack along src column.
 *                        false: quantize along src row, pack along src column.
 */
template <
    typename ElementT,
    int32_t block_size,
    int32_t qbits,
    bool Columnwise>
struct BlockwiseQuantizer {
    // To support other qbits, need to add bit packing code for
    // storing to dst and zero points
    static_assert(qbits == 2 || qbits == 4 || qbits == 8, "Only 2b, 4b and 8b block quantization is supported!");
 
    using QuantBlk = std::conditional_t<Columnwise, Shape2D<block_size, 1>, Shape2D<1, block_size>>;
    using ThreadBlk = Shape2D<QuantBlk::kRow * BitsTraits<qbits, false>::kPackSize, QuantBlk::kColumn>;
 
    static
    MLAS_FORCEINLINE
    int GetElem(int val, int idx)
    {
        return (val >> (qbits * idx)) & ((1 << qbits) - 1);
    }
 
    static
    MLAS_FORCEINLINE
    void quantizeMetaShape(int rows, int columns, int& meta_rows, int& meta_cols)
    {
        meta_rows = (rows + QuantBlk::kRow - 1) / QuantBlk::kRow;
        meta_cols = (columns + QuantBlk::kColumn - 1) / QuantBlk::kColumn;
    }
 
    static
    MLAS_FORCEINLINE
    void quantizedShape(int rows, int columns, int& q_rows, int& q_cols) {
        int meta_rows;
        int meta_cols;
        quantizeMetaShape(rows, columns, meta_rows, meta_cols);
 
        // quantized matrix is stored in column major, packed by column
        q_rows = (meta_rows * QuantBlk::kRow * qbits + 7) / 8;
        q_cols = meta_cols * QuantBlk::kColumn;
    }
 
    static MLAS_FORCEINLINE void quantizedBufferSizes(
        int rows, int columns, size_t& data_bytes, size_t& scale_num_elements, size_t* zero_point_bytes
    )
    {
        int meta_rows, meta_cols;
        quantizeMetaShape(rows, columns, meta_rows, meta_cols);
        int q_rows, q_cols;
        quantizedShape(rows, columns, q_rows, q_cols);
 
        data_bytes = q_rows * q_cols;
        scale_num_elements = meta_rows * meta_cols;
 
        if (zero_point_bytes) {
            // this works for qbits == 2, 4 or 8 but may need to be updated for other qbits values
            *zero_point_bytes = ((meta_rows * qbits + 7) / 8) * meta_cols;
        }
    }
 
    /**
     * @brief Quantized a Matrix shape [rows, columns], resulting quantized
     *        and packed data are stored in column major (transposed).
     * @param[out] dst           pointer to the quantized weights, column major: [columns, rows]
     * @param[out] scale         pointer to the scales, column major: [columns/QuantBlk::kColumn, rows/QuantBlk::kRow]
     * @param[out] zero_points   pointer to the zero points, same shape as scale
     * @param[in]  src           pointer to the source matrix, row major: [rows, columns]
     * @param rows
     * @param columns
     * @param leadingDimension   stride of the source matrix, i.e. distance from one row to the next
     */
    static void quantizeAndTranspose(
        uint8_t* dst,
        ElementT* scales,
        uint8_t* zero_points,
        const ElementT* src,
        int32_t rows,
        int32_t columns,
        int32_t leadingDimension,
        MLAS_THREADPOOL* thread_pool)
    {
        // Thread partitioning
        const auto thrd_row_blks = (rows + ThreadBlk::kRow - 1) / ThreadBlk::kRow;
        const auto thrd_col_blks = (columns + ThreadBlk::kColumn - 1) / ThreadBlk::kColumn;
        const auto total_thrd_blks = thrd_row_blks * thrd_col_blks;
 
        const auto row_blks = (rows + QuantBlk::kRow - 1) / QuantBlk::kRow;
 
        int q_rows, q_cols;
        quantizedShape(rows, columns, q_rows, q_cols);
 
        MlasTryBatchParallel(
            thread_pool, total_thrd_blks,
            [&](ptrdiff_t block_idx) {
                constexpr int kPackSize = BitsTraits<qbits, false>::kPackSize;
                uint8_t zp_bytes[kPackSize], vi[kPackSize];
                std::fill_n(zp_bytes, kPackSize, (uint8_t)BitsTraits<qbits, false>::kMid);
                std::fill_n(vi, kPackSize, 0);
 
                const int32_t r_blk_idx = static_cast<int32_t>(block_idx / thrd_col_blks);
                const int32_t c_blk_idx = static_cast<int32_t>(block_idx % thrd_col_blks);
 
                const int32_t r = r_blk_idx * ThreadBlk::kRow;
                const int32_t c = c_blk_idx * ThreadBlk::kColumn;
 
                const int32_t r_end = std::min(r + ThreadBlk::kRow, rows);
                const int32_t c_end = std::min(c + ThreadBlk::kColumn, columns);
 
                const int meta_row = r / QuantBlk::kRow;
                const int meta_col = c / QuantBlk::kColumn;
 
                // compute scale and zero point
                for (int kpack = 0; kpack < kPackSize; kpack++) {
 
                    // scan a single block to extract range [min, max]
                    float min = std::numeric_limits<float>::max();
                    float max = -min;
                    const int row_start = r + kpack * QuantBlk::kRow;
                    const int row_end = std::min(row_start + QuantBlk::kRow, r_end);
                    for (int i = row_start; i < row_end; ++i) {
                        for (int j = c; j < c_end; ++j) {
                            const float v = static_cast<float>(src[i * leadingDimension + j]);
                            if (v < min) min = v;
                            if (v > max) max = v;
                        }
                    }
 
                    // store scale and zero point at quant parameter matrix position
                    if (row_start < row_end) {
                        const int32_t meta_idx = meta_col * row_blks + meta_row + kpack;
                        if (zero_points == nullptr) {
                            range2scale<ElementT, qbits, false>(min, max, scales[meta_idx]);
                        } else {
                            range2scalezp<ElementT, qbits, false>(min, max, scales[meta_idx], zp_bytes[kpack]);
                        }
                    }
                }
 
                if (zero_points != nullptr) {
                    const int32_t meta_idx = meta_col * ((row_blks + kPackSize - 1) / kPackSize) + meta_row / kPackSize;
                    if constexpr (qbits == 8) {
                        zero_points[meta_idx] = zp_bytes[0];
                    } else if constexpr (qbits == 4) {
                        zero_points[meta_idx] = (zp_bytes[0] & 0xf) | (zp_bytes[1] << 4);
                    } else if constexpr (qbits == 2) {
                        zero_points[meta_idx] = (zp_bytes[0] & 0x3) | (zp_bytes[1] << 2) | (zp_bytes[2] << 4) | (zp_bytes[3] << 6);
                    } else {
                        MLAS_THROW_EX(std::runtime_error, "Unsupported qbits");
                    }
                }
 
                for (int32_t j = c; j < c_end; ++j) { // this does not work if j runs more then 1 because zp_bytes is indexed by i.
                    const int32_t meta_c = j / QuantBlk::kColumn;
                    for (int32_t i = r; i < r_end; i += kPackSize) {
                        for (int l = 0; l < kPackSize && i + l < r_end; l++) {
                            const int32_t meta_r = (i + l) / QuantBlk::kRow;
                            const float scale = static_cast<float>(scales[meta_c * row_blks + meta_r]);
                            const float reciprocal_scale = scale ? 1.0f / scale : 0.0f;
                            const int32_t zp = zp_bytes[meta_r % kPackSize];
 
                            const float v = static_cast<float>(src[(i + l) * leadingDimension + j]);
                            vi[l] = (uint8_t)std::clamp(roundf(v * reciprocal_scale + zp),
                                                        0.0f, BitsTraits<qbits, false>::kMaxFp);
                        }
 
                        if constexpr (qbits == 8) {
                            dst[j * q_rows + i / kPackSize] = vi[0];
                        } else if constexpr (qbits == 4) {
                            dst[j * q_rows + i / kPackSize] = (vi[0] & 0xf) | (vi[1] << 4);
                        } else if constexpr (qbits == 2) {
                            dst[j * q_rows + i / kPackSize] = (vi[0] & 0x3) | (vi[1] << 2) | (vi[2] << 4) | (vi[3] << 6);
                        } else {
                            MLAS_THROW_EX(std::runtime_error, "Unsupported qbits");
                        }
                    }
                }
            });
    }
 
    /**
     * @brief Dequantize a column major quantized matrix, and store the result in a column major
     * matrix for use in GEMM
     * @param[out] dst           pointer to the dequantized matrix, column major: [columns, rows]
     * @param[in]  weights       pointer to the quantized weights, column major: [columns, rows]
     * @param[in]  scales        pointer to the scales of quantized blocks, column major layout
     * @param[in]  zero_points   pointer to the zero points of quantized blocks, packed column major
     *                           scales
     * @param[in]  rows
     * @param[in]  columns
     */
    static void dequantize(
        ElementT* dst,
        const uint8_t* weights,
        const ElementT* scales,
        const uint8_t* zero_points,
        int32_t rows,
        int32_t columns,
        MLAS_THREADPOOL* thread_pool)
    {
        // Thread partitioning
        const auto thrd_row_blks = (rows + ThreadBlk::kRow - 1) / ThreadBlk::kRow;
        const auto thrd_col_blks = (columns + ThreadBlk::kColumn - 1) / ThreadBlk::kColumn;
        const auto total_thrd_blks = thrd_row_blks * thrd_col_blks;
 
        const auto row_blks = (rows + QuantBlk::kRow - 1) / QuantBlk::kRow;
 
        int q_rows, q_cols;
        quantizedShape(rows, columns, q_rows, q_cols);
        constexpr int32_t kPackSize = BitsTraits<qbits, false>::kPackSize;
 
        MlasTryBatchParallel(
            thread_pool, total_thrd_blks,
            [&](ptrdiff_t block_idx) {
                int32_t r_blk_idx = static_cast<int32_t>(block_idx / thrd_col_blks);
                int32_t c_blk_idx = static_cast<int32_t>(block_idx % thrd_col_blks);
 
                int32_t r = r_blk_idx * ThreadBlk::kRow;
                int32_t c = c_blk_idx * ThreadBlk::kColumn;
 
                int32_t r_end = std::min(r + ThreadBlk::kRow, rows);
                int32_t c_end = std::min(c + ThreadBlk::kColumn, columns);
 
                for (int32_t j = c; j < c_end; ++j) {
                    const int32_t meta_col = j / QuantBlk::kColumn;
 
                    for (int32_t i = r; i < r_end; ++i) {
                        const int32_t meta_row = i / QuantBlk::kRow;
                        const float scale = static_cast<float>(scales[meta_col * row_blks + meta_row]);
                        const int zp_pair =
                            zero_points
                            ? zero_points[meta_col * ((row_blks + kPackSize - 1) / kPackSize) + meta_row / kPackSize]
                            : 0;
                        const int vi_pair = weights[j * q_rows + i / kPackSize];
 
                        const int zp =
                            zero_points
                                ? GetElem(zp_pair, meta_row % kPackSize)
                                : BitsTraits<qbits, false>::kMid;
                        const int vi = GetElem(vi_pair, i % kPackSize);
                        const float v = (vi - zp) * scale;
                        dst[j * rows + i] = ElementT(v);
                    }
                }
            });
    }
};
 
/**
 * @brief Blockwise quantization methods for QDQ format. Input tensor is quantized along column
 *        or row. Scales and zeros are calculated. Based on qbits, consecutive quantized elements
 *        in memory are packed together, which means the packing is along the row. Quantized data
 *        are stored in row major, so the output tensor reserves same shape, in terms of qbits type,
 *        as the input tensor.
 *        If has zero points, quantized type is unsigned. Otherwise, quantized type is signed and the
 *        zero point is 0.
 *        The transposed outputs are used by MatMulNBits, so quant type becomes uint4 with default
 *        zp at 8.
 * @tparam Tin           source data type, e.g. fp32/fp16
 * @tparam qbits         number of bits in each quantized element
 * @tparam signed_quant  quantized type is signed
 */
template <typename Tin, int qbits, bool signed_quant>
struct BlockwiseQDQQuantizer {
    static MLAS_FORCEINLINE uint8_t GetElem(uint8_t val, int32_t idx)
    {
        if constexpr (qbits == 2) {
            return (val >> (idx << 1)) & 0x3;
        } else if constexpr (qbits == 4) {
            return (val >> (idx << 2)) & 0xF;
        } else if constexpr (qbits == 8) {
            (void)idx;
            return val;
        }
    }
 
    static MLAS_FORCEINLINE uint8_t SetElem(uint8_t val, int32_t idx, uint8_t dst)
    {
        if constexpr (qbits == 2) {
            auto shift = idx << 1;
            return ((val & 0x3) << shift) | (dst & (~(0x3 << shift)));
        } else if constexpr (qbits == 4) {
            auto shift = idx << 2;
            return ((val & 0xF) << shift) | (dst & (~(0xF << shift)));
        } else if constexpr (qbits == 8) {
            (void)idx;
            (void)dst;
            return val;
        }
    }
 
    template <bool add2>
    static MLAS_FORCEINLINE uint8_t Pack(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3)
    {
          if constexpr (add2) {
            return ((v0 & 0x3) ^ 2) | (((v1 & 0x3) ^ 2) << 2) | (((v2 & 0x3) ^ 2) << 4) | (((v3 & 0x3) ^ 2) << 6);
          } else {
              return (v0 & 0x3) | ((v1 & 0x3) << 2) | ((v2 & 0x3) << 4) | ((v3 & 0x3) << 6);
          }
    }
 
    template <bool add8>
    static MLAS_FORCEINLINE uint8_t Pack(uint8_t v0, uint8_t v1)
    {
        if constexpr (add8) {
            return ((v0 & 0xF) ^ 8) | (((v1 & 0xF) ^ 8) << 4);
        } else {
            return (v0 & 0xF) | ((v1 & 0xF) << 4);
        }
    }
 
    // If src is row major, then dst is column major. Transpose:
    //  | src0: low 4 bit | src0: high 4 bit |
    //  | src1: low 4 bit | src1: high 4 bit |
    //  -->
    //  | dst0: low 4 bit | dst1: low 4 bit  |
    //  | dst0: high 4 bit| dst1: high 4 bit |
    // If src is column major, then dst is row major. Transpose:
    //  | src0: low 4 bit | src1: low 4 bit  |
    //  | src0: high 4 bit| src1: high 4 bit |
    //  -->
    //  | dst0: low 4 bit | dst0: high 4 bit |
    //  | dst1: low 4 bit | dst1: high 4 bit |
    template <bool add8>
    static MLAS_FORCEINLINE void Transpose(uint8_t src0, uint8_t src1, uint8_t& dst0, uint8_t& dst1)
    {
        if constexpr (add8) {
            dst0 = ((src0 & 0xF) ^ 8) | (((src1 & 0xF) ^ 8) << 4);
            dst1 = (((src0 & 0xF0) ^ 0x80) >> 4) | ((src1 & 0xF0) ^ 0x80);
        } else {
            dst0 = (src0 & 0xF) | ((src1 & 0xF) << 4);
            dst1 = ((src0 & 0xF0) >> 4) | (src1 & 0xF0);
        }
    }
 
    static MLAS_FORCEINLINE uint8_t QuantizeV(Tin src, float reciprocal_scale, uint8_t zero_point)
    {
        return static_cast<uint8_t>(
            std::clamp(
                static_cast<int32_t>(
                    std::roundf(static_cast<float>(src) * reciprocal_scale)
                ) + static_cast<int32_t>(zero_point),
                BitsTraits<4, signed_quant>::kMin,
                BitsTraits<4, signed_quant>::kMax
            )
        );
    }
 
    /**
     * @brief Quantize a matrix shape [rows, columns] column-wise. Scales and zero points are calculated.
     *        Quantized data are packed row-wise based on qbits. Quantized data are stored in row major
     *        so the output tensor reserves the shape, in terms output type.
     * @param src               the source matrix, row major: [rows * columns]
     * @param scales            the scales of quantized blocks, row major with shape:
     *                          [ceil(rows/quant_block_size) * columns]
     * @param zero_points       the zero points of quantized blocks, packed. Same shape as scales in terms
     *                          of output type. In uint8_t, the shape is:
     *                          [ceil(columns * ceil(rows / quant_block_size) * qbits / 8)]
     * @param dst               the quantized weights, row major: [rows * columns] in terms of output type.
     *                          In uint8_t, the shape is: [ceil(rows * columns * qbits / 8]
     * @param rows              number of rows in the source matrix
     * @param columns           number of columns in the source matrix.
     * @param quant_block_size  number of rows/columns quantized together
     * @param thread_pool       thread pool for parallel processing
     */
    static void QuantizeColumnWise(
        const Tin* src,
        Tin* scales,
        uint8_t* zero_points,
        uint8_t* dst,
        int32_t rows,
        int32_t columns,
        int32_t quant_block_size,
        MLAS_THREADPOOL* thread_pool
    )
    {
        ORT_ENFORCE(zero_points || signed_quant, "Unsigned quant with no zero points is not supported.");
        // Must avoid multiple thread write to a single byte, which means the starting index
        // of a thread block must be even. To achieve that, we need to customize the thread
        // block size based on the parity of columns.
        if (columns & 1) {
            QuantizeColumnWisePackUnaligned(
                src, scales, zero_points, dst, rows, columns, quant_block_size, thread_pool
            );
        } else {
            QuantizeColumnWisePackAligned(
                src, scales, zero_points, dst, rows, columns, quant_block_size, thread_pool
            );
        }
    }
 
 
    /**
     * @brief Transpose quantized tensors, which has been column-wise quantized, for use in MatMulNbits.
     *        Since both src tensor and dst tensor are packed, it's not needed to consider sign
     *        during the unpacking/packing in transpose.
     * @param src_weights       The quantized weights, row major: [rows, columns] in qbits type.
     *                          In uint8_t, size of [ceil(rows * columns * qbits / 8)].
     * @param src_scales        [ceil(rows / quant_block_size), columns]
     * @param src_zero_points   [ceil(rows / quant_block_size), columns] in qbits type. In uint8_t, size of
     *                          [ceil(ceil(rows / quant_block_size) * columns * qbits / 8 )].
     * @param dst_weights       the transposed quantized weights, column major. In uint8_t, the shape is
     *                          [columns, ceil(rows / quant_block_size), ceil(quant_block_size * qbits / 8)]
     * @param dst_scales        [columns, ceil(rows / quant_block_size)]
     * @param dst_zero_points   [columns, ceil(ceil(rows / quant_block_size) * qbits / 8)] in uint8_t.
     * @param rows              number of src rows in qbits type.
     * @param columns           number of src columns in qbits type.
     * @param quant_block_size  number of elements quantized together
     * @param thread_pool       thread pool for parallel processing
     */
    static void TransposeColumnWiseQuantized(
        const uint8_t* src_weights,
        const Tin* src_scales,
        const uint8_t* src_zero_points,
        uint8_t* dst_weights,
        Tin* dst_scales,
        uint8_t* dst_zero_points,
        int32_t rows,
        int32_t columns,
        int32_t quant_block_size,
        MLAS_THREADPOOL* thread_pool
    )
    {
        ORT_ENFORCE(
            src_zero_points || signed_quant || dst_zero_points,
            "Unsigned quant types without zero points must allocate zero points with value 0."
        );
 
        if constexpr (qbits == 8) {
            // 8-bit: each element is one byte, no sub-byte packing needed.
            // Simple byte-level transpose from [rows, columns] to [columns, k_blocks, block_size].
            auto row_quant_blk_num = (rows + quant_block_size - 1) / quant_block_size;
            auto dst_bytes_per_quant_blk = quant_block_size;  // 8 bits = 1 byte per element
            auto dstT_num_row = row_quant_blk_num * dst_bytes_per_quant_blk;
 
            // Transpose weights: src [rows, columns] -> dst [columns, k_blocks, block_size]
            MlasTryBatchParallel(
                thread_pool, static_cast<ptrdiff_t>(row_quant_blk_num * columns),
                [&](ptrdiff_t thread_blk_idx) {
                    auto row_blk = static_cast<int32_t>(thread_blk_idx / columns);
                    auto col = static_cast<int32_t>(thread_blk_idx % columns);
 
                    auto src_row_start = row_blk * quant_block_size;
                    auto src_row_end = std::min(src_row_start + quant_block_size, rows);
 
                    auto dst_base = col * dstT_num_row + row_blk * dst_bytes_per_quant_blk;
                    for (auto r = src_row_start; r < src_row_end; ++r) {
                        auto src_val = src_weights[r * columns + col];
                        if constexpr (signed_quant) {
                            src_val ^= 0x80;  // INT8 -> UINT8: add 128
                        }
                        dst_weights[dst_base + (r - src_row_start)] = src_val;
                    }
                    // Zero-pad remaining bytes in the last block if rows % block_size != 0
                    for (auto r = src_row_end - src_row_start; r < quant_block_size; ++r) {
                        dst_weights[dst_base + r] = signed_quant ? 0x80 : 0;
                    }
                }
            );
 
            // Transpose scales: src [k_blocks, columns] -> dst [columns, k_blocks]
            MlasTryBatchParallel(
                thread_pool, static_cast<ptrdiff_t>(columns),
                [&](ptrdiff_t col) {
                    auto src_idx = static_cast<int32_t>(col);
                    auto dst_idx = static_cast<int32_t>(col) * row_quant_blk_num;
                    for (int32_t i = 0; i < row_quant_blk_num; ++i, ++dst_idx, src_idx += columns) {
                        dst_scales[dst_idx] = src_scales[src_idx];
                    }
                }
            );
 
            // Transpose zero points: src [k_blocks, columns] -> dst [columns, k_blocks]
            // For 8-bit, zero points are byte-aligned (1 byte each), no packing needed.
            if (src_zero_points && dst_zero_points) {
                MlasTryBatchParallel(
                    thread_pool, static_cast<ptrdiff_t>(columns),
                    [&](ptrdiff_t col) {
                        auto src_idx = static_cast<int32_t>(col);
                        auto dst_idx = static_cast<int32_t>(col) * row_quant_blk_num;
                        for (int32_t i = 0; i < row_quant_blk_num; ++i, ++dst_idx, src_idx += columns) {
                            auto zp = src_zero_points[src_idx];
                            if constexpr (signed_quant) {
                                zp ^= 0x80;  // INT8 -> UINT8
                            }
                            dst_zero_points[dst_idx] = zp;
                        }
                    }
                );
            }
        } else if constexpr (qbits == 2) {
            // 2-bit: 4 elements per byte. Element-by-element transpose.
            constexpr int32_t kPackSize = 4;
            auto row_quant_blk_num = (rows + quant_block_size - 1) / quant_block_size;
            auto packed_src_cols = (columns + kPackSize - 1) / kPackSize;
            auto dst_bytes_per_quant_blk = (quant_block_size + kPackSize - 1) / kPackSize;
            auto dstT_num_row = row_quant_blk_num * dst_bytes_per_quant_blk;
 
            // Transpose weights: src [rows, ceil(columns/4)] -> dst [columns, k_blocks, ceil(block_size/4)]
            // Each thread handles one (row_block, column) pair writing to non-overlapping dst ranges.
            MlasTryBatchParallel(
                thread_pool, static_cast<ptrdiff_t>(row_quant_blk_num * columns),
                [&](ptrdiff_t thread_blk_idx) {
                    auto row_blk = static_cast<int32_t>(thread_blk_idx / columns);
                    auto col = static_cast<int32_t>(thread_blk_idx % columns);
 
                    auto src_row_start = row_blk * quant_block_size;
                    auto src_row_end = std::min(src_row_start + quant_block_size, rows);
 
                    auto dst_base = col * dstT_num_row + row_blk * dst_bytes_per_quant_blk;
 
                    // Zero destination bytes for this block
                    for (int32_t b = 0; b < dst_bytes_per_quant_blk; ++b) {
                        dst_weights[dst_base + b] = 0;
                    }
 
                    for (auto r = src_row_start; r < src_row_end; ++r) {
                        // Extract 2-bit value from source
                        auto src_byte_idx = r * packed_src_cols + col / kPackSize;
                        auto src_bit_shift = (col % kPackSize) * 2;
                        uint8_t val = (src_weights[src_byte_idx] >> src_bit_shift) & 0x3;
 
                        if constexpr (signed_quant) {
                            val ^= 0x2;  // int2[-2,1] -> uint2[0,3]
                        }
 
                        // Place in destination
                        auto r_in_blk = r - src_row_start;
                        auto dst_byte_off = r_in_blk / kPackSize;
                        auto dst_bit_shift = (r_in_blk % kPackSize) * 2;
                        dst_weights[dst_base + dst_byte_off] |= (val << dst_bit_shift);
                    }
 
                    // Zero-pad remaining positions (unsigned equivalent of 0)
                    if constexpr (signed_quant) {
                        for (auto r_in_blk = src_row_end - src_row_start;
                             r_in_blk < quant_block_size; ++r_in_blk) {
                            auto dst_byte_off = r_in_blk / kPackSize;
                            auto dst_bit_shift = (r_in_blk % kPackSize) * 2;
                            dst_weights[dst_base + dst_byte_off] |= (0x2 << dst_bit_shift);
                        }
                    }
                }
            );
 
            // Transpose scales: src [k_blocks, columns] -> dst [columns, k_blocks]
            MlasTryBatchParallel(
                thread_pool, static_cast<ptrdiff_t>(columns),
                [&](ptrdiff_t col) {
                    auto src_idx = static_cast<int32_t>(col);
                    auto dst_idx = static_cast<int32_t>(col) * row_quant_blk_num;
                    for (int32_t i = 0; i < row_quant_blk_num; ++i, ++dst_idx, src_idx += columns) {
                        dst_scales[dst_idx] = src_scales[src_idx];
                    }
                }
            );
 
            // Transpose zero points: src [k_blocks, ceil(columns/4)] -> dst [columns, ceil(k_blocks/4)]
            if (src_zero_points && dst_zero_points) {
                auto packed_src_zp_cols = (columns + kPackSize - 1) / kPackSize;
                auto zp_dst_bytes_per_col = (row_quant_blk_num + kPackSize - 1) / kPackSize;
 
                MlasTryBatchParallel(
                    thread_pool, static_cast<ptrdiff_t>(columns),
                    [&](ptrdiff_t col_idx) {
                        auto col = static_cast<int32_t>(col_idx);
                        auto dst_base = col * zp_dst_bytes_per_col;
 
                        for (int32_t b = 0; b < zp_dst_bytes_per_col; ++b) {
                            dst_zero_points[dst_base + b] = 0;
                        }
 
                        for (int32_t blk = 0; blk < row_quant_blk_num; ++blk) {
                            auto src_byte_idx = blk * packed_src_zp_cols + col / kPackSize;
                            auto src_bit_shift = (col % kPackSize) * 2;
                            uint8_t val = (src_zero_points[src_byte_idx] >> src_bit_shift) & 0x3;
 
                            if constexpr (signed_quant) {
                                val ^= 0x2;
                            }
 
                            auto dst_byte_off = blk / kPackSize;
                            auto dst_bit_shift = (blk % kPackSize) * 2;
                            dst_zero_points[dst_base + dst_byte_off] |= (val << dst_bit_shift);
                        }
                    }
                );
            }
        } else {
            // 4-bit sub-byte types: use packing-aware transpose paths.
            // Must avoid multiple thread write to a single byte, which means the starting index
            // of a thread block must be even. To achieve that, we need to customize the thread
            // block size based on the parity of columns.
            if (columns & 1) {
                TransposeColumnWiseQuantizedPackUnaligned(
                    src_weights, src_scales, src_zero_points,
                    dst_weights, dst_scales, dst_zero_points,
                    rows, columns, quant_block_size, thread_pool
                );
            } else {
                TransposeColumnWiseQuantizedPackAligned(
                    src_weights, src_scales, src_zero_points,
                    dst_weights, dst_scales, dst_zero_points,
                    rows, columns, quant_block_size, thread_pool
                );
            }
        }
    }
 
private:
    static void QuantizeColumnWisePackAligned(
        const Tin* src,
        Tin* scales,
        uint8_t* zero_points,
        uint8_t* dst,
        int32_t rows,
        int32_t columns,
        int32_t quant_block_size,
        MLAS_THREADPOOL* thread_pool
    )
    {
        ORT_ENFORCE(columns % 2 == 0, "Columns must be multiple of 2.");
        // Thread block is [quant_block_size, thread_blk_size]. thread_blk_size % 2 == 0.
        constexpr int32_t thread_blk_size = 128;
        const auto num_row_thread_blk = (rows + quant_block_size - 1) / quant_block_size;
        const auto num_col_thread_blk = (columns + thread_blk_size - 1) / thread_blk_size;
        const auto num_thread_blk = num_row_thread_blk * num_col_thread_blk;
        constexpr auto minf = std::numeric_limits<float>::lowest();
        constexpr auto maxf = std::numeric_limits<float>::max();
 
        MlasTryBatchParallel(
            thread_pool, static_cast<ptrdiff_t>(num_thread_blk),
            [&](ptrdiff_t thread_blk_idx) {
                // !!warning!!: buffering the whole thread block
                constexpr int32_t buffer_size = 128;
                ORT_ENFORCE(buffer_size == thread_blk_size, "buffer size must be equal to thread block size.");
                float reciprocal_scale_t[buffer_size];
                uint8_t zp_t[buffer_size];
                float vmin_t[buffer_size];
                float vmax_t[buffer_size];
 
                const int32_t row_thread_blk_idx = static_cast<int32_t>(thread_blk_idx / num_col_thread_blk);
                const int32_t col_thread_blk_idx = static_cast<int32_t>(thread_blk_idx % num_col_thread_blk);
                const int32_t row_idx = row_thread_blk_idx * quant_block_size;
                const int32_t col_idx = col_thread_blk_idx * buffer_size;
                const int32_t row_size = std::min(quant_block_size, rows - row_idx);
                const int32_t col_size = std::min(buffer_size, columns - col_idx);
                // input_idx, scale_idx, col_size are aligned to 2
                auto input_idx = row_idx * columns + col_idx;
                auto scale_idx = row_thread_blk_idx * columns + col_idx;
 
                Tin scale0_tt, scale1_tt;
                uint8_t v0_tt, v1_tt;
 
                std::fill_n(vmin_t, buffer_size, maxf);
                std::fill_n(vmax_t, buffer_size, minf);
 
                // calculate min/max
                for (int32_t j = 0, input_idx_t = input_idx; j < row_size; ++j, input_idx_t += columns) {
                    // TODO(fajin): use SIMD
                    for (int32_t i = 0; i < col_size; i += 2) {
                        auto v0 = static_cast<float>(src[input_idx_t + i]);
                        auto v1 = static_cast<float>(src[input_idx_t + i + 1]);
                        vmin_t[i] = std::min(vmin_t[i], v0);
                        vmax_t[i] = std::max(vmax_t[i], v0);
                        vmin_t[i + 1] = std::min(vmin_t[i + 1], v1);
                        vmax_t[i + 1] = std::max(vmax_t[i + 1], v1);
                    }
                }
 
                // calculate scale and zero point, and store
                for (int32_t i = 0; i < col_size; i += 2) {
                    v0_tt = v1_tt = BitsTraits<4, signed_quant>::kMid;
 
                    if (zero_points) {
                        range2scalezp<Tin, 4, signed_quant>(vmin_t[i], vmax_t[i], scale0_tt, v0_tt);
                        range2scalezp<Tin, 4, signed_quant>(vmin_t[i + 1], vmax_t[i + 1], scale1_tt, v1_tt);
                        zero_points[(scale_idx + i) >> 1] = Pack<false>(v0_tt, v1_tt);
                    } else {
                        range2scale<Tin, 4, signed_quant>(vmin_t[i], vmax_t[i], scale0_tt);
                        range2scale<Tin, 4, signed_quant>(vmin_t[i + 1], vmax_t[i + 1], scale1_tt);
                    }
 
                    scales[scale_idx + i] = scale0_tt;
                    scales[scale_idx + i + 1] = scale1_tt;
 
                    float scalef0 = static_cast<float>(scale0_tt);
                    reciprocal_scale_t[i] = scalef0 ? 1.0f / scalef0 : 0.0f;
                    zp_t[i] = v0_tt;
 
                    float scalef1 = static_cast<float>(scale1_tt);
                    reciprocal_scale_t[i + 1] = scalef1 ? 1.0f / scalef1 : 0.0f;
                    zp_t[i + 1] = v1_tt;
                }
 
                // quantize and pack
                for (int32_t j = 0, input_idx_t = input_idx; j < row_size; ++j, input_idx_t += columns) {
                    // TODO(fajin): use SIMD
                    for (int32_t i = 0; i < col_size; i += 2) {
                        v0_tt = QuantizeV(src[input_idx_t + i], reciprocal_scale_t[i], zp_t[i]);
                        v1_tt = QuantizeV(src[input_idx_t + i + 1], reciprocal_scale_t[i + 1], zp_t[i + 1]);
                        dst[(input_idx_t + i) >> 1] = Pack<false>(v0_tt, v1_tt);
                    }
                }
            }
        );
    }
 
    static void QuantizeColumnWisePackUnaligned(
        const Tin* src,
        Tin* scales,
        uint8_t* zero_points,
        uint8_t* dst,
        int32_t rows,
        int32_t columns,
        int32_t quant_block_size,
        MLAS_THREADPOOL* thread_pool
    )
    {
        // Thread block is [quant_block_size * 2, columns], so the packed bytes do not cross threads.
        constexpr auto minf = std::numeric_limits<float>::lowest();
        constexpr auto maxf = std::numeric_limits<float>::max();
        auto row_thread_blk_size = quant_block_size * 2;
        auto num_row_thread_blk = (rows + row_thread_blk_size - 1) / (row_thread_blk_size);
 
        MlasTryBatchParallel(
            thread_pool, static_cast<ptrdiff_t>(num_row_thread_blk),
            [&](ptrdiff_t thread_blk_idx) {
                constexpr int32_t buffer_size = 128;
                float reciprocal_scale_t[buffer_size];
                uint8_t zp_t[buffer_size];
                float vmin_t[buffer_size];
                float vmax_t[buffer_size];
 
                auto row_thread_blk_idx = static_cast<int32_t>(thread_blk_idx);
                int32_t row_idx = row_thread_blk_idx * row_thread_blk_size;
                int32_t row_idx_end = std::min(row_thread_blk_size + row_idx, rows);
                auto input_idx = row_idx * columns;
                auto scale_idx = row_thread_blk_idx * 2 * columns;
                Tin scale0_tt, scale1_tt;
                uint8_t v0_tt, v1_tt;
 
                for (; row_idx < row_idx_end; row_idx += quant_block_size) {
                    // per quant block row
                    auto quant_row_size = std::min(quant_block_size, row_idx_end - row_idx);
                    auto input_buffer_idx = input_idx;
                    auto scale_buffer_idx = scale_idx;
                    for (int32_t buffer_idx = 0; buffer_idx < columns; buffer_idx += buffer_size) {
                        // per buffer column
                        auto buffer_col_size = std::min(buffer_size, columns - buffer_idx);
 
                        std::fill_n(vmin_t, buffer_size, maxf);
                        std::fill_n(vmax_t, buffer_size, minf);
                        // calculate min/max of [quant block, buffer]
                        auto input_idx_t = input_buffer_idx;
                        for (int32_t j = 0; j < quant_row_size; ++j, input_idx_t += columns) {
                            // TODO(fajin): use SIMD
                            for (int32_t i = 0; i < buffer_col_size; ++i) {
                                auto v = static_cast<float>(src[input_idx_t + i]);
                                vmin_t[i] = std::min(vmin_t[i], v);
                                vmax_t[i] = std::max(vmax_t[i], v);
                            }
                        }
 
                        // calculate scale and zero point
                        auto scale_buffer_idx_end = scale_buffer_idx + buffer_col_size;
                        int32_t col_idx = 0;
                        // leading unailgned zero points
                        if (scale_buffer_idx & 1) {
                            v0_tt = BitsTraits<4, signed_quant>::kMid;
                            if (zero_points) {
                                range2scalezp<Tin, 4, signed_quant>(vmin_t[0], vmax_t[0], scale0_tt, v0_tt);
                                zero_points[scale_buffer_idx >> 1] = SetElem(
                                    v0_tt, 1, zero_points[scale_buffer_idx >> 1]
                                );
                            } else {
                                range2scale<Tin, 4, signed_quant>(vmin_t[0], vmax_t[0], scale0_tt);
                            }
 
                            scales[scale_buffer_idx] = scale0_tt;
 
                            float scalef = static_cast<float>(scale0_tt);
                            reciprocal_scale_t[0] = scalef ? 1.0f / scalef : 0.0f;
                            zp_t[0] = v0_tt;
 
                            ++col_idx;
                            ++scale_buffer_idx;
                        }
                        // aligned zero points
                        for (; scale_buffer_idx < scale_buffer_idx_end - 1; col_idx += 2, scale_buffer_idx += 2) {
                            v0_tt = v1_tt = BitsTraits<4, signed_quant>::kMid;
                            if (zero_points) {
                                range2scalezp<Tin, 4, signed_quant>(vmin_t[col_idx], vmax_t[col_idx], scale0_tt, v0_tt);
                                range2scalezp<Tin, 4, signed_quant>(
                                    vmin_t[col_idx + 1], vmax_t[col_idx + 1], scale1_tt, v1_tt
                                );
                                zero_points[scale_buffer_idx >> 1] = Pack<false>(v0_tt, v1_tt);
                            } else {
                                range2scale<Tin, 4, signed_quant>(vmin_t[col_idx], vmax_t[col_idx], scale0_tt);
                                range2scale<Tin, 4, signed_quant>(vmin_t[col_idx + 1], vmax_t[col_idx + 1], scale1_tt);
                            }
 
                            scales[scale_buffer_idx] = scale0_tt;
                            scales[scale_buffer_idx + 1] = scale1_tt;
 
                            float scalef0 = static_cast<float>(scale0_tt);
                            reciprocal_scale_t[col_idx] = scalef0 ? 1.0f / scalef0 : 0.0f;
                            zp_t[col_idx] = v0_tt;
 
                            float scalef1 = static_cast<float>(scale1_tt);
                            reciprocal_scale_t[col_idx + 1] = scalef1 ? 1.0f / scalef1 : 0.0f;
                            zp_t[col_idx + 1] = v1_tt;
                        }
                        // tailing unaligned elements
                        if (scale_buffer_idx < scale_buffer_idx_end) {
                            v0_tt = BitsTraits<4, signed_quant>::kMid;
                            if (zero_points) {
                                range2scalezp<Tin, 4, signed_quant>(vmin_t[col_idx], vmax_t[col_idx], scale0_tt, v0_tt);
                                zero_points[scale_buffer_idx >> 1] = SetElem(
                                    v0_tt, 0, zero_points[scale_buffer_idx >> 1]
                                );
                            } else {
                                range2scale<Tin, 4, signed_quant>(vmin_t[col_idx], vmax_t[col_idx], scale0_tt);
                            }
 
                            scales[scale_buffer_idx] = scale0_tt;
 
                            float scalef = static_cast<float>(scale0_tt);
                            reciprocal_scale_t[col_idx] = scalef ? 1.0f / scalef : 0.0f;
                            zp_t[col_idx] = v0_tt;
 
                            ++scale_buffer_idx;
                        }
 
                        // quantize and pack
                        input_idx_t = input_buffer_idx;
                        for (int32_t j = 0; j < quant_row_size; ++j, input_idx_t += columns) {
                            auto input_idx_t_start = input_idx_t;
                            auto input_idx_t_end = input_idx_t + buffer_col_size;
                            col_idx = 0;
                            // leading unaligned output
                            if (input_idx_t_start & 1) {
                                v1_tt = QuantizeV(src[input_idx_t_start], reciprocal_scale_t[col_idx], zp_t[col_idx]);
                                dst[input_idx_t_start >> 1] = SetElem(v1_tt, 1, dst[input_idx_t_start >> 1]);
 
                                ++col_idx;
                                ++input_idx_t_start;
                            }
                            // aligned output
                            // TODO(fajin): use SIMD
                            for (; input_idx_t_start < input_idx_t_end - 1; col_idx += 2, input_idx_t_start += 2) {
                                v0_tt = QuantizeV(src[input_idx_t_start], reciprocal_scale_t[col_idx], zp_t[col_idx]);
                                v1_tt = QuantizeV(
                                    src[input_idx_t_start + 1], reciprocal_scale_t[col_idx + 1], zp_t[col_idx + 1]
                                );
 
                                dst[input_idx_t_start >> 1] = Pack<false>(v0_tt, v1_tt);
                            }
                            // tailing unaligned output
                            if (input_idx_t_start < input_idx_t_end) {
                                v0_tt = QuantizeV(src[input_idx_t_start], reciprocal_scale_t[col_idx], zp_t[col_idx]);
                                dst[input_idx_t_start >> 1] = SetElem(v0_tt, 0, dst[input_idx_t_start >> 1]);
                            }
                        }
 
                        input_buffer_idx += buffer_size;
                    }
 
                    input_idx += quant_block_size * columns;
                    scale_idx += columns;
                }
            }
        );
    }
 
    static void TransposeColumnWiseQuantizedPackAligned(
        const uint8_t* src_weights,      // [rows, columns / 2]
        const Tin* src_scales,           // [ceil(rows / quant_block_size), columns]
        const uint8_t* src_zero_points,  // [ceil(rows / quant_block_size), columns / 2]
        uint8_t* dst_weights,            // [columns, ceil(rows / quant_block_size), ceil(quant_block_size / 2)]
        Tin* dst_scales,                 // [columns, ceil(rows / quant_block_size)]
        uint8_t* dst_zero_points,        // [columns, ceil(ceil(rows / quant_block_size) / 2)]
        int32_t rows,
        int32_t columns,
        int32_t quant_block_size,
        MLAS_THREADPOOL* thread_pool
    )
    {
        ORT_ENFORCE(columns % 2 == 0, "Columns must be multiple of 2");
 
        auto row_quant_blk_num = (rows + quant_block_size - 1) / quant_block_size;
        auto dst_bytes_per_quant_blk = (quant_block_size * 4 + 7) / 8;
        // number of rows in transposed dst
        auto dstT_num_row = row_quant_blk_num * dst_bytes_per_quant_blk;
        auto packed_col_size = columns / 2;
 
        // weight transpose thread block is [dst_bytes_per_quant_blk, 2] on dst_Transpose.
        // Map to src it is [quant_block_size, 1]. Both in uint8_t.
        auto num_thread_blk = row_quant_blk_num * packed_col_size;
        MlasTryBatchParallel(
            thread_pool, static_cast<ptrdiff_t>(num_thread_blk),
            [&](ptrdiff_t thread_blk_idx) {
                uint8_t src0_t, src1_t;
                uint8_t dst0_t, dst1_t;
 
                auto row_thread_blk_idx = static_cast<int32_t>(thread_blk_idx / packed_col_size);
                auto col_thread_blk_idx = static_cast<int32_t>(thread_blk_idx % packed_col_size);
 
                auto dstT_row_idx = row_thread_blk_idx * dst_bytes_per_quant_blk;
                auto dstT_col_idx = col_thread_blk_idx * 2;
                auto dst_idx = dstT_col_idx * dstT_num_row + dstT_row_idx;
 
                auto src_row_idx = row_thread_blk_idx * quant_block_size;
                auto src_row_end_idx = std::min(src_row_idx + quant_block_size, rows);
                auto src_col_idx = col_thread_blk_idx;
                auto src_idx = src_row_idx * packed_col_size + src_col_idx;
                auto src_end_idx = src_row_end_idx * packed_col_size + src_col_idx;
 
                for (; src_idx < src_end_idx - packed_col_size; ++dst_idx) {
                    src0_t = src_weights[src_idx];
                    src1_t = src_weights[src_idx + packed_col_size];
                    src_idx += packed_col_size + packed_col_size;
                    Transpose<signed_quant>(src0_t, src1_t, dst0_t, dst1_t);
                    dst_weights[dst_idx] = dst0_t;
                    dst_weights[dst_idx + dstT_num_row] = dst1_t;
                }
 
                if (src_idx < src_end_idx) {
                    src0_t = src_weights[src_idx];
                    src1_t = 0;
                    Transpose<signed_quant>(src0_t, src1_t, dst0_t, dst1_t);
                    dst_weights[dst_idx] = dst0_t;
                    dst_weights[dst_idx + dstT_num_row] = dst1_t;
                }
            }
        );
 
        // Transpose scales. Thread block is [row_quant_blk_num, 1] on dst_Transpose.
        MlasTryBatchParallel(
            thread_pool, static_cast<ptrdiff_t>(columns),
            [&](ptrdiff_t thread_blk_idx) {
                auto col_thread_blk_idx = static_cast<int32_t>(thread_blk_idx);
                auto src_idx = col_thread_blk_idx;
                auto dst_idx = col_thread_blk_idx * row_quant_blk_num;
                for (int32_t i = 0; i < row_quant_blk_num; ++i, ++dst_idx, src_idx += columns) {
                    dst_scales[dst_idx] = src_scales[src_idx];
                }
            }
        );
 
        if (src_zero_points) {
            // Transpose zero points. Thread block is [ceil(row_quant_blk_num / 2), 2]
            // on dst_Transpose. Map to src it is [row_quant_blk_num, 1]. Both in uint8_t.
            auto dst_zp_row_num = (row_quant_blk_num + 1) / 2;
            MlasTryBatchParallel(
                thread_pool, static_cast<ptrdiff_t>(packed_col_size),
                [&](ptrdiff_t thread_blk_idx) {
                    uint8_t src0_t, src1_t;
                    uint8_t dst0_t, dst1_t;
 
                    auto col_thread_blk_idx = static_cast<int32_t>(thread_blk_idx);
                    auto src_idx = col_thread_blk_idx;
                    auto src_end_idx = row_quant_blk_num * packed_col_size + col_thread_blk_idx;
                    auto dst_idx = col_thread_blk_idx * 2 * dst_zp_row_num;
 
                    for (; src_idx < src_end_idx - packed_col_size; ++dst_idx) {
                        src0_t = src_zero_points[src_idx];
                        src1_t = src_zero_points[src_idx + packed_col_size];
                        Transpose<signed_quant>(src0_t, src1_t, dst0_t, dst1_t);
                        dst_zero_points[dst_idx] = dst0_t;
                        dst_zero_points[dst_idx + dst_zp_row_num] = dst1_t;
                        src_idx += packed_col_size + packed_col_size;
                    }
 
                    if (src_idx < src_end_idx) {
                        src0_t = src_zero_points[src_idx];
                        src1_t = 0;
                        Transpose<signed_quant>(src0_t, src1_t, dst0_t, dst1_t);
                        dst_zero_points[dst_idx] = dst0_t;
                        dst_zero_points[dst_idx + dst_zp_row_num] = dst1_t;
                    }
                }
            );
        }
    }
 
    static void TransposeColumnWiseQuantizedPackUnaligned(
      const uint8_t* src_weights,       // size of [ceil(rows * columns / 2)]
      const Tin* src_scales,            // [ceil(rows / quant_block_size), columns]
      const uint8_t* src_zero_points,   // size of [ceil(ceil(rows / quant_block_size) * columns / 2)]
      uint8_t *dst_weights,             // [columns, ceil(rows / quant_block_size), ceil(quant_block_size / 2)]
      Tin* dst_scales,                  // [columns, ceil(rows / quant_block_size)]
      uint8_t* dst_zero_points,         // [columns, ceil(ceil(rows / quant_block_size) / 2)]
      int32_t rows,
      int32_t columns,
      int32_t quant_block_size,
      MLAS_THREADPOOL* thread_pool)
    {
        auto row_quant_blk_num = (rows + quant_block_size - 1) / quant_block_size;
        auto dst_bytes_per_quant_blk = (quant_block_size * 4 + 7) / 8;
        // number of rows in transposed dst
        auto dstT_num_row = row_quant_blk_num * dst_bytes_per_quant_blk;
 
        // weight transpose thread block is [dst_bytes_per_quant_blk, 1] on dst_Transpose in uint8_t.
        // Map to src it is [quant_block_size, 1] in int4.
        auto num_thread_blk = row_quant_blk_num * columns;
        MlasTryBatchParallel(
            thread_pool, static_cast<ptrdiff_t>(num_thread_blk),
            [&](ptrdiff_t thread_blk_idx) {
                uint8_t src0_t, src1_t;
 
                auto row_thread_blk_idx = static_cast<int32_t>(thread_blk_idx / columns);
                auto col_thread_blk_idx = static_cast<int32_t>(thread_blk_idx % columns);
 
                auto dstT_row_idx = row_thread_blk_idx * dst_bytes_per_quant_blk;
                auto dst_idx = col_thread_blk_idx * dstT_num_row + dstT_row_idx;
 
                auto src_row_idx = row_thread_blk_idx * quant_block_size;
                auto src_row_end_idx = std::min(src_row_idx + quant_block_size, rows);
                auto src_idx = src_row_idx * columns + col_thread_blk_idx;
                auto src_end_idx = src_row_end_idx * columns + col_thread_blk_idx;
 
                for (; src_idx < src_end_idx - columns; ++dst_idx) {
                    src0_t = GetElem(src_weights[src_idx >> 1], src_idx & 1);
                    src1_t = GetElem(src_weights[(src_idx + columns) >> 1], (src_idx + columns) & 1);
                    dst_weights[dst_idx] = Pack<signed_quant>(src0_t, src1_t);
                    src_idx += columns + columns;
                }
 
                if (src_idx < src_end_idx) {
                    src0_t = GetElem(src_weights[src_idx >> 1], src_idx & 1);
                    dst_weights[dst_idx] = Pack<signed_quant>(src0_t, 0);
                }
            }
        );
 
        // Transpose scales. Thread block is [row_quant_blk_num, 1] on dst_Transpose.
        MlasTryBatchParallel(
            thread_pool, static_cast<ptrdiff_t>(columns),
            [&](ptrdiff_t thread_blk_idx) {
                auto col_thread_blk_idx = static_cast<int32_t>(thread_blk_idx);
                auto src_idx = col_thread_blk_idx;
                auto dst_idx = col_thread_blk_idx * row_quant_blk_num;
                for (int32_t i = 0; i < row_quant_blk_num; ++i, ++dst_idx, src_idx += columns) {
                    dst_scales[dst_idx] = src_scales[src_idx];
                }
            }
        );
 
        if (src_zero_points) {
            // Transpose zero points. Thread block is [ceil(row_quant_blk_num / 2), 1] on dst_Transpose in uint8_t.
            // Map to src it is [row_quant_blk_num, 1] in int4.
            auto dst_zp_row_num = (row_quant_blk_num + 1) / 2;
            MlasTryBatchParallel(
                thread_pool, static_cast<ptrdiff_t>(columns),
                [&](ptrdiff_t thread_blk_idx) {
                    uint8_t src0_t, src1_t;
 
                    auto col_thread_blk_idx = static_cast<int32_t>(thread_blk_idx);
                    auto src_idx = col_thread_blk_idx;
                    auto src_end_idx = row_quant_blk_num * columns + col_thread_blk_idx;
                    auto dst_idx = col_thread_blk_idx * dst_zp_row_num;
 
                    for (; src_idx < src_end_idx - columns; ++dst_idx) {
                        src0_t = GetElem(src_zero_points[src_idx >> 1], src_idx & 1);
                        src1_t = GetElem(src_zero_points[(src_idx + columns) >> 1], (src_idx + columns) & 1);
                        dst_zero_points[dst_idx] = Pack<signed_quant>(src0_t, src1_t);
                        src_idx += columns + columns;
                    }
 
                    if (src_idx < src_end_idx) {
                        src0_t = GetElem(src_zero_points[src_idx >> 1], src_idx & 1);
                        dst_zero_points[dst_idx] = Pack<signed_quant>(src0_t, 0);
                    }
                }
            );
        }
    }
};
 
template <typename T, int qbits>
void
MlasBlockwiseQuantMetaShape(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& meta_rows,
    int& meta_cols
    )
{
    switch (block_size) {
        case 16: {
            if (columnwise) {
                BlockwiseQuantizer<T, 16, qbits, true>::quantizeMetaShape(rows, columns, meta_rows, meta_cols);
            } else {
                BlockwiseQuantizer<T, 16, qbits, false>::quantizeMetaShape(rows, columns, meta_rows, meta_cols);
            }
            break;
        }
        case 32: {
            if (columnwise) {
                BlockwiseQuantizer<T, 32, qbits, true>::quantizeMetaShape(rows, columns, meta_rows, meta_cols);
            } else {
                BlockwiseQuantizer<T, 32, qbits, false>::quantizeMetaShape(
                                    rows, columns, meta_rows, meta_cols);
            }
            break;
        }
        case 64: {
            if (columnwise) {
                BlockwiseQuantizer<T, 64, qbits, true>::quantizeMetaShape(rows, columns, meta_rows,
                                                                      meta_cols);
            } else {
                BlockwiseQuantizer<T, 64, qbits, false>::quantizeMetaShape(rows, columns, meta_rows,
                                                                       meta_cols);
            }
            break;
        }
        case 128: {
            if (columnwise) {
                BlockwiseQuantizer<T, 128, qbits, true>::quantizeMetaShape(rows, columns, meta_rows,
                                                                      meta_cols);
            } else {
                BlockwiseQuantizer<T, 128, qbits, false>::quantizeMetaShape(rows, columns, meta_rows,
                                                                       meta_cols);
            }
            break;
        }
        case 256: {
            if (columnwise) {
                BlockwiseQuantizer<T, 256, qbits, true>::quantizeMetaShape(rows, columns, meta_rows,
                                                                      meta_cols);
            } else {
                BlockwiseQuantizer<T, 256, qbits, false>::quantizeMetaShape(rows, columns, meta_rows,
                                                                       meta_cols);
            }
            break;
        }
        default:
            meta_rows = 0;
            meta_cols = 0;
            break;
    }
}
 
 
 
template <typename T, int qbits>
void
MlasBlockwiseQuantizedShape(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& q_rows,
    int& q_cols
    )
{
    switch (block_size) {
        case 16: {
            if (columnwise) {
                BlockwiseQuantizer<T, 16, qbits, true>::quantizedShape(rows, columns, q_rows, q_cols);
            } else {
                BlockwiseQuantizer<T, 16, qbits, false>::quantizedShape(rows, columns, q_rows, q_cols);
            }
            break;
        }
        case 32: {
            if (columnwise) {
                BlockwiseQuantizer<T, 32, qbits, true>::quantizedShape(rows, columns, q_rows, q_cols);
            } else {
                BlockwiseQuantizer<T, 32, qbits, false>::quantizedShape(
                                    rows, columns, q_rows, q_cols);
            }
            break;
        }
        case 64: {
            if (columnwise) {
                BlockwiseQuantizer<T, 64, qbits, true>::quantizedShape(rows, columns, q_rows, q_cols);
            } else {
                BlockwiseQuantizer<T, 64, qbits, false>::quantizedShape(rows, columns, q_rows, q_cols);
            }
            break;
        }
        case 128: {
            if (columnwise) {
                BlockwiseQuantizer<T, 128, qbits, true>::quantizedShape(rows, columns, q_rows, q_cols);
            } else {
                BlockwiseQuantizer<T, 128, qbits, false>::quantizedShape(rows, columns, q_rows, q_cols);
            }
            break;
        }
        case 256: {
            if (columnwise) {
                BlockwiseQuantizer<T, 256, qbits, true>::quantizedShape(rows, columns, q_rows, q_cols);
            } else {
                BlockwiseQuantizer<T, 256, qbits, false>::quantizedShape(rows, columns, q_rows, q_cols);
            }
            break;
        }
        default:
            q_rows = 0;
            q_cols = 0;
            break;
    }
}
 
template
void
MlasBlockwiseQuantMetaShape<float, 2>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& meta_rows,
    int& meta_cols
    );
 
template
void
MlasBlockwiseQuantMetaShape<MLAS_FP16, 2>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& meta_rows,
    int& meta_cols
    );
 
template void
MlasBlockwiseQuantMetaShape<float, 4>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& meta_rows,
    int& meta_cols
);
 
template
void
MlasBlockwiseQuantMetaShape<MLAS_FP16, 4>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& meta_rows,
    int& meta_cols
    );
 
    template
void
MlasBlockwiseQuantMetaShape<float, 8>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& meta_rows,
    int& meta_cols
    );
 
template
void
MlasBlockwiseQuantMetaShape<MLAS_FP16, 8>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& meta_rows,
    int& meta_cols
    );
 
template
void
MlasBlockwiseQuantizedShape<float, 2>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& q_rows,
    int& q_cols
    );
 
template
void
MlasBlockwiseQuantizedShape<MLAS_FP16, 2>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& q_rows,
    int& q_cols
    );
 
template
void
MlasBlockwiseQuantizedShape<float, 4>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& q_rows,
    int& q_cols
    );
 
template void
MlasBlockwiseQuantizedShape<MLAS_FP16, 4>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& q_rows,
    int& q_cols
    );
 
template
void
MlasBlockwiseQuantizedShape<float, 8>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& q_rows,
    int& q_cols
    );
 
template
void
MlasBlockwiseQuantizedShape<MLAS_FP16, 8>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int& q_rows,
    int& q_cols
    );
 
template <int qbits>
void MLASCALL
MlasBlockwiseQuantizedBufferSizes(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    size_t& q_data_size_in_bytes,
    size_t& q_scale_num_elements,
    size_t* q_zero_point_size_in_bytes
)
{
    q_data_size_in_bytes = q_scale_num_elements = 0;
    if (q_zero_point_size_in_bytes) {
        *q_zero_point_size_in_bytes = 0;
    }
 
    switch (block_size) {
        case 16:
            if (columnwise) {
                BlockwiseQuantizer<float, 16, qbits, true>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            } else {
                BlockwiseQuantizer<float, 16, qbits, false>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            }
            break;
 
        case 32:
            if (columnwise) {
                BlockwiseQuantizer<float, 32, qbits, true>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            } else {
                BlockwiseQuantizer<float, 32, qbits, false>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            }
            break;
 
        case 64:
            if (columnwise) {
                BlockwiseQuantizer<float, 64, qbits, true>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            } else {
                BlockwiseQuantizer<float, 64, qbits, false>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            }
            break;
 
        case 128:
            if (columnwise) {
                BlockwiseQuantizer<float, 128, qbits, true>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            } else {
                BlockwiseQuantizer<float, 128, qbits, false>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            }
            break;
 
        case 256:
            if (columnwise) {
                BlockwiseQuantizer<float, 256, qbits, true>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            } else {
                BlockwiseQuantizer<float, 256, qbits, false>::quantizedBufferSizes(
                    rows, columns, q_data_size_in_bytes, q_scale_num_elements, q_zero_point_size_in_bytes
                );
            }
            break;
 
        default:
            ORT_ENFORCE(false, "Only block sizes 16, 32, 64, 128, 256 are supported for buffer size calculation, got: ",
                        block_size);
            break;
    }
}
 
template
void MLASCALL
MlasBlockwiseQuantizedBufferSizes<2>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    size_t& q_data_size_in_bytes,
    size_t& q_scale_num_elements,
    size_t* q_zero_point_size_in_bytes
);
 
template
void MLASCALL
MlasBlockwiseQuantizedBufferSizes<4>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    size_t& q_data_size_in_bytes,
    size_t& q_scale_num_elements,
    size_t* q_zero_point_size_in_bytes
);
 
template
void MLASCALL
MlasBlockwiseQuantizedBufferSizes<8>(
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    size_t& q_data_size_in_bytes,
    size_t& q_scale_num_elements,
    size_t* q_zero_point_size_in_bytes
);
 
template <typename T, int qbits>
void
MlasQuantizeBlockwise(
    uint8_t* dst,
    T* scales,
    uint8_t* zero_points,
    const T* src,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int leading_dimension,
    MLAS_THREADPOOL* thread_pool
    )
{
    switch (block_size) {
        case 16:
            if (columnwise) {
                BlockwiseQuantizer<T, 16, qbits, true>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            } else {
                BlockwiseQuantizer<T, 16, qbits, false>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            }
            break;
 
        case 32:
            if (columnwise) {
                BlockwiseQuantizer<T, 32, qbits, true>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            } else {
                BlockwiseQuantizer<T, 32, qbits, false>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            }
            break;
 
        case 64:
            if (columnwise) {
                BlockwiseQuantizer<T, 64, qbits, true>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            } else {
                BlockwiseQuantizer<T, 64, qbits, false>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            }
            break;
 
        case 128:
            if (columnwise) {
                BlockwiseQuantizer<T, 128, qbits, true>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            } else {
                BlockwiseQuantizer<T, 128, qbits, false>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            }
            break;
 
        case 256:
            if (columnwise) {
                BlockwiseQuantizer<T, 256, qbits, true>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            } else {
                BlockwiseQuantizer<T, 256, qbits, false>::quantizeAndTranspose(
                    dst, scales, zero_points, src, rows, columns, leading_dimension, thread_pool);
            }
            break;
 
        default:
            ORT_ENFORCE(false, "Only block sizes 16, 32, 64, 128, 256 are supported for quantization, got: ",
                        block_size);
            break;
    }
}
 
template
void
MlasQuantizeBlockwise<float, 2>(
    uint8_t* dst,
    float* scales,
    uint8_t* zero_points,
    const float* src,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int leading_dimension,
    MLAS_THREADPOOL* thread_pool
    );
 
template
void
MlasQuantizeBlockwise<MLAS_FP16, 2>(
    uint8_t* dst,
    MLAS_FP16* scales,
    uint8_t* zero_points,
    const MLAS_FP16* src,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int leading_dimension,
    MLAS_THREADPOOL* thread_pool
    );
 
template
void
MlasQuantizeBlockwise<float, 4>(
    uint8_t* dst,
    float* scales,
    uint8_t* zero_points,
    const float* src,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int leading_dimension,
    MLAS_THREADPOOL* thread_pool
    );
 
template
void
MlasQuantizeBlockwise<MLAS_FP16, 4>(
    uint8_t* dst,
    MLAS_FP16* scales,
    uint8_t* zero_points,
    const MLAS_FP16* src,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    int leading_dimension,
    MLAS_THREADPOOL* thread_pool
    );
 
    template
    void
    MlasQuantizeBlockwise<float, 8>(
        uint8_t* dst,
        float* scales,
        uint8_t* zero_points,
        const float* src,
        int block_size,
        bool columnwise,
        int rows,
        int columns,
        int leading_dimension,
        MLAS_THREADPOOL* thread_pool
        );
 
    template
    void
    MlasQuantizeBlockwise<MLAS_FP16, 8>(
        uint8_t* dst,
        MLAS_FP16* scales,
        uint8_t* zero_points,
        const MLAS_FP16* src,
        int block_size,
        bool columnwise,
        int rows,
        int columns,
        int leading_dimension,
        MLAS_THREADPOOL* thread_pool
        );
 
template <typename T, int qbits>
void
MlasDequantizeBlockwise(
    T* dst,
    const uint8_t* src,
    const T* scales,
    const uint8_t* zero_points,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
    )
{
    switch (block_size) {
        case 16:
            if (columnwise) {
                BlockwiseQuantizer<T, 16, qbits, true>::dequantize(dst, src, scales, zero_points, rows,
                                                               columns, thread_pool);
            } else {
                BlockwiseQuantizer<T, 16, qbits, false>::dequantize(dst, src, scales, zero_points, rows,
                                                                columns, thread_pool);
            }
            break;
        case 32:
            if (columnwise) {
                BlockwiseQuantizer<T, 32, qbits, true>::dequantize(dst, src, scales, zero_points, rows,
                                                               columns, thread_pool);
            } else {
                BlockwiseQuantizer<T, 32, qbits, false>::dequantize(dst, src, scales, zero_points, rows,
                                                                columns, thread_pool);
            }
            break;
        case 64:
            if (columnwise) {
                BlockwiseQuantizer<T, 64, qbits, true>::dequantize(dst, src, scales, zero_points, rows,
                                                               columns, thread_pool);
            } else {
                BlockwiseQuantizer<T, 64, qbits, false>::dequantize(dst, src, scales, zero_points, rows,
                                                                columns, thread_pool);
            }
            break;
        case 128:
            if (columnwise) {
                BlockwiseQuantizer<T, 128, qbits, true>::dequantize(dst, src, scales, zero_points, rows,
                                                                columns, thread_pool);
            } else {
                BlockwiseQuantizer<T, 128, qbits, false>::dequantize(dst, src, scales, zero_points,
                                                                 rows, columns, thread_pool);
            }
            break;
        case 256:
            if (columnwise) {
                BlockwiseQuantizer<T, 256, qbits, true>::dequantize(dst, src, scales, zero_points, rows,
                                                                columns, thread_pool);
            } else {
                BlockwiseQuantizer<T, 256, qbits, false>::dequantize(dst, src, scales, zero_points,
                                                                 rows, columns, thread_pool);
            }
            break;
        default:
            ORT_ENFORCE(false, "Only block sizes 16, 32, 64, 128, 256 are supported for dequantization, got: ",
                        block_size);
            break;
    }
}
 
template void
MlasDequantizeBlockwise<float, 2>(
    float* dst,
    const uint8_t* src,
    const float* scales,
    const uint8_t* zero_points,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasDequantizeBlockwise<MLAS_FP16, 2>(
    MLAS_FP16* dst,
    const uint8_t* src,
    const MLAS_FP16* scales,
    const uint8_t* zero_points,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasDequantizeBlockwise<float, 4>(
    float* dst,
    const uint8_t* src,
    const float* scales,
    const uint8_t* zero_points,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasDequantizeBlockwise<MLAS_FP16, 4>(
    MLAS_FP16* dst,
    const uint8_t* src,
    const MLAS_FP16* scales,
    const uint8_t* zero_points,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasDequantizeBlockwise<float, 8>(
    float* dst,
    const uint8_t* src,
    const float* scales,
    const uint8_t* zero_points,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasDequantizeBlockwise<MLAS_FP16, 8>(
    MLAS_FP16* dst,
    const uint8_t* src,
    const MLAS_FP16* scales,
    const uint8_t* zero_points,
    int block_size,
    bool columnwise,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
//
// Blockwise dequantization with floating point zero points. The per-block
// span kernel is platform dispatched on x64; every element computes
// float(q) * scale + (-scale * zp), matching the arithmetic the CPU
// MatMulNBits operator historically used for this path.
//
 
void
MLASCALL
MlasDequantizeBlockwise2BitsKernel(
    float* Output,
    const uint8_t* PackedData,
    size_t N,
    float Scale,
    float ZeroPointAdjust
)
{
    for (size_t i = 0; i < N; i++) {
        const uint8_t packed = PackedData[i >> 2];
        const float q = static_cast<float>((packed >> (2 * (i & 3))) & 0x3);
        Output[i] = q * Scale + ZeroPointAdjust;
    }
}
 
template <typename ElementT, typename ZeroPointT, int qbits>
void
MlasDequantizeBlockwiseFpZeroPoint(
    ElementT* dst,
    const uint8_t* src,
    const ElementT* scales,
    const ZeroPointT* zero_points,
    int block_size,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
)
{
    static_assert(qbits == 2, "only 2 bit is implemented");
    static_assert(std::is_same_v<ElementT, float>, "only float dequantized elements are implemented");
 
    // The packed stream is columnwise: elements in a block come from the same column.
    // This routine only needs block_size to be a multiple of 4 so each block starts byte
    // aligned in the packed stream; the MatMulNBits op passes a power of two >= 16, which
    // satisfies that.
 
    const int k_blocks = (rows + block_size - 1) / block_size;
    const size_t src_col_stride = static_cast<size_t>(k_blocks) * block_size / 4;
 
    MLAS_DEQUANTIZE_BLOCKWISE_2BITS_KERNEL* kernel =
#if defined(MLAS_TARGET_AMD64)
        GetMlasPlatform().DequantizeBlockwise2BitsKernel;
#else
        MlasDequantizeBlockwise2BitsKernel;
#endif
 
    MlasTryBatchParallel(
        thread_pool, static_cast<ptrdiff_t>(columns),
        [&](ptrdiff_t n) {
            const uint8_t* src_col = src + static_cast<size_t>(n) * src_col_stride;
            float* dst_col = dst + static_cast<size_t>(n) * rows;
            const size_t block_base = static_cast<size_t>(n) * k_blocks;
            for (int kb = 0; kb < k_blocks; kb++) {
                const int k_start = kb * block_size;
                const size_t count = static_cast<size_t>(std::min(block_size, rows - k_start));
                const float scale = static_cast<float>(scales[block_base + kb]);
                float zp = 0.0f;
                if (zero_points != nullptr) {
                    if constexpr (std::is_same_v<ZeroPointT, MLAS_FP16>) {
                        zp = zero_points[block_base + kb].ToFloat();
                    } else {
                        zp = static_cast<float>(zero_points[block_base + kb]);
                    }
                }
                kernel(dst_col + k_start,
                       src_col + static_cast<size_t>(kb) * (block_size / 4),
                       count, scale, -scale * zp);
            }
        });
}
 
template void
MlasDequantizeBlockwiseFpZeroPoint<float, float, 2>(
    float* dst,
    const uint8_t* src,
    const float* scales,
    const float* zero_points,
    int block_size,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasDequantizeBlockwiseFpZeroPoint<float, MLAS_FP16, 2>(
    float* dst,
    const uint8_t* src,
    const float* scales,
    const MLAS_FP16* zero_points,
    int block_size,
    int rows,
    int columns,
    MLAS_THREADPOOL* thread_pool
);
 
template <typename Tin, int qbits>
bool
MlasQDQQuantizeBlockwise(
    const Tin* src,
    Tin* scales,
    uint8_t* zero_points,
    uint8_t* dst,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
)
{
    ORT_ENFORCE(MlasQDQBlockwiseShapeIsValid(rows, columns, quant_block_size, qbits, columnwise, false),
                "QDQ blockwise quantization shape exceeds the int32 index range.");
    if (columnwise) {
        if (zero_points) {
            BlockwiseQDQQuantizer<Tin, qbits, false>::QuantizeColumnWise(
                src, scales, zero_points, dst, rows, columns, quant_block_size, thread_pool
            );
            return false;
        } else {
            BlockwiseQDQQuantizer<Tin, qbits, true>::QuantizeColumnWise(
                src, scales, zero_points, dst, rows, columns, quant_block_size, thread_pool
            );
            return true;
        }
    } else {
        ORT_THROW("Row-wise MlasQDQQuantizeBlockwise is not implemented");
    }
}
 
template bool
MlasQDQQuantizeBlockwise<float, 4>(
    const float* src,
    float* scales,
    uint8_t* zero_points,
    uint8_t* dst,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template bool
MlasQDQQuantizeBlockwise<float, 2>(
    const float* src,
    float* scales,
    uint8_t* zero_points,
    uint8_t* dst,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template bool
MlasQDQQuantizeBlockwise<MLAS_FP16, 4>(
    const MLAS_FP16* src,
    MLAS_FP16* scales,
    uint8_t* zero_points,
    uint8_t* dst,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template bool
MlasQDQQuantizeBlockwise<MLAS_FP16, 2>(
    const MLAS_FP16* src,
    MLAS_FP16* scales,
    uint8_t* zero_points,
    uint8_t* dst,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template <typename Tin, int qbits, bool signed_quant>
void
MlasQDQTransposeBlockwiseQuantized(
    const uint8_t* src_weights,
    const Tin* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    Tin* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
)
{
    ORT_ENFORCE(MlasQDQBlockwiseShapeIsValid(rows, columns, quant_block_size, qbits, columnwise, true),
                "QDQ blockwise quantization shape exceeds the int32 index range.");
    if (columnwise) {
        BlockwiseQDQQuantizer<Tin, qbits, signed_quant>::TransposeColumnWiseQuantized(
            src_weights, src_scales, src_zero_points, dst_weights, dst_scales, dst_zero_points,
            rows, columns, quant_block_size, thread_pool
        );
    } else {
        ORT_THROW("Row-wise MlasQDQTransposeBlockwiseQuantized is not implemented");
    }
}
 
template void
MlasQDQTransposeBlockwiseQuantized<float, 2, true>(
    const uint8_t* src_weights,
    const float* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    float* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<float, 2, false>(
    const uint8_t* src_weights,
    const float* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    float* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<float, 4, true>(
    const uint8_t* src_weights,
    const float* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    float* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<float, 4, false>(
    const uint8_t* src_weights,
    const float* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    float* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<MLAS_FP16, 4, true>(
    const uint8_t* src_weights,
    const MLAS_FP16* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    MLAS_FP16* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<MLAS_FP16, 4, false>(
    const uint8_t* src_weights,
    const MLAS_FP16* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    MLAS_FP16* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<float, 8, true>(
    const uint8_t* src_weights,
    const float* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    float* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<float, 8, false>(
    const uint8_t* src_weights,
    const float* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    float* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<MLAS_FP16, 8, true>(
    const uint8_t* src_weights,
    const MLAS_FP16* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    MLAS_FP16* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<MLAS_FP16, 8, false>(
    const uint8_t* src_weights,
    const MLAS_FP16* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    MLAS_FP16* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<MLAS_FP16, 2, true>(
    const uint8_t* src_weights,
    const MLAS_FP16* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    MLAS_FP16* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);
 
template void
MlasQDQTransposeBlockwiseQuantized<MLAS_FP16, 2, false>(
    const uint8_t* src_weights,
    const MLAS_FP16* src_scales,
    const uint8_t* src_zero_points,
    uint8_t* dst_weights,
    MLAS_FP16* dst_scales,
    uint8_t* dst_zero_points,
    bool columnwise,
    int rows,
    int columns,
    int quant_block_size,
    MLAS_THREADPOOL* thread_pool
);