-
Notifications
You must be signed in to change notification settings - Fork 188
/
test_quant_primitives.py
843 lines (758 loc) · 28.3 KB
/
test_quant_primitives.py
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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# mypy: ignore-errors
# This test takes a long time to run
import unittest
import torch
from torchao.dtypes.utils import is_device
from torchao.quantization.quant_primitives import (
MappingType,
ZeroPointDomain,
choose_qparams_affine,
dequantize_affine,
fake_quantize_affine,
fake_quantize_affine_cachemask,
quantize_affine,
)
# TODO: remove test for utils?
from torchao.quantization.utils import (
get_group_qparams_symmetric,
groupwise_affine_dequantize_tensor_from_qparams,
groupwise_affine_quantize_tensor_from_qparams,
quantize_activation_per_token_absmax,
)
from torchao.utils import (
TORCH_VERSION_AT_LEAST_2_3,
TORCH_VERSION_AT_LEAST_2_4,
TORCH_VERSION_AT_LEAST_2_5,
TORCH_VERSION_AT_LEAST_2_6,
is_fbcode,
)
_SEED = 1234
torch.manual_seed(_SEED)
# Helper function to run a function twice
# and verify that the result is the same.
# Adds some verification to avoid side effects.
# NOTE:
# - Does not verify the args and kwargs are unchanged.
# - Assumes the output is a single Tensor
def check_idempotent(self, fn, *args, **kwargs):
output0 = fn(*args, **kwargs)
assert torch.is_tensor(output0)
output1 = fn(*args, **kwargs)
self.assertTrue(
torch.equal(output0, output1), f"Expected given function {fn} to be idempotent."
)
return output1
# Legacy tinygemm ops
def _get_groupwise_affine_qparams(
w,
n_bit=4,
groupsize=128,
dtype=torch.bfloat16,
zero_point_domain=ZeroPointDomain.FLOAT,
):
if groupsize > w.shape[-1]:
groupsize = w.shape[-1]
assert groupsize > 1
assert w.shape[-1] % groupsize == 0
assert w.dim() == 2
to_quant = w.reshape(-1, groupsize)
# assert torch.isnan(to_quant).sum() == 0
max_val = to_quant.amax(dim=1, keepdim=True)
min_val = to_quant.amin(dim=1, keepdim=True)
max_int = 2**n_bit - 1
quant_min = 0
quant_max = max_int
scales = (max_val - min_val).clamp(min=1e-6) / max_int
if zero_point_domain == ZeroPointDomain.FLOAT:
zeros = min_val + scales * (2 ** (n_bit - 1))
zeros = zeros.to(dtype=dtype).reshape(w.shape[0], -1)
else:
zeros = quant_min - torch.round(min_val / scales)
zeros = torch.clamp(zeros, quant_min, quant_max)
zeros = zeros.to(dtype=dtype).reshape(w.shape[0], -1)
scales = scales.to(dtype=dtype).reshape(w.shape[0], -1)
return scales, zeros
def _groupwise_affine_quantize_tensor_from_qparams(
w, scales, zeros, n_bit=4, groupsize=128, zero_point_domain=ZeroPointDomain.FLOAT
):
assert groupsize > 1
assert n_bit == 4
# needed for GPTQ single column quantize
if groupsize > w.shape[-1] and scales.shape[-1] == 1:
groupsize = w.shape[-1]
assert w.shape[-1] % groupsize == 0
assert w.dim() == 2
to_quant = w.reshape(-1, groupsize)
# assert torch.isnan(to_quant).sum() == 0
scales = scales.reshape(-1, 1)
zeros = zeros.reshape(-1, 1)
max_int = 2**n_bit - 1
min_int = 0
if zero_point_domain == ZeroPointDomain.FLOAT:
min_val = zeros - scales * (2 ** (n_bit - 1))
w_int4x8 = (
to_quant.sub(min_val)
.div(scales)
.round()
.clamp_(min_int, max_int)
.to(torch.int32)
.reshape_as(w)
)
else:
w_int4x8 = (
to_quant.div(scales)
.round()
.add(zeros)
.clamp_(min_int, max_int)
.to(torch.int32)
.reshape_as(w)
)
if TORCH_VERSION_AT_LEAST_2_5:
if not (is_device(w.device.type, "cpu") and TORCH_VERSION_AT_LEAST_2_6):
w_int4x8 = (w_int4x8[::, ::2] << 4 | w_int4x8[::, 1::2]).to(torch.uint8)
return w_int4x8
def _groupwise_affine_dequantize_tensor_from_qparams(
w_int4x8,
scales,
zeros,
n_bit=4,
groupsize=128,
zero_point_domain=ZeroPointDomain.FLOAT,
):
assert groupsize > 1
# needed for GPTQ single column dequantize
if groupsize > w_int4x8.shape[-1] and scales.shape[-1] == 1:
groupsize = w_int4x8.shape[-1]
assert w_int4x8.shape[-1] % groupsize == 0
assert w_int4x8.dim() == 2
w_int4x8_grouped = w_int4x8.reshape(-1, groupsize)
scales = scales.reshape(-1, 1)
zeros = zeros.reshape(-1, 1)
if zero_point_domain == ZeroPointDomain.FLOAT:
w_dq = (
w_int4x8_grouped.sub(2 ** (n_bit - 1))
.mul(scales)
.add(zeros)
.reshape_as(w_int4x8)
)
else:
w_dq = w_int4x8_grouped.sub(zeros).mul(scales).reshape_as(w_int4x8)
return w_dq
class TestQuantPrimitives(unittest.TestCase):
SEED = 123
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_3, "skipping when torch version is 2.3 or lower"
)
def test_get_group_qparams_symmetric(self):
"""
Test that `get_group_qparams_symmetric` produces the exact same scales as
`PerChannelMinMaxObserver._calculate_qparams`.
"""
n_bit = 4
qmin = -(2 ** (n_bit - 1))
qmax = 2 ** (n_bit - 1) - 1
groupsize = 256
torch.manual_seed(self.SEED)
weight = torch.randn(100, 256).to(torch.float16)
# calculate observer scales
obs = torch.ao.quantization.PerChannelMinMaxObserver(
ch_axis=0,
qscheme=torch.per_channel_symmetric,
quant_min=qmin,
quant_max=qmax,
# This is needed to ensure `min_val` and `max_val` are fp16,
# otherwise they default to fp32 and the qparams will be slightly off
factory_kwargs={"dtype": torch.float16},
)
obs(weight)
(scale_obs, _) = obs.calculate_qparams()
scale_obs = scale_obs.reshape(weight.shape[0], -1)
# assert that scales are identical
(scale_ao, _) = get_group_qparams_symmetric(
weight, n_bit, groupsize, precision=torch.float16
)
torch.testing.assert_close(scale_obs, scale_ao, rtol=0, atol=0)
def test_choose_qparams_group_sym(self):
"""Note: groupwise asymmetric quant is using a different way of computing zero_points, so
we don't include it here. We may just replace it with per block quant
"""
input = torch.randn(10, 10)
mapping_type = MappingType.SYMMETRIC
dtype = torch.int8
block_size = (1, 2)
eps = torch.finfo(torch.float32).eps
precision = torch.float32
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
eps=eps,
scale_dtype=precision,
zero_point_dtype=precision,
)
scale_ref, zp_ref = get_group_qparams_symmetric(
input, n_bit=8, groupsize=2, precision=precision, mapping_type=mapping_type
)
self.assertTrue(torch.equal(scale, scale_ref))
self.assertTrue(torch.equal(zero_point, zp_ref))
def test_choose_qparams_group_sym_no_clipping_err(self):
"""
Test the added MappingType.SYMMETRIC_NO_CLIPPING_ERR
"""
input = torch.randn(10, 10)
mapping_type = MappingType.SYMMETRIC_NO_CLIPPING_ERR
dtype = torch.int8
block_size = (1, 2)
eps = torch.finfo(torch.float32).eps
precision = torch.float32
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
eps=eps,
scale_dtype=precision,
zero_point_dtype=precision,
)
scale_ref, zp_ref = get_group_qparams_symmetric(
input, n_bit=8, groupsize=2, precision=precision, mapping_type=mapping_type
)
self.assertTrue(torch.equal(scale, scale_ref))
self.assertTrue(torch.equal(zero_point, zp_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_3, "skipping when torch version is 2.3 or lower"
)
@unittest.skipIf(is_fbcode(), "broken in fbcode")
def test_choose_qparams_token_asym(self):
input = torch.randn(10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (1, 10)
if TORCH_VERSION_AT_LEAST_2_6:
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
eps=torch.finfo(torch.float32).eps,
scale_dtype=torch.float64,
zero_point_dtype=torch.int64,
)
else:
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
eps=torch.finfo(torch.float32).eps,
)
scale_ref, zp_ref = (
torch.ops.quantized_decomposed.choose_qparams_per_token_asymmetric(
input, dtype
)
)
scale_ref = scale_ref.squeeze()
zp_ref = zp_ref.squeeze()
torch.testing.assert_close(scale, scale_ref, atol=10e-3, rtol=10e-3)
self.assertTrue(torch.equal(zero_point, zp_ref))
@unittest.skipIf(is_fbcode(), "broken in fbcode")
def test_choose_qparams_tensor_asym(self):
input = torch.randn(10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (10, 10)
eps = torch.finfo(torch.float32).eps
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype, eps=eps
)
quant_min = -128
quant_max = 127
scale_ref, zp_ref = torch.ops.quantized_decomposed.choose_qparams(
input, quant_min, quant_max, eps, dtype
)
scale_ref = scale_ref.squeeze()
zp_ref = zp_ref.squeeze()
self.assertTrue(torch.equal(scale, scale_ref))
self.assertTrue(torch.equal(zero_point, zp_ref))
@unittest.skipIf(is_fbcode(), "broken in fbcode")
def test_choose_qparams_tensor_sym(self):
input = torch.randn(10, 10)
mapping_type = MappingType.SYMMETRIC
dtype = torch.int8
block_size = (10, 10)
eps = torch.finfo(torch.float32).eps
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype, eps=eps
)
quant_min = -128
quant_max = 127
scale_ref, zp_ref = torch.ops.quantized_decomposed.choose_qparams_symmetric(
input, quant_min, quant_max, eps, dtype
)
scale_ref = scale_ref.squeeze()
zp_ref = zp_ref.squeeze()
self.assertTrue(torch.equal(scale, scale_ref))
self.assertTrue(torch.equal(zero_point, zp_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
def test_quantize_activation_per_token_abs_max(self):
input = torch.randn(10, 10)
quantized_ref, scale_ref = quantize_activation_per_token_absmax(input)
mapping_type = MappingType.SYMMETRIC
block_size = list(input.shape)
for i in range(len(block_size) - 1):
block_size[i] = 1
dtype = torch.int8
eps = 1e-5
quant_min = -127
quant_max = 127
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
quant_min,
quant_max,
eps=eps,
scale_dtype=torch.float,
)
quantized = quantize_affine(
input, block_size, scale, zero_point, dtype, quant_min, quant_max
)
self.assertTrue(torch.equal(quantized, quantized_ref))
self.assertTrue(torch.equal(scale, scale_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
def test_quantize_activation_per_token_abs_max_zero_input(self):
input = torch.zeros(10, 10)
# make sure it still works
quantized_ref, scale_ref = quantize_activation_per_token_absmax(input)
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
def test_quantize_activation_per_token_abs_max_dtype(self):
input = torch.zeros(10, 10, dtype=torch.bfloat16)
quantized_ref, scale_ref = quantize_activation_per_token_absmax(input)
self.assertTrue(scale_ref.dtype, torch.bfloat16)
input = torch.zeros(10, 10, dtype=torch.float32)
quantized_ref, scale_ref = quantize_activation_per_token_absmax(input)
self.assertTrue(scale_ref.dtype, torch.float32)
input = torch.zeros(10, 10, dtype=torch.float16)
quantized_ref, scale_ref = quantize_activation_per_token_absmax(input)
self.assertTrue(scale_ref.dtype, torch.float32)
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
@unittest.skipIf(is_fbcode(), "broken in fbcode")
def test_quantize_dequantize_group_sym(self):
input = torch.randn(10, 10)
mapping_type = MappingType.SYMMETRIC
dtype = torch.int8
block_size = (1, 2)
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype, eps=torch.finfo(torch.float32).eps
)
quantized = quantize_affine(input, block_size, scale, zero_point, dtype)
dequantized = check_idempotent(
self,
dequantize_affine,
quantized,
block_size,
scale,
zero_point,
dtype,
output_dtype=torch.float32,
)
group_size = 2
quant_min = -128
quant_max = 127
quantized_ref = torch.ops.quantized_decomposed.quantize_per_channel_group(
input, scale, zero_point, quant_min, quant_max, torch.int8, group_size
)
dequantized_ref = torch.ops.quantized_decomposed.dequantize_per_channel_group(
quantized_ref,
scale,
zero_point,
quant_min,
quant_max,
torch.int8,
group_size,
output_dtype=torch.float32,
)
self.assertTrue(torch.equal(quantized, quantized_ref))
self.assertTrue(torch.equal(dequantized, dequantized_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
@unittest.skipIf(is_fbcode(), "broken in fbcode")
def test_quantize_dequantize_channel_asym(self):
input = torch.randn(10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (10, 1)
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype, eps=torch.finfo(torch.float32).eps
)
output_dtype = torch.float32
quantized = quantize_affine(input, block_size, scale, zero_point, dtype)
dequantized = check_idempotent(
self,
dequantize_affine,
quantized,
block_size,
scale,
zero_point,
dtype,
output_dtype=output_dtype,
)
axis = 1
quant_min = -128
quant_max = 127
quantized_ref = torch.ops.quantized_decomposed.quantize_per_channel(
input, scale, zero_point, axis, quant_min, quant_max, torch.int8
)
dequantized_ref = torch.ops.quantized_decomposed.dequantize_per_channel(
quantized_ref,
scale,
zero_point,
axis,
quant_min,
quant_max,
torch.int8,
out_dtype=output_dtype,
)
self.assertTrue(torch.equal(quantized, quantized_ref))
self.assertTrue(torch.equal(dequantized, dequantized_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
@unittest.skipIf(is_fbcode(), "broken in fbcode")
def test_quantize_dequantize_tensor_asym(self):
input = torch.randn(10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (10, 10)
output_dtype = torch.float32
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype, eps=torch.finfo(torch.float32).eps
)
quantized = quantize_affine(input, block_size, scale, zero_point, dtype)
dequantized = check_idempotent(
self,
dequantize_affine,
quantized,
block_size,
scale,
zero_point,
dtype,
output_dtype=output_dtype,
)
quant_min = -128
quant_max = 127
quantized_ref = torch.ops.quantized_decomposed.quantize_per_tensor(
input, scale, zero_point, quant_min, quant_max, torch.int8
)
dequantized_ref = torch.ops.quantized_decomposed.dequantize_per_tensor(
quantized_ref,
scale,
zero_point,
quant_min,
quant_max,
torch.int8,
out_dtype=output_dtype,
)
self.assertTrue(torch.equal(quantized, quantized_ref))
self.assertTrue(torch.equal(dequantized, dequantized_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
@unittest.skipIf(is_fbcode(), "broken in fbcode")
def test_quantize_dequantize_channel_asym_4d(self):
input = torch.randn(3, 3, 10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (3, 3, 1, 10)
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype, eps=torch.finfo(torch.float32).eps
)
quantized = quantize_affine(input, block_size, scale, zero_point, dtype)
dequantized = check_idempotent(
self,
dequantize_affine,
quantized,
block_size,
scale,
zero_point,
dtype,
output_dtype=torch.float32,
)
axis = 2
quant_min = -128
quant_max = 127
quantized_ref = torch.ops.quantized_decomposed.quantize_per_channel(
input, scale, zero_point, axis, quant_min, quant_max, torch.int8
)
dequantized_ref = torch.ops.quantized_decomposed.dequantize_per_channel(
quantized_ref,
scale,
zero_point,
axis,
quant_min,
quant_max,
torch.int8,
out_dtype=torch.float32,
)
self.assertTrue(torch.equal(quantized, quantized_ref))
self.assertTrue(torch.equal(dequantized, dequantized_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_3, "skipping when torch version is 2.3 or lower"
)
def test_quantize_dequantize_channel_asym_4d_multi_dim_reduction(self):
input = torch.randn(3, 3, 10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (3, 3, 2, 2)
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype, eps=torch.finfo(torch.float32).eps
)
quantized = quantize_affine(input, block_size, scale, zero_point, dtype)
dequantized = check_idempotent(
self,
dequantize_affine,
quantized,
block_size,
scale,
zero_point,
dtype,
output_dtype=torch.float32,
)
# we don't have corresponding ops in existing primitives, so just make sure it runs and it's close to float
torch.testing.assert_close(dequantized, input, rtol=2, atol=0.02)
def test_choose_qparams_tensor_asym_eps(self):
input = torch.zeros(10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (10, 10)
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype
)
eps = torch.finfo(torch.float32).eps
self.assertEqual(scale, eps)
@unittest.skipIf(
not torch.cuda.is_available(), "skipping when cuda is not available"
)
def test_get_group_qparams_symmetric_memory(self):
"""Check the memory usage of the op"""
weight = torch.randn(1024, 1024).to(device="cuda")
original_mem_use = torch.cuda.memory_allocated()
n_bit = 4
groupsize = 128
(scale_ao, _) = get_group_qparams_symmetric(weight, n_bit, groupsize)
after_choose_qparams_mem_use = torch.cuda.memory_allocated()
self.assertTrue(after_choose_qparams_mem_use < 1.2 * original_mem_use)
def test_raises(self):
"""Make sure some errors are raised when user requested an unsupported type of quantization"""
input = torch.randn(10, 10)
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (10, 10)
scale, zero_point = choose_qparams_affine(
input, mapping_type, block_size, dtype
)
# make sure we can't quantize int32 tensors:
with self.assertRaisesRegex(AssertionError, "Unsupported input dtype:"):
_ = quantize_affine(
input.to(torch.int32), block_size, scale, zero_point, dtype
)
# block_size and scale/zero_point shape mismatch
block_size = (1, 1)
with self.assertRaisesRegex(RuntimeError, "is invalid for input of size 1"):
_ = quantize_affine(input, block_size, scale, zero_point, dtype)
def test_not_preserve_zero_not_supported(self):
"""Making sure preserve_zero == False is not supported for symmetric quant"""
input = torch.randn(10, 256)
n_bit = 4
mapping_type = MappingType.SYMMETRIC
dtype = torch.int8
block_size = (1, 128)
quant_min = 0
quant_max = 2**n_bit - 1
eps = 1e-6
scale_dtype = torch.bfloat16
zero_point_dtype = torch.bfloat16
with self.assertRaisesRegex(
ValueError,
"preserve_zero == False is not supported for symmetric quantization",
):
choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
quant_min,
quant_max,
eps,
scale_dtype=scale_dtype,
zero_point_dtype=zero_point_dtype,
preserve_zero=False,
)
def test_get_groupwise_affine_qparams(self):
input = torch.randn(10, 256)
n_bit = 4
zero_point_domains = [ZeroPointDomain.FLOAT, ZeroPointDomain.INT]
mapping_type = MappingType.ASYMMETRIC
dtype = torch.int8
block_size = (1, 128)
quant_min = 0
quant_max = 2**n_bit - 1
eps = 1e-6
scale_dtype = torch.bfloat16
zero_point_dtype = torch.bfloat16
for zero_point_domain in zero_point_domains:
scale_ref, zero_point_ref = _get_groupwise_affine_qparams(
input,
n_bit=n_bit,
groupsize=128,
dtype=torch.bfloat16,
zero_point_domain=zero_point_domain,
)
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
quant_min,
quant_max,
eps,
scale_dtype=scale_dtype,
zero_point_dtype=zero_point_dtype,
preserve_zero=zero_point_domain == ZeroPointDomain.INT,
zero_point_domain=zero_point_domain,
)
self.assertTrue(torch.equal(scale, scale_ref))
self.assertTrue(torch.equal(zero_point, zero_point_ref))
def test_groupwise_affine_quantize_tensor_from_qparams(self):
input = torch.randn(10, 256)
scales = torch.randn(10, 2)
zeros = torch.randn(10, 2)
n_bit = 4
groupsize = 128
for zero_point_domain in [ZeroPointDomain.FLOAT, ZeroPointDomain.INT]:
w_int4x8 = groupwise_affine_quantize_tensor_from_qparams(
input, scales, zeros, n_bit, groupsize, zero_point_domain
)
w_int4x8_ref = _groupwise_affine_quantize_tensor_from_qparams(
input, scales, zeros, n_bit, groupsize, zero_point_domain
)
self.assertTrue(torch.equal(w_int4x8, w_int4x8_ref))
def test_groupwise_affine_dequantize_tensor_from_qparams(self):
input = torch.randint(0, 15, (10, 256), dtype=torch.int32)
scales = torch.randn(10, 2).bfloat16()
zeros = torch.randn(10, 2).bfloat16()
n_bit = 4
groupsize = 128
for zero_point_domain in [ZeroPointDomain.FLOAT, ZeroPointDomain.INT]:
if zero_point_domain == ZeroPointDomain.INT:
zeros = torch.randint(0, 15, (10, 2), dtype=torch.int32)
if TORCH_VERSION_AT_LEAST_2_5:
input_tmp = input
if not (
is_device(input.device.type, "cpu") and TORCH_VERSION_AT_LEAST_2_6
):
input_tmp = (input[::, ::2] << 4 | input[::, 1::2]).to(torch.uint8)
w_bf16 = groupwise_affine_dequantize_tensor_from_qparams(
input_tmp, scales, zeros, n_bit, groupsize, zero_point_domain
)
else:
if zero_point_domain == ZeroPointDomain.INT:
continue
w_bf16 = groupwise_affine_dequantize_tensor_from_qparams(
input, scales, zeros, n_bit, groupsize
)
w_bf16_ref = _groupwise_affine_dequantize_tensor_from_qparams(
input, scales, zeros, n_bit, groupsize, zero_point_domain
)
self.assertTrue(torch.equal(w_bf16, w_bf16_ref))
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
def test_fake_quantize_affine(self):
input = torch.randn(10, 10)
mapping_type = MappingType.SYMMETRIC
block_size = list(input.shape)
for i in range(len(block_size) - 1):
block_size[i] = 1
dtype = torch.int8
eps = 1e-5
quant_min = -127
quant_max = 127
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
quant_min,
quant_max,
eps=eps,
scale_dtype=torch.float,
)
quantized = quantize_affine(
input, block_size, scale, zero_point, dtype, quant_min, quant_max
)
dequantized = dequantize_affine(
quantized, block_size, scale, zero_point, dtype, quant_min, quant_max
)
fake_quantized = fake_quantize_affine(
input, block_size, scale, zero_point, dtype, quant_min, quant_max
)
torch.testing.assert_close(dequantized, fake_quantized)
@unittest.skipIf(
not TORCH_VERSION_AT_LEAST_2_4, "skipping when torch version is 2.4 or lower"
)
def test_fake_quantize_affine_cachemask(self):
input = torch.randn(10, 10)
mapping_type = MappingType.SYMMETRIC
block_size = list(input.shape)
for i in range(len(block_size) - 1):
block_size[i] = 1
dtype = torch.int8
eps = 1e-5
quant_min = -127
quant_max = 127
scale, zero_point = choose_qparams_affine(
input,
mapping_type,
block_size,
dtype,
quant_min,
quant_max,
eps=eps,
scale_dtype=torch.float,
)
quantized = quantize_affine(
input, block_size, scale, zero_point, dtype, quant_min, quant_max
)
dequantized = dequantize_affine(
quantized, block_size, scale, zero_point, dtype, quant_min, quant_max
)
(fake_quantized, mask) = fake_quantize_affine_cachemask(
input,
block_size,
scale,
zero_point,
dtype,
quant_min,
quant_max,
)
expected_mask = torch.full(input.shape, True)
torch.testing.assert_close(dequantized, fake_quantized)
torch.testing.assert_close(expected_mask, mask)
if __name__ == "__main__":
unittest.main()