-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathquantization_pass.py
3617 lines (3323 loc) · 144 KB
/
quantization_pass.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
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 collections
import logging
import numpy as np
try:
from tqdm import tqdm
except:
from .utils import tqdm
import paddle
from ...base.framework import IrGraph, IrNode
from ...framework import _get_paddle_place, core
from ...static import Program, data, program_guard, scope_guard
from ...utils import unique_name
from ..log_helper import get_logger
from . import utils
from .quant_config import (
SUPPORT_ACT_QUANTIZATION_OP_DICT,
SUPPORT_QUANTIZATION_OP_DICT,
SUPPORT_WEIGHT_QUANTIZATION_OP_DICT,
)
_logger = get_logger(
__name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s'
)
_fake_quant_op_list = [
'fake_quantize_abs_max',
'fake_quantize_range_abs_max',
'fake_quantize_moving_average_abs_max',
'fake_channel_wise_quantize_abs_max',
]
_fake_dequant_op_list = [
'fake_dequantize_max_abs',
'fake_channel_wise_dequantize_max_abs',
]
_fake_quant_dequant_op_list = [
'fake_quantize_dequantize_moving_average_abs_max',
"fake_channel_wise_quantize_dequantize_abs_max",
"fake_quantize_dequantize_abs_max",
]
_conv_ops = ['conv2d', 'depthwise_conv2d', 'conv2d_transpose']
_SCALE_DEFAULT_VALUE = 0.001
def _init_var_node(var_node, value, scope, place):
assert isinstance(
value, np.ndarray
), 'The type of value should be numpy array.'
assert scope is not None, 'The scope cannot be set None.'
assert place is not None, 'The place cannot be set None.'
tensor = scope.var(var_node.name()).get_tensor()
tensor.set(value, place)
def _is_input_all_not_persistable(graph, op_node):
'''
Analyse the real inputs of the op node are all not persistable.
'''
is_input_all_not_persistable = True
for var_name in utils._get_op_input_var_names(op_node):
in_node = graph._find_node_by_name(op_node.inputs, var_name)
is_input_all_not_persistable = is_input_all_not_persistable and (
not in_node.persistable()
)
return is_input_all_not_persistable
class QuantizationTransformPass:
"""
Quantize the ops that have weights. Add quant and dequant ops for
the quantized ops's inputs.
"""
def __init__(
self,
scope=None,
place=None,
weight_bits=8,
activation_bits=8,
activation_quantize_type='abs_max',
weight_quantize_type='abs_max',
window_size=10000,
moving_rate=0.9,
skip_pattern=['skip_quant'],
quantizable_op_type=['conv2d', 'depthwise_conv2d', 'mul'],
weight_quantize_func=None,
act_quantize_func=None,
weight_preprocess_func=None,
act_preprocess_func=None,
optimizer_func=None,
executor=None,
is_test=None,
):
r"""
Constructor.
Args:
scope(static.Scope): When activation use 'range_abs_max' as the quantize
type, this pass will create some new parameters. The scope is used to
initialize these new parameters.
place(static.CPUPlace|static.CUDAPlace|str): place is used to initialize new
parameters described above. If it's string, It can be ``cpu``, and ``gpu:x``,
where ``x`` is the index of the GPUs.
weight_bits(int): quantization bit number for weights,
the bias is not quantized.
activation_bits(int): quantization bit number for activation.
activation_quantize_type(str): quantization type for activation,
now support 'abs_max', 'range_abs_max' and 'moving_average_abs_max'.
If use 'abs_max' mode, the quantization scale will be calculated
dynamically each step in both training and testing period. If use
'range_abs_max', a static quantization scale will be calculated
during training and used in inference.
weight_quantize_type(str): quantization type for weights,
support 'abs_max' and 'channel_wise_abs_max'. The 'range_abs_max'
usually is not used for weight, since weights are fixed once the
model is well trained.
window_size(int): the window size for 'range_abs_max' quantization.
moving_rate(float): the param for 'moving_average_abs_max' quantization.
skip_pattern(str or str list): The user-defined quantization skip pattern, which
will be presented in the name scope of an op. When the skip pattern is
detected in an op's name scope, the corresponding op will not be quantized.
quantizable_op_type(list[str]): List the type of ops that will be quantized.
Default is ["conv2d", "depthwise_conv2d", "mul"]. The quantizable_op_type in
QuantizationFreezePass and ConvertToInt8Pass must be the same as this.
weight_quantize_func(function): Function that defines how to quantize weight.
Using this can quickly test if user's quantization method works or not.
In this function, user should both define quantization function and
dequantization function, that is, the function's input is non-quantized
weight and function returns dequantized weight. If None, will use
quantization op defined by 'weight_quantize_type'. Default is None.
act_quantize_func(function): Function that defines how to quantize activation.
Using this can quickly test if user's quantization method works or not.
In this function, user should both define quantization and dequantization
process, that is, the function's input is non-quantized activation and
function returns dequantized activation. If None, will use quantization
op defined by 'activation_quantize_type'. Default is None.
weight_preprocess_func(function): Function that defines how to preprocess
weight before quantization. Using this can quickly test if user's preprocess
method works or not. The function's input is non-quantized weight and
function returns processed weight to be quantized. If None, the weight will
be quantized directly. Default is None.
act_preprocess_func(function): Function that defines how to preprocess
activation before quantization. Using this can quickly test if user's
preprocess method works or not. The function's input is non-quantized
activation and function returns processed activation to be quantized.
If None, the activation will be quantized directly. Default is None.
optimizer_func(function): Function return a optimizer. When 'is_test' is
False and user want to use self-defined quantization function and
preprocess function, this function must be set. Default is None.
executor(base.Executor): If user want to use self-defined quantization
function and preprocess function, executor must be set for initialization.
Default is None.
Examples:
.. code-block:: python
>>> # The original graph will be rewrite.
>>> import paddle.static as static
>>> from paddle.static.quantization import QuantizationTransformPass
>>> from paddle.base.framework import IrGraph
>>> from paddle.framework import core
>>> graph = IrGraph(core.Graph(static.Program().desc), for_test=False)
>>> place = paddle.CPUPlace()
>>> transform_pass = QuantizationTransformPass(static.global_scope(), place)
>>> transform_pass.apply(graph)
"""
self._scope = scope
self._place = _get_paddle_place(place)
self._weight_bits = weight_bits
self._activation_bits = activation_bits
self._skip_pattern = skip_pattern
self._weight_quantize_func = weight_quantize_func
self._act_quantize_func = act_quantize_func
self._weight_preprocess_func = weight_preprocess_func
self._act_preprocess_func = act_preprocess_func
self._optimizer = optimizer_func
self._exe = executor
quant_type = [
'abs_max',
'channel_wise_abs_max',
'range_abs_max',
'moving_average_abs_max',
]
assert (
activation_quantize_type != 'channel_wise_abs_max'
), "The activation quantization type does not support 'channel_wise_abs_max'."
if activation_quantize_type not in quant_type:
raise ValueError(
"Unknown activation_quantize_type : '%s'. It can only be "
"'abs_max' or 'range_abs_max' or 'moving_average_abs_max'."
% (str(activation_quantize_type))
)
if weight_quantize_type not in quant_type:
raise ValueError(
"Unknown weight_quantize_type: '%s'. It can only be "
"'abs_max' or 'channel_wise_abs_max' or 'range_abs_max' "
"or 'moving_average_abs_max'." % (str(weight_quantize_type))
)
self._activation_quantize_type = activation_quantize_type
self._weight_quantize_type = weight_quantize_type
self._window_size = window_size
self._moving_rate = moving_rate
self._quantizable_ops = quantizable_op_type
for op in self._quantizable_ops:
assert op in list(SUPPORT_WEIGHT_QUANTIZATION_OP_DICT.keys()), (
op + " is not supported for quantization."
)
self._quantizable_grad_ops = [
'%s_grad' % (op) for op in self._quantizable_ops
]
self._is_test = is_test
self._global_step = None
self.create_var_map = {}
self.create_op_map = {}
def apply(self, graph):
"""
Quantize the graph for training process. According to weight and
activation quantization type, the graph will be added some fake
quantize operators and fake dequantize operators.
Args:
graph(IrGraph): the applied graph.
Returns:
None
"""
assert isinstance(
graph, IrGraph
), 'graph must be the instance of IrGraph.'
if self._is_test is None:
self._is_test = graph.is_test()
# marked the variable which has been dequantized.
dequantized_vars = collections.OrderedDict()
persistable_vars = [p.name() for p in graph.all_persistable_nodes()]
processed_vars = []
def _quant_preprocess(op_node):
user_skipped = False
if isinstance(self._skip_pattern, list):
user_skipped = op_node.op().has_attr("op_namescope") and any(
pattern in op_node.op().attr("op_namescope")
for pattern in self._skip_pattern
)
elif isinstance(self._skip_pattern, str):
user_skipped = (
op_node.op().has_attr("op_namescope")
and op_node.op()
.attr("op_namescope")
.find(self._skip_pattern)
!= -1
)
if user_skipped:
op_node.op()._set_attr("skip_quant", True)
op_node.op()._set_attr("with_quant_attr", True)
def _transform_forward(graph, op):
op.op()._set_attr("quantization_type", "qat_with_weight")
op.op()._set_attr("with_quant_attr", True)
op_role = op.op().attr("op_role")
inputs = op.inputs
for var_node in inputs:
if var_node.name() not in op.input_arg_names():
continue
if var_node.name() in dequantized_vars:
dequant_var_node = dequantized_vars[var_node.name()]
else:
name = var_node.name()
if name in processed_vars:
continue
is_weight = (
True if var_node.name() in persistable_vars else False
)
# if var node is weight and weight_preprocess_func is not None,
# will insert weight preprocess func
# to preprocess weight before quantization
# if var node is activation and act_preprocess_func is not None,
# will insert activation preprocess func
# to preprocess activation before quantization
if is_weight and self._weight_preprocess_func is not None:
var_node = self._insert_func(
graph, self._weight_preprocess_func, var_node, op
)
elif (
not is_weight and self._act_preprocess_func is not None
):
var_node = self._insert_func(
graph, self._act_preprocess_func, var_node, op
)
# if var node is weight and weight_quantize_func is not None,
# will insert weight quantize func to quantize and dequantize weight
# if var node is activation and act_quantize_func is not None,
# will insert act quantize func to quantize and dequantize activation
if is_weight and self._weight_quantize_func is not None:
target_out_node = self._insert_func(
graph, self._weight_quantize_func, var_node, op
)
processed_vars.append(name)
continue
elif not is_weight and self._act_quantize_func is not None:
target_out_node = self._insert_func(
graph, self._act_quantize_func, var_node, op
)
processed_vars.append(name)
continue
quant_bits = (
self._weight_bits
if var_node.name() in persistable_vars
else self._activation_bits
)
quant_type = (
self._weight_quantize_type
if is_weight
else self._activation_quantize_type
)
if (
quant_type == 'channel_wise_abs_max'
): # Weight quantization
op_type = op.name()
trans_y = (op_type == 'matmul_v2') and op.op().attr(
'trans_y'
)
op_type = op_type + '_trans_y' if trans_y else op_type
quant_axis = (
1
if op_type in utils._channelwise_quant_axis1_ops
else 0
)
(
quant_var_node,
scale_var_node,
) = self._insert_channel_quant_op(
graph,
var_node,
name,
quant_bits,
quant_axis,
op_role,
)
dequant_var_node = self._insert_channel_dequant_op(
graph,
quant_var_node,
[scale_var_node],
[quant_bits],
quant_axis,
op_role,
)
else:
quant_var_node, scale_var_node = self._insert_quant_op(
graph,
var_node,
name,
quant_bits,
quant_type,
op_role,
)
dequant_var_node = self._insert_dequant_op(
graph,
quant_var_node,
scale_var_node,
quant_bits,
op_role,
)
dequantized_vars[name] = dequant_var_node
graph.update_input_link(var_node, dequant_var_node, op)
def _transform_backward(graph, op):
for var_node in op.inputs:
if var_node.name() not in op.input_arg_names():
continue
if var_node.name() in dequantized_vars:
dequant_var_node = dequantized_vars[var_node.name()]
graph.update_input_link(var_node, dequant_var_node, op)
def _has_weight(op):
has_weight = False
for var_node in op.inputs:
if var_node.name() not in op.input_arg_names():
continue
name = var_node.name()
if var_node.name() in persistable_vars:
has_weight = True
return has_weight
if not self._is_test:
self._create_global_step(graph)
ops = graph.all_op_nodes()
# Do the preprocess of quantization, such as skipping some ops
# for not being quantized.
for op in ops:
if (
op.name() in self._quantizable_ops
or op.name() in self._quantizable_grad_ops
):
_quant_preprocess(op)
# Insert mapping table to solve the problem in saving inference model.
graph.out_node_mapping_table = {}
# The process of _transform_forward and _transform_backward is needed in two for loops.
# The loop for transforming the forward graph:
with tqdm(
total=len(ops),
bar_format='Adding quant op with weight:|{bar}| {n_fmt}/{total_fmt}',
ncols=80,
) as t:
for op in ops:
if op.name() in self._quantizable_ops:
if not self._is_skip_quant(graph, op) and _has_weight(op):
_transform_forward(graph, op)
t.update()
# The loop for renaming the inputs of backward op.
for op in ops:
if op.name() in self._quantizable_grad_ops and _has_weight(op):
_transform_backward(graph, op)
graph.resolve_hazard()
return graph
def _create_global_step(self, graph):
if (
self._weight_quantize_type == 'range_abs_max'
or self._activation_quantize_type == 'range_abs_max'
):
counter_name = '@STEP_COUNTER@'
for node in graph.all_var_nodes():
if node.name() == counter_name:
self._global_step = node
if self._global_step is None:
global_step_in = graph.create_persistable_node(
name=counter_name,
var_type=core.VarDesc.VarType.LOD_TENSOR,
shape=[1],
var_dtype=core.VarDesc.VarType.INT64,
)
_init_var_node(
global_step_in,
np.zeros([1], dtype='int64'),
self._scope,
self._place,
)
global_step_out = graph.create_var_node_from_desc(
global_step_in.var()
)
# The attribute of `op_role` is needed by ParallelExecutor.
increment_op = graph.create_op_node(
op_type='increment',
attrs={
'step': 1.0,
'op_role': core.op_proto_and_checker_maker.OpRole.Forward,
},
inputs={'X': global_step_in},
outputs={'Out': global_step_out},
)
graph.link_to(global_step_in, increment_op)
graph.link_to(increment_op, global_step_out)
self._global_step = global_step_out
def _insert_quant_op(
self, graph, var_node, name, quant_bits, quant_type, op_role
):
"""
Insert fake_quantize_op in the graph.
"""
if quant_type == 'abs_max':
return self._insert_quant_abs_max_op(
graph, var_node, name, quant_bits, op_role
)
elif quant_type == 'range_abs_max':
return self._insert_quant_range_abs_max_op(
graph, var_node, name, quant_bits, op_role
)
elif quant_type == 'moving_average_abs_max':
return self._insert_quant_moving_average_abs_max_op(
graph, var_node, name, quant_bits, op_role
)
def _insert_quant_abs_max_op(
self, graph, var_node, name, quant_bits, op_role
):
"""
Insert fake_quantize_abs_max op in the graph.
"""
assert var_node.is_var(), f'{var_node.name()} is not a var'
quant_var_node = graph.create_var_node(
name=self._quantized_var_name(name),
var_type=var_node.type(),
shape=var_node.shape(),
var_dtype=var_node.dtype(),
)
scale_name = self._quantized_scale_name(name)
if var_node.dtype() == paddle.float64:
data_type = 'float64'
elif var_node.dtype() == paddle.float32:
data_type = 'float32'
else:
data_type = "float16"
try:
scale_value = np.array(
self._scope.find_var(scale_name).get_tensor()
)
except:
scale_value = np.zeros([1], dtype=data_type)
scale_var_node = graph.create_persistable_node(
name=scale_name,
var_type=var_node.type(),
shape=[1],
var_dtype=var_node.dtype(),
)
_init_var_node(scale_var_node, scale_value, self._scope, self._place)
quant_op_node = graph.create_op_node(
op_type='fake_quantize_abs_max',
attrs={'bit_length': quant_bits, 'op_role': op_role},
inputs={'X': var_node},
outputs={'Out': quant_var_node, 'OutScale': scale_var_node},
)
graph.link_to(var_node, quant_op_node)
graph.link_to(quant_op_node, quant_var_node)
graph.link_to(quant_op_node, scale_var_node)
return quant_var_node, scale_var_node
def _insert_quant_range_abs_max_op(
self, graph, var_node, name, quant_bits, op_role
):
"""
Insert fake_quantize_range_abs_max on the graph.
"""
assert var_node.is_var(), f'{var_node.name()} is not a var'
quant_var_node = graph.create_var_node(
name=self._quantized_var_name(name),
var_type=var_node.type(),
shape=var_node.shape(),
var_dtype=var_node.dtype(),
)
scale_name = self._quantized_scale_name(name)
if var_node.dtype() == paddle.float64:
data_type = 'float64'
elif var_node.dtype() == paddle.float32:
data_type = 'float32'
else:
data_type = "float16"
try:
scale_value = np.array(
self._scope.find_var(scale_name).get_tensor()
)
except:
scale_value = np.array([_SCALE_DEFAULT_VALUE], dtype=data_type)
scale_in_node = graph.create_persistable_node(
name=scale_name,
var_type=core.VarDesc.VarType.LOD_TENSOR,
shape=[1],
var_dtype=var_node.dtype(),
)
_init_var_node(scale_in_node, scale_value, self._scope, self._place)
scale_out_node = graph.create_var_node_from_desc(scale_in_node.var())
inputs = {'X': var_node, 'InScale': scale_in_node}
outputs = {'Out': quant_var_node, 'OutScale': scale_out_node}
if not self._is_test:
# The name of scales_var_node maybe 'scales_0', 'scales_1', etc.
scales_node = graph.create_persistable_node(
name=unique_name.generate('scales'),
var_type=core.VarDesc.VarType.LOD_TENSOR,
shape=[self._window_size],
var_dtype=var_node.dtype(),
)
if var_node.dtype() == paddle.float64:
data_type = 'float64'
elif var_node.dtype() == paddle.float32:
data_type = 'float32'
else:
data_type = "float16"
_init_var_node(
scales_node,
np.zeros([self._window_size], dtype=data_type),
self._scope,
self._place,
)
inputs['Iter'] = self._global_step
outputs['OutScales'] = scales_node
attrs = {
'window_size': self._window_size,
'bit_length': quant_bits,
'is_test': self._is_test,
'op_role': op_role,
}
quant_op_node = graph.create_op_node(
op_type='fake_quantize_range_abs_max',
attrs=attrs,
inputs=inputs,
outputs=outputs,
)
graph.link_to(var_node, quant_op_node)
graph.link_to(scale_in_node, quant_op_node)
graph.link_to(quant_op_node, quant_var_node)
graph.link_to(quant_op_node, scale_out_node)
if not self._is_test:
graph.link_to(self._global_step, quant_op_node)
graph.link_to(quant_op_node, scales_node)
return quant_var_node, scale_out_node
def _insert_quant_moving_average_abs_max_op(
self, graph, var_node, name, quant_bits, op_role
):
"""Insert fake_quantize_moving_average_abs_max"""
quant_var_node = graph.create_var_node(
name=self._quantized_var_name(name),
var_type=var_node.type(),
shape=var_node.shape(),
var_dtype=var_node.dtype(),
)
scale_name = self._quantized_scale_name(name)
if var_node.dtype() == paddle.float64:
data_type = 'float64'
elif var_node.dtype() == paddle.float32:
data_type = 'float32'
else:
data_type = "float16"
try:
scale_value = np.array(
self._scope.find_var(scale_name).get_tensor()
)
except:
scale_value = np.array([_SCALE_DEFAULT_VALUE], dtype=data_type)
scale_in_node = graph.create_persistable_node(
name=scale_name,
var_type=core.VarDesc.VarType.LOD_TENSOR,
shape=[1],
var_dtype=var_node.dtype(),
)
_init_var_node(scale_in_node, scale_value, self._scope, self._place)
scale_out_node = graph.create_var_node_from_desc(scale_in_node.var())
ins = {'X': var_node, 'InScale': scale_in_node}
outs = {'Out': quant_var_node, 'OutScale': scale_out_node}
if not self._is_test:
state_in_node = graph.create_persistable_node(
name=unique_name.generate('state'),
var_type=core.VarDesc.VarType.LOD_TENSOR,
var_dtype=var_node.dtype(),
shape=[1],
)
if var_node.dtype() == paddle.float64:
data_type = 'float64'
elif var_node.dtype() == paddle.float32:
data_type = 'float32'
else:
data_type = "float16"
_init_var_node(
state_in_node,
np.ones([1], dtype=data_type),
self._scope,
self._place,
)
accum_in_node = graph.create_persistable_node(
name=unique_name.generate('accum'),
var_type=core.VarDesc.VarType.LOD_TENSOR,
var_dtype=var_node.dtype(),
shape=[1],
)
_init_var_node(
accum_in_node,
np.ones([1], dtype=data_type),
self._scope,
self._place,
)
state_out_node = graph.create_var_node_from_desc(
state_in_node.var()
)
accum_out_node = graph.create_var_node_from_desc(
accum_in_node.var()
)
ins['InState'] = state_in_node
ins['InAccum'] = accum_in_node
outs['OutState'] = state_out_node
outs['OutAccum'] = accum_out_node
attrs = {
'bit_length': quant_bits,
'moving_rate': self._moving_rate,
'is_test': self._is_test,
'op_role': op_role,
}
quant_op_node = graph.create_op_node(
op_type='fake_quantize_moving_average_abs_max',
attrs=attrs,
inputs=ins,
outputs=outs,
)
graph.link_to(var_node, quant_op_node)
graph.link_to(scale_in_node, quant_op_node)
graph.link_to(quant_op_node, quant_var_node)
graph.link_to(quant_op_node, scale_out_node)
if not self._is_test:
graph.link_to(state_in_node, quant_op_node)
graph.link_to(accum_in_node, quant_op_node)
graph.link_to(quant_op_node, state_out_node)
graph.link_to(quant_op_node, accum_out_node)
return quant_var_node, scale_out_node
def _insert_channel_quant_op(
self, graph, var_node, name, quant_bits, quant_axis, op_role
):
"""
Insert fake_channel_wise_quantize_abs_max op in the graph.
"""
assert var_node.is_var(), f'{var_node.name()} is not a var'
quant_var_node = graph.create_var_node(
name=self._quantized_var_name(name),
var_type=var_node.type(),
shape=var_node.shape(),
var_dtype=var_node.dtype(),
)
scale_name = self._quantized_scale_name(name)
if var_node.dtype() == paddle.float64:
data_type = 'float64'
elif var_node.dtype() == paddle.float32:
data_type = 'float32'
else:
data_type = "float16"
try:
scale_value = np.array(
self._scope.find_var(scale_name).get_tensor()
)
except:
scale_value = np.zeros(
[var_node.shape()[quant_axis]], dtype=data_type
)
scale_var_node = graph.create_persistable_node(
name=self._quantized_scale_name(name),
var_type=var_node.type(),
shape=[var_node.shape()[quant_axis]],
var_dtype=var_node.dtype(),
)
_init_var_node(scale_var_node, scale_value, self._scope, self._place)
quant_op_node = graph.create_op_node(
op_type='fake_channel_wise_quantize_abs_max',
attrs={
'bit_length': quant_bits,
'quant_axis': quant_axis,
'is_test': self._is_test,
'op_role': op_role,
},
inputs={'X': var_node},
outputs={'Out': quant_var_node, 'OutScale': scale_var_node},
)
graph.link_to(var_node, quant_op_node)
graph.link_to(quant_op_node, quant_var_node)
graph.link_to(quant_op_node, scale_var_node)
return quant_var_node, scale_var_node
def _insert_dequant_op(
self, graph, var_node, scale_var_node, quant_bits, op_role
):
"""
Insert fake_dequantize_op in the graph.
"""
assert var_node.is_var(), f'{var_node.name()} is not a var'
dequant_var_node = graph.create_var_node(
name=self._dequantized_var_name(var_node.name()),
var_type=var_node.type(),
shape=var_node.shape(),
var_dtype=var_node.dtype(),
)
max_range = (1 << (quant_bits - 1)) - 1
dequant_op_node = graph.create_op_node(
op_type='fake_dequantize_max_abs',
attrs={'max_range': float(max_range), 'op_role': op_role},
inputs={'X': var_node, 'Scale': scale_var_node},
outputs={'Out': dequant_var_node},
)
graph.link_to(var_node, dequant_op_node)
graph.link_to(scale_var_node, dequant_op_node)
graph.link_to(dequant_op_node, dequant_var_node)
return dequant_var_node
def _insert_channel_dequant_op(
self, graph, var_node, scale_var_nodes, quant_bits, quant_axis, op_role
):
"""
Insert fake_channel_wise_dequantize_max_abs in the graph.
"""
assert var_node.is_var(), f'{var_node.name()} is not a var'
dequant_var_node = graph.create_var_node(
name=self._dequantized_var_name(var_node.name()),
var_type=var_node.type(),
shape=var_node.shape(),
var_dtype=var_node.dtype(),
)
dequant_op_node = graph.create_op_node(
op_type='fake_channel_wise_dequantize_max_abs',
attrs={
'quant_bits': quant_bits,
'quant_axis': quant_axis,
'op_role': op_role,
},
inputs={'X': var_node, 'Scales': scale_var_nodes},
outputs={'Out': dequant_var_node},
)
graph.link_to(var_node, dequant_op_node)
for scale_n in scale_var_nodes:
graph.link_to(scale_n, dequant_op_node)
graph.link_to(dequant_op_node, dequant_var_node)
return dequant_var_node
def _create_new_node(self, graph, in_node):
"""
create a node that same with in_node in graph
Args:
graph(IrGraph): create node in graph.
in_node(IrVarNode): create node that same with in_node.
Returns:
created new node
"""
key = ''
for inp in in_node.inputs:
key = key + inp.name()
key = key + in_node.name()
for inp in in_node.outputs:
key = key + inp.name()
if key in self.create_var_map.keys():
new_node = self.create_var_map[key]
elif in_node.is_ctrl_var():
new_node = graph.create_control_dep_var()
self.create_var_map[key] = new_node
else:
new_node = graph.create_var_node_from_desc(in_node.node.var())
self.create_var_map[key] = new_node
return new_node
def _copy_graph(self, graph, source_graph, op_node):
"""
copy op_node in source_graph to graph. And will run recursively
for next ops that link to op_node's outputs.
Args:
graph(IrGraph): target graph to copy.
source_graph(IrGraph): source graph to copy.
op_node(IrOpNode): op node in source_graph.
Returns:
None
"""
key = ''
for inp in op_node.inputs:
key = key + inp.name()
key = key + op_node.name()
for inp in op_node.outputs:
key = key + inp.name()
has_created = False
if key in self.create_op_map.keys():
new_op_node = self.create_op_map[key]
has_created = True
else:
new_op_node = graph.create_op_node_from_desc(op_node.node.op())
self.create_op_map[key] = new_op_node
if has_created:
return
for in_node in op_node.inputs:
new_node = self._create_new_node(graph, in_node)
graph.link_to(new_node, new_op_node)
for in_node in op_node.outputs:
new_node = self._create_new_node(graph, in_node)
graph.link_to(new_op_node, new_node)
for var_node in op_node.outputs:
for next_op_node in var_node.outputs:
self._copy_graph(graph, source_graph, next_op_node)
return
def _insert_func(self, graph, func, var_node, op):
"""
Insert a tmp program that returned by func between var_node and op.
Args:
graph(IrGraph): target graph to insert tmp program.
func(Function): function to define a tmp program
var_node(IrVarNode): node in target graph.
op(IrOpNode): op in target graph.
Returns:
op's new input that replaces var_node
"""
tmp_program = Program()
startup_program = Program()
with program_guard(tmp_program, startup_program):
with tmp_program.switch_name_generator_guard(var_node.name() + "_"):
in_node = data(
var_node.name() + '_tmp_input',
shape=var_node.shape(),
dtype='float32',
)
out_node = func(in_node)
graph.out_node_mapping_table[out_node.name] = var_node.name()
# loss shape must be 1 when minimize
loss = paddle.mean(out_node)
if not graph._for_test:
assert (
self._optimizer
), "optimizer_func must be set when graph is test graph"
in_node.stop_gradient = False
optimizer = self._optimizer()
optimizer.minimize(loss)
with scope_guard(self._scope):
self._exe.run(startup_program)
tmp_graph = IrGraph(
core.Graph(tmp_program.desc), for_test=graph._for_test
)
in_node = tmp_graph._find_node_by_name(
tmp_graph.all_var_nodes(), in_node.name
)
out_node = tmp_graph._find_node_by_name(
tmp_graph.all_var_nodes(), out_node.name
)
in_node_params = []
in_op_node = []
# copy tmp graph to graph, after that, we can insert tmp graph's copy to graph.
for node in tmp_graph.all_var_nodes():
if node.inputs == [] and node.persistable():
in_node_params.append(node)
for node in tmp_graph.all_op_nodes():
if node.inputs == []:
in_op_node.append(node)
for node in in_node.outputs:
self._copy_graph(graph, tmp_graph, node)
for node in in_node_params:
for op_node in node.outputs:
self._copy_graph(graph, tmp_graph, op_node)
for node in in_op_node:
self._copy_graph(graph, tmp_graph, node)
target_in_node = graph._find_node_by_name(
graph.all_var_nodes(), in_node.name()
)
target_out_node = graph._find_node_by_name(
graph.all_var_nodes(), out_node.name()
)
loss_node = graph._find_node_by_name(graph.all_var_nodes(), loss.name)
outputs = target_in_node.outputs
for node in outputs:
graph.update_input_link(target_in_node, var_node, node)
graph.update_input_link(var_node, target_out_node, op)
# update grad
if not graph._for_test:
op_out = op.outputs[0]
op_out_grad = graph._find_node_by_name(
graph.all_var_nodes(), op_out.name() + "@GRAD"
)
# find op's gradient op, such as conv2d_grad
op_grad = op_out_grad.outputs[0]
target_out_grad_node = graph._find_node_by_name(
graph.all_var_nodes(), target_out_node.name() + "@GRAD"
)
in_node_grad = graph._find_node_by_name(
graph.all_var_nodes(), target_in_node.name() + "@GRAD"
)