Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

quantization_utility_tests.py 34 KB

You have to be logged in to leave a comment. Sign In
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
  1. import unittest
  2. import super_gradients
  3. import torch
  4. import torchvision
  5. from super_gradients.common.object_names import Models
  6. from super_gradients.import_utils import import_pytorch_quantization_or_install
  7. from torch import nn
  8. class QuantizationUtilityTest(unittest.TestCase):
  9. def setUp(self):
  10. import_pytorch_quantization_or_install()
  11. def test_vanilla_replacement(self):
  12. from super_gradients.training.utils.quantization import SelectiveQuantizer
  13. # ARRANGE
  14. class MyModel(nn.Module):
  15. def __init__(self) -> None:
  16. super().__init__()
  17. self.conv1 = nn.Conv2d(3, 8, kernel_size=3, padding=1)
  18. def forward(self, x):
  19. return self.conv1(x)
  20. module = MyModel()
  21. # TEST
  22. q_util = SelectiveQuantizer()
  23. q_util.quantize_module(module)
  24. x = torch.rand(1, 3, 32, 32)
  25. # ASSERT
  26. with torch.no_grad():
  27. y = module(x)
  28. torch.testing.assert_close(y.size(), (1, 8, 32, 32))
  29. self.assertTrue(isinstance(module.conv1, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  30. def test_module_list_replacement(self):
  31. from super_gradients.training.utils.quantization import SelectiveQuantizer
  32. # ARRANGE
  33. class MyModel(nn.Module):
  34. def __init__(self) -> None:
  35. super().__init__()
  36. self.convs = nn.ModuleList([nn.Conv2d(3, 8, kernel_size=3, padding=1) for _ in range(3)])
  37. def forward(self, x):
  38. return torch.cat([conv(x) for conv in self.convs], dim=1)
  39. module = MyModel()
  40. # TEST
  41. q_util = SelectiveQuantizer()
  42. q_util.quantize_module(module)
  43. x = torch.rand(1, 3, 32, 32)
  44. # ASSERT
  45. with torch.no_grad():
  46. y = module(x)
  47. torch.testing.assert_close(y.size(), (1, 3 * 8, 32, 32))
  48. for conv in module.convs:
  49. self.assertTrue(isinstance(conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  50. def test_sequential_list_replacement(self):
  51. from super_gradients.training.utils.quantization import SelectiveQuantizer
  52. # ARRANGE
  53. class MyModel(nn.Module):
  54. def __init__(self) -> None:
  55. super().__init__()
  56. self.convs = nn.Sequential(
  57. nn.Conv2d(3, 8, kernel_size=3, padding=1),
  58. nn.Conv2d(8, 16, kernel_size=3, padding=1),
  59. )
  60. def forward(self, x):
  61. return self.convs(x)
  62. module = MyModel()
  63. # TEST
  64. q_util = SelectiveQuantizer()
  65. q_util.quantize_module(module)
  66. x = torch.rand(1, 3, 32, 32)
  67. # ASSERT
  68. with torch.no_grad():
  69. y = module(x)
  70. torch.testing.assert_close(y.size(), (1, 16, 32, 32))
  71. for conv in module.convs:
  72. self.assertTrue(isinstance(conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  73. def test_nested_module_replacement(self):
  74. from super_gradients.training.utils.quantization import SelectiveQuantizer
  75. # ARRANGE
  76. class MyBlock(nn.Module):
  77. def __init__(self, in_feats, out_feats) -> None:
  78. super().__init__()
  79. self.flatten = nn.Flatten()
  80. self.linear = nn.Linear(in_feats, out_feats)
  81. def forward(self, x):
  82. return self.linear(self.flatten(x))
  83. class MyModel(nn.Module):
  84. def __init__(self, res, n_classes) -> None:
  85. super().__init__()
  86. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  87. self.my_block = MyBlock(4 * (res**2), n_classes)
  88. def forward(self, x):
  89. y = self.conv(x)
  90. return self.my_block(y)
  91. res = 32
  92. n_clss = 10
  93. module = MyModel(res, n_clss)
  94. # TEST
  95. q_util = SelectiveQuantizer()
  96. q_util.quantize_module(module)
  97. x = torch.rand(1, 3, res, res)
  98. # ASSERT
  99. with torch.no_grad():
  100. y = module(x)
  101. torch.testing.assert_close(y.size(), (1, n_clss))
  102. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  103. self.assertTrue(isinstance(module.my_block.linear, SelectiveQuantizer.mapping_instructions[nn.Linear].quantized_target_class))
  104. def test_static_selective_skip_quantization(self):
  105. from super_gradients.training.utils.quantization import SelectiveQuantizer, SkipQuantization
  106. # ARRANGE
  107. class MyModel(nn.Module):
  108. def __init__(self) -> None:
  109. super().__init__()
  110. self.conv1 = nn.Conv2d(3, 8, kernel_size=3, padding=1)
  111. self.conv2 = SkipQuantization(nn.Conv2d(8, 16, kernel_size=3, padding=1))
  112. def forward(self, x):
  113. return self.conv2(self.conv1(x))
  114. module = MyModel()
  115. # TEST
  116. q_util = SelectiveQuantizer()
  117. q_util.quantize_module(module)
  118. x = torch.rand(1, 3, 32, 32)
  119. # ASSERT
  120. with torch.no_grad():
  121. y = module(x)
  122. torch.testing.assert_close(y.size(), (1, 16, 32, 32))
  123. self.assertTrue(isinstance(module.conv1, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  124. self.assertTrue(isinstance(module.conv2, nn.Conv2d))
  125. def test_dynamic_skip_quantization(self):
  126. from super_gradients.training.utils.quantization import SelectiveQuantizer
  127. # ARRANGE
  128. class MyModel(nn.Module):
  129. def __init__(self) -> None:
  130. super().__init__()
  131. self.conv1 = nn.Conv2d(3, 8, kernel_size=3, padding=1)
  132. self.conv2 = nn.Conv2d(8, 16, kernel_size=3, padding=1)
  133. def forward(self, x):
  134. return self.conv2(self.conv1(x))
  135. module = MyModel()
  136. # TEST
  137. q_util = SelectiveQuantizer()
  138. q_util.register_skip_quantization(layer_names={"conv2"})
  139. q_util.quantize_module(module)
  140. x = torch.rand(1, 3, 32, 32)
  141. # ASSERT
  142. with torch.no_grad():
  143. y = module(x)
  144. torch.testing.assert_close(y.size(), (1, 16, 32, 32))
  145. self.assertTrue(isinstance(module.conv1, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  146. self.assertTrue(isinstance(module.conv2, nn.Conv2d))
  147. def test_custom_quantized_mapping_wrapper_explicit_from_float(self):
  148. from super_gradients.training.utils.quantization import SGQuantMixin, SelectiveQuantizer, QuantizedMapping
  149. from pytorch_quantization import nn as quant_nn
  150. # ARRANGE
  151. class MyBlock(nn.Module):
  152. def __init__(self, in_feats, out_feats) -> None:
  153. super().__init__()
  154. self.flatten = nn.Flatten()
  155. self.linear = nn.Linear(in_feats, out_feats)
  156. def forward(self, x):
  157. return self.linear(self.flatten(x))
  158. class MyQuantizedBlock(SGQuantMixin):
  159. # NOTE: **kwargs are necessary because quant descriptors are passed there!
  160. @classmethod
  161. def from_float(cls, float_instance: MyBlock, **kwargs):
  162. return cls(in_feats=float_instance.linear.in_features, out_feats=float_instance.linear.out_features)
  163. def __init__(self, in_feats, out_feats) -> None:
  164. super().__init__()
  165. self.flatten = nn.Flatten()
  166. self.linear = quant_nn.QuantLinear(in_feats, out_feats)
  167. def forward(self, x):
  168. return self.linear(self.flatten(x))
  169. class MyModel(nn.Module):
  170. def __init__(self, res, n_classes) -> None:
  171. super().__init__()
  172. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  173. self.my_block = QuantizedMapping(float_module=MyBlock(4 * (res**2), n_classes), quantized_target_class=MyQuantizedBlock)
  174. def forward(self, x):
  175. y = self.conv(x)
  176. return self.my_block(y)
  177. res = 32
  178. n_clss = 10
  179. module = MyModel(res, n_clss)
  180. # TEST
  181. q_util = SelectiveQuantizer()
  182. q_util.quantize_module(module)
  183. x = torch.rand(1, 3, res, res)
  184. # ASSERT
  185. with torch.no_grad():
  186. y = module(x)
  187. torch.testing.assert_close(y.size(), (1, n_clss))
  188. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  189. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  190. def test_custom_quantized_mapping_wrapper_implicit_from_float(self):
  191. from super_gradients.training.utils.quantization import SGQuantMixin, SelectiveQuantizer, QuantizedMapping
  192. from pytorch_quantization import nn as quant_nn
  193. # ARRANGE
  194. class MyBlock(nn.Module):
  195. def __init__(self, in_feats, out_feats) -> None:
  196. super().__init__()
  197. self.in_feats = in_feats
  198. self.out_feats = out_feats
  199. self.flatten = nn.Flatten()
  200. self.linear = nn.Linear(in_feats, out_feats)
  201. def forward(self, x):
  202. return self.linear(self.flatten(x))
  203. class MyQuantizedBlock(SGQuantMixin):
  204. def __init__(self, in_feats, out_feats) -> None:
  205. super().__init__()
  206. self.flatten = nn.Flatten()
  207. self.linear = quant_nn.QuantLinear(in_feats, out_feats)
  208. def forward(self, x):
  209. return self.linear(self.flatten(x))
  210. class MyModel(nn.Module):
  211. def __init__(self, res, n_classes) -> None:
  212. super().__init__()
  213. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  214. self.my_block = QuantizedMapping(float_module=MyBlock(4 * (res**2), n_classes), quantized_target_class=MyQuantizedBlock)
  215. def forward(self, x):
  216. y = self.conv(x)
  217. return self.my_block(y)
  218. res = 32
  219. n_clss = 10
  220. module = MyModel(res, n_clss)
  221. # TEST
  222. q_util = SelectiveQuantizer()
  223. q_util.quantize_module(module)
  224. x = torch.rand(1, 3, res, res)
  225. # ASSERT
  226. with torch.no_grad():
  227. y = module(x)
  228. torch.testing.assert_close(y.size(), (1, n_clss))
  229. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  230. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  231. def test_custom_quantized_mapping_register_with_decorator(self):
  232. from super_gradients.training.utils.quantization import SGQuantMixin, SelectiveQuantizer, register_quantized_module
  233. from pytorch_quantization import nn as quant_nn
  234. # ARRANGE
  235. class MyBlock(nn.Module):
  236. def __init__(self, in_feats, out_feats) -> None:
  237. super().__init__()
  238. self.in_feats = in_feats
  239. self.out_feats = out_feats
  240. self.flatten = nn.Flatten()
  241. self.linear = nn.Linear(in_feats, out_feats)
  242. def forward(self, x):
  243. return self.linear(self.flatten(x))
  244. @register_quantized_module(float_source=MyBlock)
  245. class MyQuantizedBlock(SGQuantMixin):
  246. def __init__(self, in_feats, out_feats) -> None:
  247. super().__init__()
  248. self.flatten = nn.Flatten()
  249. self.linear = quant_nn.QuantLinear(in_feats, out_feats)
  250. def forward(self, x):
  251. return self.linear(self.flatten(x))
  252. class MyModel(nn.Module):
  253. def __init__(self, res, n_classes) -> None:
  254. super().__init__()
  255. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  256. self.my_block = MyBlock(4 * (res**2), n_classes)
  257. def forward(self, x):
  258. y = self.conv(x)
  259. return self.my_block(y)
  260. res = 32
  261. n_clss = 10
  262. module = MyModel(res, n_clss)
  263. # TEST
  264. q_util = SelectiveQuantizer()
  265. q_util.quantize_module(module)
  266. x = torch.rand(1, 3, res, res)
  267. # ASSERT
  268. with torch.no_grad():
  269. y = module(x)
  270. torch.testing.assert_close(y.size(), (1, n_clss))
  271. self.assertTrue(MyQuantizedBlock is not None)
  272. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  273. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  274. def test_dynamic_quantized_mapping(self):
  275. from super_gradients.training.utils.quantization import SGQuantMixin, SelectiveQuantizer
  276. from pytorch_quantization import nn as quant_nn
  277. # ARRANGE
  278. class MyBlock(nn.Module):
  279. def __init__(self, in_feats, out_feats) -> None:
  280. super().__init__()
  281. self.in_feats = in_feats
  282. self.out_feats = out_feats
  283. self.flatten = nn.Flatten()
  284. self.linear = nn.Linear(in_feats, out_feats)
  285. def forward(self, x):
  286. return self.linear(self.flatten(x))
  287. class MyQuantizedBlock(SGQuantMixin):
  288. def __init__(self, in_feats, out_feats) -> None:
  289. super().__init__()
  290. self.flatten = nn.Flatten()
  291. self.linear = quant_nn.QuantLinear(in_feats, out_feats)
  292. def forward(self, x):
  293. return self.linear(self.flatten(x))
  294. class MyModel(nn.Module):
  295. def __init__(self, res, n_classes) -> None:
  296. super().__init__()
  297. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  298. self.my_block = MyBlock(4 * (res**2), n_classes)
  299. def forward(self, x):
  300. y = self.conv(x)
  301. return self.my_block(y)
  302. res = 32
  303. n_clss = 10
  304. module = MyModel(res, n_clss)
  305. # TEST
  306. q_util = SelectiveQuantizer()
  307. q_util.register_quantization_mapping(layer_names={"my_block"}, quantized_target_class=MyQuantizedBlock)
  308. q_util.quantize_module(module)
  309. x = torch.rand(1, 3, res, res)
  310. # ASSERT
  311. with torch.no_grad():
  312. y = module(x)
  313. torch.testing.assert_close(y.size(), (1, n_clss))
  314. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  315. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  316. def test_non_default_quant_descriptors_are_piped(self):
  317. from super_gradients.training.utils.quantization import SelectiveQuantizer
  318. from pytorch_quantization.calib import MaxCalibrator
  319. # ARRANGE
  320. class MyModel(nn.Module):
  321. def __init__(self) -> None:
  322. super().__init__()
  323. self.conv1 = nn.Conv2d(3, 8, kernel_size=3, padding=1)
  324. def forward(self, x):
  325. return self.conv1(x)
  326. module = MyModel()
  327. # TEST
  328. q_util = SelectiveQuantizer(default_quant_modules_calibrator_inputs="max", default_quant_modules_calibrator_weights="max")
  329. q_util.quantize_module(module)
  330. x = torch.rand(1, 3, 32, 32)
  331. # ASSERT
  332. with torch.no_grad():
  333. y = module(x)
  334. torch.testing.assert_close(y.size(), (1, 8, 32, 32))
  335. self.assertTrue(isinstance(module.conv1, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  336. self.assertTrue(type(module.conv1._input_quantizer._calibrator) == MaxCalibrator)
  337. self.assertTrue(type(module.conv1._weight_quantizer._calibrator) == MaxCalibrator)
  338. def test_different_quant_descriptors_are_piped(self):
  339. from super_gradients.training.utils.quantization import SelectiveQuantizer
  340. from pytorch_quantization.calib import HistogramCalibrator
  341. from pytorch_quantization.calib import MaxCalibrator
  342. from pytorch_quantization.tensor_quant import QuantDescriptor
  343. # ARRANGE
  344. class MyModel(nn.Module):
  345. def __init__(self) -> None:
  346. super().__init__()
  347. self.conv1 = nn.Conv2d(3, 8, kernel_size=3, padding=1)
  348. self.conv2 = nn.Conv2d(8, 8, kernel_size=3, padding=1)
  349. def forward(self, x):
  350. return self.conv2(self.conv1(x))
  351. module = MyModel()
  352. # TEST
  353. q_util = SelectiveQuantizer()
  354. from pytorch_quantization.nn import QuantConv2d
  355. q_util.register_quantization_mapping(
  356. layer_names={"conv1"},
  357. quantized_target_class=QuantConv2d,
  358. input_quant_descriptor=QuantDescriptor(calib_method="max"),
  359. weights_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  360. )
  361. from pytorch_quantization.tensor_quant import QuantDescriptor
  362. q_util.register_quantization_mapping(
  363. layer_names={"conv2"},
  364. quantized_target_class=QuantConv2d,
  365. input_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  366. weights_quant_descriptor=QuantDescriptor(calib_method="max"),
  367. )
  368. q_util.quantize_module(module)
  369. x = torch.rand(1, 3, 32, 32)
  370. # ASSERT
  371. with torch.no_grad():
  372. y = module(x)
  373. torch.testing.assert_close(y.size(), (1, 8, 32, 32))
  374. self.assertTrue(isinstance(module.conv1, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  375. self.assertTrue(type(module.conv1._input_quantizer._calibrator) == MaxCalibrator)
  376. self.assertTrue(type(module.conv1._weight_quantizer._calibrator) == HistogramCalibrator)
  377. self.assertTrue(type(module.conv2._input_quantizer._calibrator) == HistogramCalibrator)
  378. self.assertTrue(type(module.conv2._weight_quantizer._calibrator) == MaxCalibrator)
  379. def test_quant_descriptors_are_piped_to_custom_quant_modules_if_has_kwargs(self):
  380. from super_gradients.training.utils.quantization import SGQuantMixin, SelectiveQuantizer, QuantizedMapping
  381. from pytorch_quantization import nn as quant_nn
  382. from pytorch_quantization.tensor_quant import QuantDescriptor
  383. from pytorch_quantization.calib import MaxCalibrator
  384. from pytorch_quantization.calib import HistogramCalibrator
  385. # ARRANGE
  386. class MyBlock(nn.Module):
  387. def __init__(self, in_feats, out_feats) -> None:
  388. super().__init__()
  389. self.in_feats = in_feats
  390. self.out_feats = out_feats
  391. self.flatten = nn.Flatten()
  392. self.linear = nn.Linear(in_feats, out_feats)
  393. def forward(self, x):
  394. return self.linear(self.flatten(x))
  395. class MyQuantizedBlock(SGQuantMixin):
  396. # NOTE: if **kwargs are existing, then quant descriptors are passed there!
  397. # NOTE: because we don't override `from_float`,
  398. # then the float instance should have `in_feats` and `out_feats` as state
  399. def __init__(self, in_feats, out_feats, **kwargs) -> None:
  400. super().__init__()
  401. self.flatten = nn.Flatten()
  402. self.linear = quant_nn.QuantLinear(
  403. in_feats,
  404. out_feats,
  405. quant_desc_input=kwargs["quant_desc_input"],
  406. quant_desc_weight=kwargs["quant_desc_weight"],
  407. )
  408. def forward(self, x):
  409. return self.linear(self.flatten(x))
  410. class MyModel(nn.Module):
  411. def __init__(self, res, n_classes) -> None:
  412. super().__init__()
  413. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  414. self.my_block = QuantizedMapping(
  415. float_module=MyBlock(4 * (res**2), n_classes),
  416. quantized_target_class=MyQuantizedBlock,
  417. input_quant_descriptor=QuantDescriptor(calib_method="max"),
  418. weights_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  419. )
  420. def forward(self, x):
  421. y = self.conv(x)
  422. return self.my_block(y)
  423. res = 32
  424. n_clss = 10
  425. module = MyModel(res, n_clss)
  426. # TEST
  427. q_util = SelectiveQuantizer()
  428. q_util.quantize_module(module)
  429. x = torch.rand(1, 3, res, res)
  430. # ASSERT
  431. with torch.no_grad():
  432. y = module(x)
  433. torch.testing.assert_close(y.size(), (1, n_clss))
  434. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  435. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  436. self.assertTrue(type(module.my_block.linear._input_quantizer._calibrator) == MaxCalibrator)
  437. self.assertTrue(type(module.my_block.linear._weight_quantizer._calibrator) == HistogramCalibrator)
  438. def test_quant_descriptors_are_piped_to_custom_quant_modules_if_expects_in_init(self):
  439. from super_gradients.training.utils.quantization import SGQuantMixin, SelectiveQuantizer, QuantizedMapping
  440. from pytorch_quantization import nn as quant_nn
  441. from pytorch_quantization.tensor_quant import QuantDescriptor
  442. from pytorch_quantization.calib import MaxCalibrator
  443. from pytorch_quantization.calib import HistogramCalibrator
  444. # ARRANGE
  445. class MyBlock(nn.Module):
  446. def __init__(self, in_feats, out_feats) -> None:
  447. super().__init__()
  448. self.in_feats = in_feats
  449. self.out_feats = out_feats
  450. self.flatten = nn.Flatten()
  451. self.linear = nn.Linear(in_feats, out_feats)
  452. def forward(self, x):
  453. return self.linear(self.flatten(x))
  454. class MyQuantizedBlock(SGQuantMixin):
  455. # NOTE: `since quant_desc_input`, `quant_desc_weight` are existing, then quant descriptors are passed there!
  456. # NOTE: because we don't override `from_float`,
  457. # then the float instance should have `in_feats` and `out_feats` as state
  458. def __init__(self, in_feats, out_feats, quant_desc_input, quant_desc_weight) -> None:
  459. super().__init__()
  460. self.flatten = nn.Flatten()
  461. self.linear = quant_nn.QuantLinear(
  462. in_feats,
  463. out_feats,
  464. quant_desc_input=quant_desc_input,
  465. quant_desc_weight=quant_desc_weight,
  466. )
  467. def forward(self, x):
  468. return self.linear(self.flatten(x))
  469. class MyModel(nn.Module):
  470. def __init__(self, res, n_classes) -> None:
  471. super().__init__()
  472. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  473. self.my_block = QuantizedMapping(
  474. float_module=MyBlock(4 * (res**2), n_classes),
  475. quantized_target_class=MyQuantizedBlock,
  476. input_quant_descriptor=QuantDescriptor(calib_method="max"),
  477. weights_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  478. )
  479. def forward(self, x):
  480. y = self.conv(x)
  481. return self.my_block(y)
  482. res = 32
  483. n_clss = 10
  484. module = MyModel(res, n_clss)
  485. # TEST
  486. q_util = SelectiveQuantizer()
  487. q_util.quantize_module(module)
  488. x = torch.rand(1, 3, res, res)
  489. # ASSERT
  490. with torch.no_grad():
  491. y = module(x)
  492. torch.testing.assert_close(y.size(), (1, n_clss))
  493. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  494. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  495. self.assertTrue(type(module.my_block.linear._input_quantizer._calibrator) == MaxCalibrator)
  496. self.assertTrue(type(module.my_block.linear._weight_quantizer._calibrator) == HistogramCalibrator)
  497. def test_quant_descriptors_are_not_piped_if_custom_quant_module_does_not_expect_them(self):
  498. from super_gradients.training.utils.quantization import SGQuantMixin, SelectiveQuantizer, QuantizedMapping
  499. from pytorch_quantization import nn as quant_nn
  500. # ARRANGE
  501. class MyBlock(nn.Module):
  502. def __init__(self, in_feats, out_feats) -> None:
  503. super().__init__()
  504. self.in_feats = in_feats
  505. self.out_feats = out_feats
  506. self.flatten = nn.Flatten()
  507. self.linear = nn.Linear(in_feats, out_feats)
  508. def forward(self, x):
  509. return self.linear(self.flatten(x))
  510. class MyQuantizedBlock(SGQuantMixin):
  511. # NOTE: because we don't override `from_float`,
  512. # then the float instance should have `in_feats` and `out_feats` as state
  513. def __init__(self, in_feats, out_feats) -> None:
  514. super().__init__()
  515. self.flatten = nn.Flatten()
  516. self.linear = quant_nn.QuantLinear(in_feats, out_feats)
  517. def forward(self, x):
  518. return self.linear(self.flatten(x))
  519. class MyModel(nn.Module):
  520. def __init__(self, res, n_classes) -> None:
  521. super().__init__()
  522. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  523. self.my_block = QuantizedMapping(float_module=MyBlock(4 * (res**2), n_classes), quantized_target_class=MyQuantizedBlock)
  524. def forward(self, x):
  525. y = self.conv(x)
  526. return self.my_block(y)
  527. res = 32
  528. n_clss = 10
  529. module = MyModel(res, n_clss)
  530. # TEST
  531. q_util = SelectiveQuantizer()
  532. q_util.quantize_module(module)
  533. x = torch.rand(1, 3, res, res)
  534. # ASSERT
  535. with torch.no_grad():
  536. y = module(x)
  537. torch.testing.assert_close(y.size(), (1, n_clss))
  538. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  539. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  540. def test_custom_quantized_mappings_are_recursively_quantized_if_required(self):
  541. from super_gradients.training.utils.quantization import SGQuantMixin, QuantizedMetadata, SelectiveQuantizer, QuantizedMapping
  542. # ARRANGE
  543. class MyBlock(nn.Module):
  544. def __init__(self, in_feats, out_feats) -> None:
  545. super().__init__()
  546. self.in_feats = in_feats
  547. self.out_feats = out_feats
  548. self.flatten = nn.Flatten()
  549. self.linear = nn.Linear(in_feats, out_feats)
  550. def forward(self, x):
  551. return self.linear(self.flatten(x))
  552. class MyQuantizedBlock(SGQuantMixin):
  553. def __init__(self, in_feats, out_feats) -> None:
  554. super().__init__()
  555. self.flatten = nn.Flatten()
  556. self.linear = nn.Linear(in_feats, out_feats)
  557. def forward(self, x):
  558. return self.linear(self.flatten(x))
  559. class MyModel(nn.Module):
  560. def __init__(self, res, n_classes) -> None:
  561. super().__init__()
  562. self.conv = nn.Conv2d(3, 4, kernel_size=3, padding=1)
  563. self.my_block = QuantizedMapping(
  564. float_module=MyBlock(4 * (res**2), n_classes),
  565. quantized_target_class=MyQuantizedBlock,
  566. action=QuantizedMetadata.ReplacementAction.REPLACE_AND_RECURE,
  567. )
  568. def forward(self, x):
  569. y = self.conv(x)
  570. return self.my_block(y)
  571. res = 32
  572. n_clss = 10
  573. module = MyModel(res, n_clss)
  574. # TEST
  575. q_util = SelectiveQuantizer()
  576. q_util.quantize_module(module)
  577. x = torch.rand(1, 3, res, res)
  578. # ASSERT
  579. with torch.no_grad():
  580. y = module(x)
  581. torch.testing.assert_close(y.size(), (1, n_clss))
  582. self.assertTrue(isinstance(module.conv, SelectiveQuantizer.mapping_instructions[nn.Conv2d].quantized_target_class))
  583. self.assertTrue(isinstance(module.my_block, MyQuantizedBlock))
  584. self.assertTrue(isinstance(module.my_block.linear, SelectiveQuantizer.mapping_instructions[nn.Linear].quantized_target_class))
  585. def test_torchvision_resnet_sg_vanilla_quantization_matches_pytorch_quantization(self):
  586. from super_gradients.training.utils.quantization import SelectiveQuantizer, QuantizedMetadata
  587. from pytorch_quantization import nn as quant_nn
  588. from pytorch_quantization.tensor_quant import QuantDescriptor
  589. from pytorch_quantization import quant_modules
  590. resnet_sg = torchvision.models.resnet50(pretrained=True)
  591. # SG SELECTIVE QUANTIZATION
  592. sq = SelectiveQuantizer(
  593. custom_mappings={
  594. torch.nn.Conv2d: QuantizedMetadata(
  595. torch.nn.Conv2d,
  596. quant_nn.QuantConv2d,
  597. action=QuantizedMetadata.ReplacementAction.REPLACE,
  598. input_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  599. weights_quant_descriptor=QuantDescriptor(calib_method="max", axis=0),
  600. ),
  601. torch.nn.Linear: QuantizedMetadata(
  602. torch.nn.Linear,
  603. quant_nn.QuantLinear,
  604. action=QuantizedMetadata.ReplacementAction.REPLACE,
  605. input_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  606. weights_quant_descriptor=QuantDescriptor(calib_method="max", axis=0),
  607. ),
  608. torch.nn.AdaptiveAvgPool2d: QuantizedMetadata(
  609. torch.nn.AdaptiveAvgPool2d,
  610. quant_nn.QuantAdaptiveAvgPool2d,
  611. action=QuantizedMetadata.ReplacementAction.REPLACE,
  612. input_quant_descriptor=QuantDescriptor(calib_method="max"),
  613. ),
  614. },
  615. default_per_channel_quant_weights=True,
  616. )
  617. sq.quantize_module(resnet_sg, preserve_state_dict=True)
  618. # PYTORCH-QUANTIZATION
  619. quant_desc_input = QuantDescriptor(calib_method="histogram")
  620. quant_nn.QuantConv2d.set_default_quant_desc_input(quant_desc_input)
  621. quant_nn.QuantLinear.set_default_quant_desc_input(quant_desc_input)
  622. quant_modules.initialize()
  623. resnet_pyquant = torchvision.models.resnet50(pretrained=True)
  624. quant_modules.deactivate()
  625. for (n1, p1), (n2, p2) in zip(resnet_sg.named_parameters(), resnet_pyquant.named_parameters()):
  626. torch.testing.assert_allclose(p1, p2)
  627. x = torch.rand(1, 3, 128, 128)
  628. with torch.no_grad():
  629. y_pyquant = resnet_pyquant(x)
  630. y_sg = resnet_sg(x)
  631. torch.testing.assert_close(y_sg, y_pyquant)
  632. def test_sg_resnet_sg_vanilla_quantization_matches_pytorch_quantization(self):
  633. # SG SELECTIVE QUANTIZATION
  634. from super_gradients.training.models.classification_models.resnet import Bottleneck
  635. from super_gradients.training.utils.quantization import SelectiveQuantizer, QuantizedMetadata
  636. from pytorch_quantization import nn as quant_nn
  637. from pytorch_quantization import quant_modules
  638. from pytorch_quantization.tensor_quant import QuantDescriptor
  639. sq = SelectiveQuantizer(
  640. custom_mappings={
  641. torch.nn.Conv2d: QuantizedMetadata(
  642. torch.nn.Conv2d,
  643. quant_nn.QuantConv2d,
  644. action=QuantizedMetadata.ReplacementAction.REPLACE,
  645. input_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  646. weights_quant_descriptor=QuantDescriptor(calib_method="max", axis=0),
  647. ),
  648. torch.nn.Linear: QuantizedMetadata(
  649. torch.nn.Linear,
  650. quant_nn.QuantLinear,
  651. action=QuantizedMetadata.ReplacementAction.REPLACE,
  652. input_quant_descriptor=QuantDescriptor(calib_method="histogram"),
  653. weights_quant_descriptor=QuantDescriptor(calib_method="max", axis=0),
  654. ),
  655. torch.nn.AdaptiveAvgPool2d: QuantizedMetadata(
  656. torch.nn.AdaptiveAvgPool2d,
  657. quant_nn.QuantAdaptiveAvgPool2d,
  658. action=QuantizedMetadata.ReplacementAction.REPLACE,
  659. input_quant_descriptor=QuantDescriptor(calib_method="max"),
  660. ),
  661. },
  662. default_per_channel_quant_weights=True,
  663. )
  664. # SG registers non-naive QuantBottleneck that will have different behaviour, pop it for testing purposes
  665. if Bottleneck in sq.mapping_instructions:
  666. sq.mapping_instructions.pop(Bottleneck)
  667. resnet_sg: nn.Module = super_gradients.training.models.get(Models.RESNET50, pretrained_weights="imagenet", num_classes=1000)
  668. sq.quantize_module(resnet_sg, preserve_state_dict=True)
  669. # PYTORCH-QUANTIZATION
  670. quant_desc_input = QuantDescriptor(calib_method="histogram")
  671. quant_desc_weights = QuantDescriptor(calib_method="max", axis=0)
  672. quant_nn.QuantConv2d.set_default_quant_desc_input(quant_desc_input)
  673. quant_nn.QuantConv2d.set_default_quant_desc_weight(quant_desc_weights)
  674. quant_nn.QuantLinear.set_default_quant_desc_input(quant_desc_input)
  675. quant_nn.QuantLinear.set_default_quant_desc_weight(quant_desc_weights)
  676. quant_nn.QuantAdaptiveAvgPool2d.set_default_quant_desc_input(QuantDescriptor(calib_method="histogram"))
  677. quant_modules.initialize()
  678. resnet_pyquant: nn.Module = super_gradients.training.models.get(Models.RESNET50, pretrained_weights="imagenet", num_classes=1000)
  679. quant_modules.deactivate()
  680. for (n1, p1), (n2, p2) in zip(resnet_sg.named_parameters(), resnet_pyquant.named_parameters()):
  681. torch.testing.assert_allclose(p1, p2)
  682. x = torch.rand(1, 3, 128, 128)
  683. with torch.no_grad():
  684. y_pyquant = resnet_pyquant(x)
  685. y_sg = resnet_sg(x)
  686. torch.testing.assert_close(y_sg, y_pyquant)
  687. if __name__ == "__main__":
  688. unittest.main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...