-
Notifications
You must be signed in to change notification settings - Fork 243
/
pytorch.py
3448 lines (3089 loc) · 154 KB
/
pytorch.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import math
import os
from enum import Enum
from collections import OrderedDict, UserDict
from packaging.version import Version
import yaml
from functools import partial
from neural_compressor.utils.utility import dump_elapsed_time
from .adaptor import adaptor_registry, Adaptor
from ..utils.utility import LazyImport, CpuInfo, GLOBAL_STATE, MODE
from ..utils.utility import Statistics
from ..utils import logger
from .query import QueryBackendCapability
from ..experimental.data.dataloaders.base_dataloader import BaseDataLoader
try: # pragma: no cover
import intel_extension_for_pytorch as ipex
IPEX = True
except:
IPEX = False
torch = LazyImport("torch")
json = LazyImport("json")
hvd = LazyImport("horovod.torch")
torch_utils = LazyImport("neural_compressor.adaptor.torch_utils")
REDUCE_RANGE = False if CpuInfo().vnni else True
logger.debug("Reduce range is {}".format(str(REDUCE_RANGE)))
def get_torch_version():
try:
torch_version = torch.__version__.split('+')[0]
except ValueError as e: # pragma: no cover
assert False, 'Got an unknown version of torch: {}'.format(e)
version = Version(torch_version)
return version
def get_example_inputs(dataloader): # pragma: no cover
if dataloader is None:
return None
it = iter(dataloader)
example_inputs = next(it)
if isinstance(example_inputs, dict):
input_tensor = []
if "label" in example_inputs.keys():
example_inputs.pop("label")
for key, value in example_inputs.items():
if key == "start_positions" or key == "end_positions":
continue
input_tensor.append(value)
return input_tensor
if isinstance(example_inputs, list) or isinstance(example_inputs, tuple):
if len(example_inputs) > 1:
return example_inputs[0]
return example_inputs
if isinstance(example_inputs, torch.Tensor):
return example_inputs
def get_torch_white_list(approach):
version = get_torch_version()
import torch.quantization as tq
if version < Version("1.7.0-rc1"): # pragma: no cover
white_list = \
set(tq.default_mappings.DEFAULT_DYNAMIC_MODULE_MAPPING.keys()) \
if approach == 'post_training_dynamic_quant' else \
tq.default_mappings.DEFAULT_QCONFIG_PROPAGATE_WHITE_LIST
elif version < Version("1.8.0-rc1"): # pragma: no cover
white_list = \
set(tq.quantization_mappings.get_dynamic_quant_module_mappings().keys()) \
if approach == 'post_training_dynamic_quant' else \
tq.quantization_mappings.get_qconfig_propagation_list()
else:
white_list = \
set(tq.quantization_mappings.get_default_dynamic_quant_module_mappings().keys()) \
if approach == 'post_training_dynamic_quant' else \
tq.quantization_mappings.get_default_qconfig_propagation_list()
return white_list
def pytorch_forward_wrapper(model, input, device='cpu', conf=None, running_mode='inference'):
version = get_torch_version()
if isinstance(input, dict) or isinstance(input, UserDict):
if device == 'cpu':
output = model(**input)
elif device == 'ipex': # pragma: no cover
# have to split the case to avoid exposing ipex.DEVICE outside
# which require intel extension installed
if version < Version("1.12.0-rc1"):
if running_mode == "calibration":
with ipex.quantization.calibrate(conf, default_recipe=True): # pylint: disable=E1101
output = model(**input)
else:
output = model(**input)
else:
output = model(**input)
else: # pragma: no cover
for inp in input.keys():
input[inp] = input[inp].to("dpcpp" if device=="gpu" else device) \
if isinstance(input[inp], torch.Tensor) else input[inp]
output = model(**input)
elif isinstance(input, list) or isinstance(input, tuple):
if device == 'cpu':
output = model(*input)
elif device == 'ipex': # pragma: no cover
if version < Version("1.12.0-rc1"):
if running_mode == "calibration":
with ipex.quantization.calibrate(conf, default_recipe=True): # pylint: disable=E1101
output = model(*input)
else:
output = model(*input)
else:
output = model(*input)
else: # pragma: no cover
tmp_device = "dpcpp" if device == "gpu" else device
input = [inp.to(tmp_device) \
if isinstance(inp, torch.Tensor) else inp
for inp in input] # pylint: disable=E1133
output = model(*input)
else:
if device == 'cpu' or not isinstance(input, torch.Tensor):
output = model(input)
elif device == 'ipex': # pragma: no cover
if version < Version("1.12.0-rc1"):
if running_mode == "calibration":
with ipex.quantization.calibrate(conf, default_recipe=True): # pylint: disable=E1101
output = model(input)
else:
output = model(input)
else:
output = model(input)
else: # pragma: no cover
input = input.to("dpcpp" if device == "gpu" else device) # pylint: disable=no-member
output = model(input)
return output
def get_ops_recursively(model, prefix, ops={}):
"""This is a helper function for `graph_info`,
and it will get all ops from model.
Args:
model (object): input model
prefix (string): prefix of op name
ops (dict): dict of ops from model {op name: type}.
Returns:
None
"""
version = get_torch_version()
if version < Version("1.7.0-rc1"): # pragma: no cover
white_list = \
(set(torch.quantization.default_mappings.DEFAULT_MODULE_MAPPING.values()) |
set(torch.quantization.default_mappings.DEFAULT_QAT_MODULE_MAPPING.values()) |
set(torch.quantization.default_mappings.DEFAULT_DYNAMIC_MODULE_MAPPING.values()) |
set(torch.quantization.default_mappings.DEFAULT_MODULE_MAPPING.keys()) |
set(torch.quantization.default_mappings.DEFAULT_QAT_MODULE_MAPPING.keys()) |
set(torch.quantization.default_mappings.DEFAULT_DYNAMIC_MODULE_MAPPING.keys()) |
torch.quantization.default_mappings._INCLUDE_QCONFIG_PROPAGATE_LIST)
elif version < Version("1.8.0-rc1"): # pragma: no cover
white_list = torch.quantization.get_compare_output_module_list()
else:
white_list = torch.quantization.get_default_compare_output_module_list()
for name, child in model.named_children():
op_name = prefix + '.' + name if prefix != '' else name
if type(child) in white_list and not isinstance(child, torch.nn.Sequential) and \
type(child) != torch.quantization.stubs.DeQuantStub:
ops[op_name] = unify_op_type_mapping[str(child.__class__.__name__)] \
if str(child.__class__.__name__) in unify_op_type_mapping else \
str(child.__class__.__name__)
get_ops_recursively(child, op_name, ops)
def _cfg_to_qconfig(tune_cfg, observer_type='post_training_static_quant'):
"""Convert tune configure to quantization config for each op.
Args:
tune_cfg (dict): dictionary of tune configure for each op
observer_type (str, optional): specify observer type, Default is 'ptq_static',
options: 'ptq_dynamic', 'qat'.
Returns:
op_qcfgs (dict): dictionary of quantization configure for each op
tune_cfg should be a format like below:
{
'fuse': {'int8': [['CONV2D', 'RELU', 'BN'], ['CONV2D', 'RELU']],
'fp32': [['CONV2D', 'RELU', 'BN']]},
'calib_iteration': 10,
'op': {
('op1', 'CONV2D'): {
'activation': {'dtype': 'uint8',
'algorithm': 'minmax',
'scheme':'sym',
'granularity': 'per_tensor'},
'weight': {'dtype': 'int8',
'algorithm': 'kl',
'scheme':'asym',
'granularity': 'per_channel'}
},
('op2', 'RELU): {
'activation': {'dtype': 'int8',
'scheme': 'asym',
'granularity': 'per_tensor',
'algorithm': 'minmax'}
},
('op3', 'CONV2D'): {
'activation': {'dtype': 'fp32'},
'weight': {'dtype': 'fp32'}
},
...
}
}
"""
op_qcfgs = OrderedDict()
op_qcfgs['bf16_ops_list'] = []
for key in tune_cfg['op']:
value = tune_cfg['op'][key]
assert isinstance(value, dict)
assert 'activation' in value
if ('weight' in value and value['weight']['dtype'] == 'fp32') or \
('weight' not in value and value['activation']['dtype'] == 'fp32'):
op_qcfgs[key[0]] = None
elif ('weight' in value and value['weight']['dtype'] == 'bf16') or \
('weight' not in value and value['activation']['dtype'] == 'bf16'):
op_qcfgs['bf16_ops_list'].append(key)
op_qcfgs[key[0]] = None
else:
if 'weight' in value:
weight = value['weight']
scheme = weight['scheme']
granularity = weight['granularity']
algorithm = weight['algorithm']
dtype = weight['dtype']
if observer_type == 'quant_aware_training' and \
key[1] not in ['Embedding', 'EmbeddingBag', 'LSTM', 'GRU',
'LSTMCell', 'GRUCell', 'RNNCell']:
weights_fake_quantize = _fake_quantize(algorithm, scheme, granularity, dtype)
else:
weights_observer = _observer(algorithm, scheme, granularity, dtype)
else:
if observer_type == 'quant_aware_training':
weights_fake_quantize = torch.quantization.default_weight_fake_quant
else:
weights_observer = torch.quantization.default_per_channel_weight_observer
activation = value['activation']
scheme = activation['scheme']
granularity = activation['granularity']
algorithm = activation['algorithm']
dtype = activation['dtype']
compute_dtype = activation['compute_dtype'] \
if 'compute_dtype' in activation \
and activation['compute_dtype'] is not None \
else 'uint8'
if observer_type == 'quant_aware_training':
if key[1] in ['LSTM', 'GRU', 'LSTMCell', 'GRUCell', 'RNNCell']:
activation_observer = _observer(algorithm, scheme, granularity,
dtype, 'post_training_dynamic_quant', compute_dtype)
elif key[1] not in ['Embedding', 'EmbeddingBag']:
activation_fake_quantize = _fake_quantize(algorithm, scheme, granularity, dtype,
compute_dtype)
else:
activation_observer = \
_observer(algorithm, scheme, granularity, dtype, observer_type, compute_dtype)
elif value['activation']['quant_mode'] == 'static':
activation_observer = _observer(algorithm, scheme, granularity,
dtype, 'post_training_static_quant', compute_dtype)
elif value['activation']['quant_mode'] == 'dynamic':
activation_observer = _observer(algorithm, scheme, granularity,
dtype, 'post_training_dynamic_quant', compute_dtype)
if observer_type == 'quant_aware_training':
if key[1] in ['LSTM', 'GRU', 'LSTMCell', 'GRUCell', 'RNNCell',
'Embedding', 'EmbeddingBag']:
qconfig = torch.quantization.QConfigDynamic(
activation=activation_observer, weight=weights_observer)
else:
qconfig = torch.quantization.QConfig(activation=activation_fake_quantize,
weight=weights_fake_quantize)
elif value['activation']['quant_mode'] == 'static':
qconfig = torch.quantization.QConfig(activation=activation_observer,
weight=weights_observer)
else:
version = get_torch_version()
if version < Version("1.6.0-rc1"): # pragma: no cover
qconfig = torch.quantization.QConfigDynamic(weight=weights_observer)
else:
qconfig = torch.quantization.QConfigDynamic(activation=activation_observer,
weight=weights_observer)
op_qcfgs[key[0]] = qconfig
return op_qcfgs
def _cfgs_to_fx_cfgs(op_cfgs, observer_type='post_training_static_quant'):
"""Convert quantization config to a format that meets the requirements of torch.fx.
Args:
op_cfgs (dict): dictionary of quantization configure for each op
observer_type (str, optional): specify observer type, Default is 'ptq_static',
options: 'ptq_dynamic', 'qat'.
Returns:
fx_op_cfgs (dict): dictionary of quantization configure that meets
the requirements of torch.fx
example: fx_op_cfgs = {"": default_qconfig,
"module_name": [("layer4.1.conv2", per_channel_weight_qconfig)]}
"""
version = get_torch_version()
if observer_type == 'post_training_dynamic_quant':
model_qconfig = torch.quantization.default_dynamic_qconfig
elif observer_type == 'quant_aware_training':
model_qconfig = torch.quantization.QConfig(
activation=torch.quantization.FakeQuantize.with_args(
dtype=torch.quint8,
qscheme=torch.per_tensor_affine,
reduce_range=REDUCE_RANGE),
weight=torch.quantization.default_weight_fake_quant) \
if version < Version("1.10.0-rc1") else \
torch.quantization.QConfig(
activation=torch.quantization.FusedMovingAvgObsFakeQuantize.with_args(
dtype=torch.quint8,
qscheme=torch.per_tensor_affine,
reduce_range=REDUCE_RANGE),
weight=torch.quantization.default_fused_per_channel_wt_fake_quant)
else:
model_qconfig = torch.quantization.QConfig(
activation=torch.quantization.HistogramObserver.with_args(reduce_range=REDUCE_RANGE),
weight=torch.quantization.default_per_channel_weight_observer)
if version > Version("1.12.1"): # pragma: no cover
from torch.ao.quantization import QConfigMapping
fx_op_cfgs = QConfigMapping()
fx_op_cfgs.set_global(model_qconfig)
else:
fx_op_cfgs = dict()
fx_op_cfgs[""] = model_qconfig
op_tuple_cfg_list = []
for key, value in op_cfgs.items():
if key == "default_qconfig":
if version > Version("1.12.1"): # pragma: no cover
fx_op_cfgs.set_global(value)
else:
fx_op_cfgs[""] = value
continue
if version > Version("1.12.1"): # pragma: no cover
fx_op_cfgs.set_module_name(key, value)
else:
op_tuple = (key, value)
op_tuple_cfg_list.append(op_tuple)
if version <= Version("1.12.1"): # pragma: no cover
fx_op_cfgs["module_name"] = op_tuple_cfg_list
return fx_op_cfgs
def _observer(algorithm,
scheme,
granularity,
dtype,
observer_type='post_training_static_quant',
compute_dtype='uint8'):
"""Construct an observer module, In forward, observer will update the statistics of
the observed Tensor. And they should provide a `calculate_qparams` function
that computes the quantization parameters given the collected statistics.
Args:
algorithm (string): What algorithm for computing the quantization parameters based on.
scheme (string): Quantization scheme to be used.
granularity (string): What granularity to computing the quantization parameters,
per channel or per tensor.
dtype (string): Quantized data type
observer_type (string): Observer type, default is 'post_training_static_quant'.
Returns:
oberser (object)
"""
if observer_type == 'post_training_dynamic_quant' and \
get_torch_version() >= Version("1.6.0-rc1"):
return torch.quantization.default_dynamic_quant_observer
compute_dtype_dict = {'int8': torch.qint8, 'uint8': torch.quint8, 'None': None}
if compute_dtype in compute_dtype_dict:
compute_dtype = compute_dtype_dict[compute_dtype]
else: # pragma: no cover
assert False, "Unsupport compute_dtype with {}".format(compute_dtype)
dtype_dict = {'int8': torch.qint8, 'uint8': torch.quint8, 'fp32': torch.float}
if dtype in dtype_dict:
dtype = dtype_dict[dtype]
else: # pragma: no cover
assert False, "Unsupport dtype with {}".format(dtype)
if algorithm == 'placeholder' or dtype == torch.float: # pragma: no cover
return torch.quantization.PlaceholderObserver \
if get_torch_version() <= Version("1.7.1") \
else torch.quantization.PlaceholderObserver.with_args(dtype=dtype,
compute_dtype=compute_dtype)
if algorithm == 'minmax':
if granularity == 'per_channel':
observer = torch.quantization.PerChannelMinMaxObserver
if scheme == 'sym':
qscheme = torch.per_channel_symmetric
elif scheme == 'asym_float':
qscheme = torch.per_channel_affine_float_qparams
else:
qscheme = torch.per_channel_affine
else:
assert granularity == 'per_tensor'
observer = torch.quantization.MinMaxObserver
if scheme == 'sym':
qscheme = torch.per_tensor_symmetric
else:
assert scheme == 'asym'
qscheme = torch.per_tensor_affine
else:
assert algorithm == 'kl'
observer = torch.quantization.HistogramObserver
assert granularity == 'per_tensor'
if scheme == 'sym':
qscheme = torch.per_tensor_symmetric
else:
assert scheme == 'asym'
qscheme = torch.per_tensor_affine
return observer.with_args(qscheme=qscheme,
dtype=dtype,
reduce_range=(REDUCE_RANGE and scheme == 'asym'))
def _fake_quantize(algorithm, scheme, granularity, dtype, compute_dtype='uint8'):
"""Construct a fake quantize module, In forward, fake quantize module will update
the statistics of the observed Tensor and fake quantize the input.
They should also provide a `calculate_qparams` function
that computes the quantization parameters given the collected statistics.
Args:
algorithm (string): What algorithm for computing the quantization parameters based on.
scheme (string): Quantization scheme to be used.
granularity (string): What granularity to computing the quantization parameters,
per channel or per tensor.
dtype (sting): Quantized data type
Return:
fake quantization (object)
"""
version = get_torch_version()
if scheme == 'asym_float' \
and version >= Version("1.7.0-rc1"):
return torch.quantization.default_float_qparams_observer
if algorithm == 'placeholder' or dtype == 'fp32': # pragma: no cover
return _observer(algorithm, scheme, granularity, dtype, compute_dtype=compute_dtype)
fake_quant = torch.quantization.FakeQuantize \
if version < Version("1.10.0-rc1") else \
torch.quantization.FusedMovingAvgObsFakeQuantize
if algorithm == 'minmax':
if granularity == 'per_channel':
observer = torch.quantization.MovingAveragePerChannelMinMaxObserver
if scheme == 'sym':
qscheme = torch.per_channel_symmetric
else:
assert scheme == 'asym'
qscheme = torch.per_channel_affine
else:
assert granularity == 'per_tensor'
observer = torch.quantization.MovingAverageMinMaxObserver
if scheme == 'sym':
qscheme = torch.per_tensor_symmetric
else:
assert scheme == 'asym'
qscheme = torch.per_tensor_affine
else: # pragma: no cover
# Histogram observer is too slow for quantization aware training
assert algorithm == 'kl'
observer = torch.quantization.HistogramObserver
assert granularity == 'per_tensor'
if scheme == 'sym':
qscheme = torch.per_tensor_symmetric
else:
assert scheme == 'asym'
qscheme = torch.per_tensor_affine
if dtype == 'int8':
qmin = -128
qmax = 127
dtype = torch.qint8
else:
assert dtype == 'uint8'
qmin = 0
qmax = 255
dtype = torch.quint8
return fake_quant.with_args(observer=observer,
quant_min=qmin,
quant_max=qmax,
dtype=dtype,
qscheme=qscheme,
reduce_range=(REDUCE_RANGE and scheme == 'asym'))
def _propagate_qconfig(model,
op_qcfgs,
is_qat_convert=False,
approach='post_training_static_quant'):
"""Propagate qconfig through the module hierarchy and assign `qconfig`
attribute on each leaf module
Args:
model (object): input model
op_qcfgs (dict): dictionary that maps from name or type of submodule to
quantization configuration, qconfig applies to all submodules of a
given module unless qconfig for the submodules are specified (when
the submodule already has qconfig attribute)
is_qat_convert (bool): flag that specified this function is used to QAT prepare
for pytorch 1.7 or above.
approach (str): quantization approach
Return:
None, module is modified inplace with qconfig attached
"""
fallback_ops = []
_propagate_qconfig_recursively(model, '', op_qcfgs)
if approach != 'post_training_dynamic_quant':
for k, v in op_qcfgs.items():
if v is None and not is_qat_convert:
fallback_ops.append(k)
if fallback_ops and not is_qat_convert:
_fallback_quantizable_ops_recursively(model, '', fallback_ops, op_qcfgs)
def _propagate_qconfig_recursively(model, prefix, op_qcfgs, qconfig_parent=None):
"""This is a helper function for `propagate_qconfig`
Args:
model (object): input model
prefix (string): prefix of op name
op_qcfgs (dict): dictionary that maps from name or type of submodule to
quantization configuration
qconfig_parent (object, optional): qconfig of parent module
Returns:
None
"""
for name, child in model.named_children():
op_name = prefix + name
child.qconfig = qconfig_parent
qconfig_son = None
if op_name in op_qcfgs:
child.qconfig = op_qcfgs[op_name]
# for submodules of fused module, like nn.ConvBnRelu2d.
qconfig_son = child.qconfig
elif type(child) == torch.quantization.DeQuantStub:
version = get_torch_version()
if version >= Version("1.8.0-rc1"):
child.qconfig = torch.quantization.QConfig(
activation=torch.quantization.MinMaxObserver.with_args(
reduce_range=REDUCE_RANGE),
weight=torch.quantization.default_per_channel_weight_observer)
_propagate_qconfig_recursively(child, op_name + '.', op_qcfgs, qconfig_son)
def _find_quantized_op_num(module, op_qcfgs, prefix='', op_count=0):
"""This is a helper function for `_fallback_quantizable_ops_recursively`
Args:
model (object): input model
op_cfgs (dict): dictionary of quantization configure for each op
prefix (str): prefix of op name
op_count (int, optional): count the quantizable op quantity in this module
Returns:
the quantizable op quantity in this module
"""
for name_tmp, child_tmp in module.named_children():
op_name = prefix + '.' + name_tmp if prefix != '' else name_tmp
if op_name in op_qcfgs.keys() and \
type(child_tmp) != torch.quantization.QuantStub:
op_count += 1
else:
op_count = _find_quantized_op_num(child_tmp, op_qcfgs, op_name, op_count)
return op_count
def _fallback_quantizable_ops_recursively(model, prefix, fallback_ops, op_qcfgs):
"""Handle all fallback ops(fp32 ops)
Args:
model (object): input model
prefix (string): the prefix of op name
fallback_ops (list): list of fallback ops(fp32 ops)
op_cfgs (dict): dictionary of quantization configure for each op
Returns:
None
"""
class DequantQuantWrapper(torch.nn.Module):
"""A wrapper class that wraps the input module, adds DeQuantStub and
surround the call to module with call to dequant.
this is used by fallback layer when the data type of quantized op
is input:int8/output:int8.
This is used by the fallback utility functions to add the dequant and
quant modules, before `convert` function `QuantStub` will just be observer,
it observes the input tensor, after `convert`, `QuantStub`
will be swapped to `nnq.Quantize` which does actual quantization. Similarly
for `DeQuantStub`.
"""
def __init__(self, module, observer=None):
super(DequantQuantWrapper, self).__init__()
if not module.qconfig and observer:
weights_observer = observer('minmax', 'asym', 'per_channel', 'int8')
activation_observer = observer('minmax', 'sym', 'per_tensor', 'uint8')
module.qconfig = torch.quantization.QConfig(activation=activation_observer,
weight=weights_observer)
self.add_module('quant', torch.quantization.QuantStub(module.qconfig))
self.add_module('dequant', torch.quantization.DeQuantStub())
self.add_module('module', module)
version = get_torch_version()
if version >= Version("1.8.0-rc1"):
self.dequant.qconfig = module.qconfig
module.qconfig = None
self.train(module.training)
def forward(self, X):
X = self.dequant(X)
X = self.module(X)
return self.quant(X)
def add(self, x, y):
# type: (Tensor, Tensor) -> Tensor
x = self.dequant(x)
y = self.dequant(y)
r = self.module.add(x, y)
return self.quant(r)
def add_scalar(self, x, y):
# type: (Tensor, float) -> Tensor
x = self.dequant(x)
r = self.module.add_scalar(x, y)
return self.quant(r)
def mul(self, x, y):
# type: (Tensor, Tensor) -> Tensor
x = self.dequant(x)
y = self.dequant(y)
r = self.module.mul(x, y)
return self.quant(r)
def mul_scalar(self, x, y):
# type: (Tensor, float) -> Tensor
x = self.dequant(x)
r = self.module.mul_scalar(x, y)
return self.quant(r)
def cat(self, x, dim=0):
# type: (List[Tensor], int) -> Tensor
X = [self.dequant(x_) for x_ in x]
r = self.module.cat(X, dim)
return self.quant(r)
def add_relu(self, x, y):
# type: (Tensor, Tensor) -> Tensor
x = self.dequant(x)
y = self.dequant(y)
r = self.module.add_relu(x, y)
return self.quant(r)
for name, child in model.named_children():
op_name = prefix + '.' + name if prefix != '' else name
if op_name in fallback_ops:
child.qconfig = None
quantize_op_num = _find_quantized_op_num(model, op_qcfgs, prefix=prefix)
if quantize_op_num == 1:
found = False
for name_tmp, child_tmp in model.named_children():
if isinstance(child_tmp, torch.quantization.QuantStub) or isinstance(
child_tmp, torch.quantization.DeQuantStub):
model._modules[name_tmp] = torch.nn.Identity()
found = True
if not found:
model._modules[name] = DequantQuantWrapper(child, observer=_observer)
else:
model._modules[name] = DequantQuantWrapper(child, observer=_observer)
else:
_fallback_quantizable_ops_recursively(child, op_name, fallback_ops, op_qcfgs)
@adaptor_registry
class TemplateAdaptor(Adaptor):
"""Tample adaptor of PyTorch framework.
Args:
framework_specific_info (dict): dictionary of tuning configure from yaml file.
"""
def __init__(self, framework_specific_info):
super(TemplateAdaptor, self).__init__(framework_specific_info)
import torch.quantization as tq
self.version = get_torch_version()
# set torch random seed
random_seed = framework_specific_info['random_seed']
torch.manual_seed(random_seed)
self.bf16_ops = []
self.use_bf16 = framework_specific_info['use_bf16'] if \
'use_bf16' in framework_specific_info else True
self.device = framework_specific_info['device']
self.q_dataloader = framework_specific_info['q_dataloader']
self.benchmark = (GLOBAL_STATE.STATE == MODE.BENCHMARK)
self.workspace_path = framework_specific_info['workspace_path']
self.is_baseline = False if GLOBAL_STATE.STATE == MODE.BENCHMARK else True
self.query_handler = None
self.approach = ''
self.pre_optimized_model = None
self.sub_module_list = None
self.default_qconfig = framework_specific_info['default_qconfig'] \
if 'default_qconfig' in framework_specific_info else None
if 'approach' in framework_specific_info: # pragma: no cover
self.approach = framework_specific_info['approach']
if framework_specific_info['approach'] in ["post_training_static_quant",
"post_training_auto_quant"]:
if self.version < Version("1.7.0-rc1"):
self.q_mapping = tq.default_mappings.DEFAULT_MODULE_MAPPING
elif self.version < Version("1.8.0-rc1"):
self.q_mapping = \
tq.quantization_mappings.get_static_quant_module_mappings()
else:
self.q_mapping = \
tq.quantization_mappings.get_default_static_quant_module_mappings()
elif framework_specific_info['approach'] == "quant_aware_training":
if self.version < Version("1.7.0-rc1"):
self.q_mapping = tq.default_mappings.DEFAULT_QAT_MODULE_MAPPING
elif self.version < Version("1.8.0-rc1"):
self.q_mapping = \
tq.quantization_mappings.get_qat_module_mappings()
else:
self.q_mapping = \
tq.quantization_mappings.get_default_qat_module_mappings()
elif framework_specific_info['approach'] == "post_training_dynamic_quant":
if self.version < Version("1.7.0-rc1"):
self.q_mapping = \
tq.default_mappings.DEFAULT_DYNAMIC_MODULE_MAPPING
elif self.version < Version("1.8.0-rc1"):
self.q_mapping = \
tq.quantization_mappings.get_dynamic_quant_module_mappings()
else:
self.q_mapping = \
tq.quantization_mappings.get_default_dynamic_quant_module_mappings()
else:
assert False, "Unsupport approach: {}".format(self.approach)
self.fp32_results = []
self.fp32_preds_as_label = False
def calib_func(self, model, dataloader, tmp_iterations, conf=None):
try:
for idx, (input, label) in enumerate(dataloader):
output = pytorch_forward_wrapper(model,
input,
device=self.device,
conf=conf,
running_mode='calibration')
if idx >= tmp_iterations - 1:
break
except Exception as e:
for idx, input in enumerate(dataloader):
output = pytorch_forward_wrapper(model,
input,
device=self.device,
conf=conf,
running_mode='calibration')
if idx >= tmp_iterations - 1:
break
def model_calibration(self,
q_model,
dataloader,
iterations=1,
conf=None,
calib_sampling_size=1):
assert iterations > 0
with torch.no_grad():
if isinstance(dataloader, BaseDataLoader):
batch_size = dataloader.batch_size
try:
for i in range(batch_size):
if calib_sampling_size % (batch_size - i) == 0:
calib_batch_size = batch_size - i
if i != 0:
logger.warning("Reset `calibration.dataloader.batch_size` field "
"to {}".format(calib_batch_size) +
" to make sure the sampling_size is "
"divisible exactly by batch size")
break
tmp_iterations = int(math.ceil(calib_sampling_size / calib_batch_size))
dataloader.batch(calib_batch_size)
self.calib_func(q_model, dataloader, tmp_iterations, conf)
except Exception: # pragma: no cover
logger.warning("Fail to forward with batch size={}, set to {} now.".format(
batch_size, 1))
dataloader.batch(1)
self.calib_func(q_model, dataloader, calib_sampling_size, conf)
else: # pragma: no cover
if hasattr(dataloader, 'batch_size') and \
calib_sampling_size % dataloader.batch_size != 0:
logger.warning(
"Please note that calibration sampling size {} " \
"isn't divisible exactly by batch size {}. " \
"So the real sampling size is {}.".
format(calib_sampling_size, dataloader.batch_size,
dataloader.batch_size * iterations))
self.calib_func(q_model, dataloader, iterations, conf)
def eval_func(self, model, dataloader, postprocess, metrics, measurer, iteration, conf=None):
results = []
for idx, (input, label) in enumerate(dataloader):
if measurer is not None:
measurer.start()
output = pytorch_forward_wrapper(model, input, device=self.device, conf=conf)
if self.device != "cpu": # pragma: no cover
output = output.to("cpu")
label = label.to("cpu")
if measurer is not None:
measurer.end()
if postprocess is not None:
output, label = postprocess((output, label))
if metrics:
for metric in metrics:
if not hasattr(metric, "compare_label") or \
(hasattr(metric, "compare_label") and metric.compare_label):
metric.update(output, label)
# If distributed dataloader, gather all outputs to update metric
if getattr(dataloader, 'distributed', False) or \
isinstance(dataloader.sampler, \
torch.utils.data.distributed.DistributedSampler):
hvd.init()
for metric in metrics:
metric.hvd = hvd
if self.fp32_preds_as_label:
self.fp32_results.append(output) if self.is_baseline else \
results.append(output)
if idx + 1 == iteration:
break
return results
def model_eval(self,
model,
dataloader,
postprocess=None,
metrics=None,
measurer=None,
iteration=-1,
conf=None):
with torch.no_grad():
if metrics:
for metric in metrics:
metric.reset()
if isinstance(dataloader, BaseDataLoader) and not self.benchmark:
try:
results = self.eval_func(model, dataloader, postprocess, metrics, measurer,
iteration, conf)
except Exception: # pragma: no cover
logger.warning("Fail to forward with batch size={}, set to {} now.".format(
dataloader.batch_size, 1))
dataloader.batch(1)
results = self.eval_func(model, dataloader, postprocess, metrics, measurer,
iteration, conf)
else: # pragma: no cover
results = self.eval_func(model, dataloader, postprocess, metrics, measurer,
iteration, conf)
if self.fp32_preds_as_label:
if self.is_baseline:
results = torch_utils.util.collate_torch_preds(self.fp32_results)
reference = results
else:
reference = torch_utils.util.collate_torch_preds(self.fp32_results)
results = torch_utils.util.collate_torch_preds(results)
for metric in metrics:
if hasattr(metric, "compare_label") and not metric.compare_label:
metric.update(results, reference)
acc = 0 if metrics is None else [metric.result() for metric in metrics]
return acc if not isinstance(acc, list) or len(acc) > 1 else acc[0]
def _get_quantizable_ops_recursively(self, model, prefix, quantizable_ops):
"""This is a helper function for `query_fw_capability`,
and it will get all quantizable ops from model.
Args:
model (object): input model
prefix (string): prefix of op name
quantizable_ops (list): list of quantizable ops from model include op name and type.
Returns:
None
"""
raise NotImplementedError
def _get_quantizable_ops(self, model):
"""This is a helper function to get all quantizable ops from model.
Args:
model (object): input model which is PyTorch model
Returns:
q_capability (dictionary): tuning capability for each op from model.
"""
tmp_model = model
tmp_model.eval()
quantizable_ops = []
self._get_quantizable_ops_recursively(tmp_model, '', quantizable_ops)
capability = self.query_handler.get_quantization_capability()['dynamic'] \
if self.approach == "post_training_dynamic_quant" else \
self.query_handler.get_quantization_capability()['quant_aware'] \
if self.approach == "quant_aware_training" else \
self.query_handler.get_quantization_capability()['int8']
q_capability = {}
q_capability['optypewise'] = OrderedDict()
q_capability['opwise'] = OrderedDict()
if self.approach == "post_training_dynamic_quant":
capability_pair = [
(self.query_handler.get_quantization_capability()['dynamic'], 'dynamic')]
elif self.approach == "quant_aware_training":
capability_pair = [
(self.query_handler.get_quantization_capability()['quant_aware'], 'static')]
elif self.approach == "post_training_static_quant":
capability_pair = [
(self.query_handler.get_quantization_capability()['int8'], 'static')]
else:
capability_pair = [
(self.query_handler.get_quantization_capability()['int8'], 'static'),
(self.query_handler.get_quantization_capability()['dynamic'], 'dynamic')]
fp32_config = {'activation': {'dtype': 'fp32'}, 'weight': {'dtype': 'fp32'}}
# Ignore LayerNorm, InstanceNorm3d and Embedding quantizable ops,
# due to huge accuracy regression in PyTorch.
if isinstance(self, PyTorch_IPEXAdaptor):
additional_skipped_module_classes = {}
else:
additional_skipped_module_classes = {'LayerNorm', 'InstanceNorm3d', 'Dropout'}
no_fp32_ops = {'QuantStub'}
for pair in capability_pair:
capability, mode = pair
for q_op in quantizable_ops:
if q_op not in q_capability['opwise']:
q_capability['opwise'][q_op] = []
if q_op[1] not in q_capability['optypewise']:
q_capability['optypewise'][q_op[1]] = []
if mode == 'static' and self.approach != "quant_aware_training" and \
q_op[1] in ['LSTM', 'GRU', 'LSTMCell', 'GRUCell', 'RNNCell']:
continue
op_cfg = copy.deepcopy(capability[q_op[1]]) if q_op[1] in capability \
else copy.deepcopy(capability['default'])
op_cfg['activation']['quant_mode'] = mode if q_op[1] not in \
['LSTM', 'GRU', 'LSTMCell', 'GRUCell', 'RNNCell'] else 'dynamic'
# skip the op that only include fp32
if q_op[1] not in additional_skipped_module_classes:
if op_cfg not in q_capability['opwise'][q_op]:
q_capability['opwise'][q_op].append(op_cfg)
if op_cfg not in q_capability['optypewise'][q_op[1]]:
q_capability['optypewise'][q_op[1]].append(op_cfg)