-
Notifications
You must be signed in to change notification settings - Fork 351
/
Copy pathreconstruction_quantization.py
1244 lines (1137 loc) · 50.9 KB
/
reconstruction_quantization.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 copy
import logging
import sys
import time
import numpy as np
import paddle
from paddle.static.quantization import utils
from paddle.static.quantization import PostTrainingQuantization
from ..dist import merge
from ..core.graph_wrapper import GraphWrapper
from ..common import get_logger
__all__ = [
'ReconstructionQuantization',
]
_logger = get_logger(
__name__,
logging.INFO,
fmt='%(asctime)s-%(levelname)s: %(message)s', )
GAMMA = -0.1
ZETA = 1.1
class Collections(object):
def __init__(self, **kwargs):
self._config = dict()
for k, v in kwargs.items():
self._config[k] = v
def _get_config(self):
return self._config
class ReconstructionQuantization(PostTrainingQuantization):
"""
Utilizing reconstruction quantization method to quantize the FP32 model,
and it uses calibrate data to get the quantization information for all
quantized variables.
"""
def __init__(self, PTQCollections, RSQCollections):
'''
Args:
PTQCollections(Collections): The parameters set required for post training quantization.
RSQCollections(Collections): The parameters set required for reconstruction quantization.
Returns:
None
'''
super().__init__(**PTQCollections._get_config())
self._config = RSQCollections._get_config()
def quantize(self):
'''
Load the FP32 model, and use the calibrate data to calculate the forward-stage.
Based on the sample data, we can get the quantization information, and obtain
the final quantized model.
Args:
None
Returns:
the program of quantized model.
'''
self._load_model_data()
self._collect_target_varnames()
self._set_activation_persistable()
if self._algo in ["KL", "hist"]:
self._preparation()
self._sampling_threshold()
self._calculate_threshold()
self._reset_activation_persistable()
self._reconstruction()
self._postprocessing()
return self._program
def _preparation(self):
batch_id = 0
with utils.tqdm(
total=self._batch_nums,
bar_format=
'Preparation stage, Run batch:|{bar}| {n_fmt}/{total_fmt}',
ncols=80, ) as t:
for data in self._data_loader():
self._executor.run(
program=self._program,
feed=data,
fetch_list=self._fetch_list,
return_numpy=False,
scope=self._scope, )
self._collect_activation_abs_min_max()
batch_id += 1
t.update()
if self._batch_nums and batch_id >= self._batch_nums:
break
self._init_sampling_act_histogram()
def _sampling_threshold(self):
batch_id = 0
with utils.tqdm(
total=self._batch_nums,
bar_format=
'Sampling stage, Run batch:|{bar}| {n_fmt}/{total_fmt}',
ncols=80, ) as t:
for data in self._data_loader():
self._executor.run(
program=self._program,
feed=data,
fetch_list=self._fetch_list,
return_numpy=False,
scope=self._scope, )
self._sampling()
batch_id += 1
t.update()
if self._batch_nums and batch_id >= self._batch_nums:
break
def _calculate_threshold(self):
if self._algo == 'avg':
for var_name in self._quantized_act_var_name:
self._quantized_threshold[var_name] = \
np.array(self._quantized_var_avg[var_name]).mean()
self._scale_dict = self._quantized_threshold
elif self._algo in ["KL", "hist"]:
self._calculate_kl_hist_threshold()
self._scale_dict = self._quantized_var_threshold
else:
self._scale_dict = self._quantized_threshold
def _reconstruction(self):
reconstruction_quanter = ReconstructionQuanter(
data_loader=self._data_loader,
fp32_program=self._program,
feed_list=self._feed_list,
fetch_list=self._fetch_list,
exe=self._executor,
scope=self._scope,
place=self._place,
quantized_op_pairs=self._quantized_op_pairs,
weight_op_pairs=self._weight_op_pairs,
weight_quantize_type=self._weight_quantize_type,
activation_bits=self._activation_bits,
weight_bits=self._weight_bits,
scale_dict=copy.deepcopy(self._scale_dict),
regions=self._config['regions'],
region_weights_names=self._config['region_weights_names'],
recon_level=self._config['recon_level'],
simulate_activation_quant=self._config['simulate_activation_quant'],
skip_tensor_list=self._skip_tensor_list,
num_iterations=self._batch_nums,
lr=self._config['lr'],
bias_correction=self._bias_correction,
epochs=self._config['epochs'],
limit=self._config['limit'])
self._program, self._scale_dict = reconstruction_quanter._run()
if self._algo in ["KL", "hist"]:
self._quantized_var_threshold = self._scale_dict
else:
self._quantized_threshold = self._scale_dict
def _postprocessing(self):
if self._algo == 'min_max':
self._save_input_threhold()
else:
self._update_program()
# save out_threshold for quantized ops.
self._save_output_threshold()
if any(op_type in self.quant_config.activation_quant_operation_types
for op_type in self._dynamic_quantize_op_type):
self._collect_dynamic_quantize_op_threshold(
self._dynamic_quantize_op_type)
# Move sub blocks persistable var to global block
global_block = self._program.global_block()
for _op in global_block.ops:
if _op.type == "while":
_block_id = _op.attr("sub_block").id
_block = self._program.block(_block_id)
persistables = []
for _name, _var in _block.vars.items():
if _var.persistable:
global_block._clone_variable(_var)
persistables.append(_name)
for _name in persistables:
_block._remove_var(_name)
persistables.extend(_op.input('X'))
_op.desc.set_input("X", persistables)
class ReconstructionQuanter(object):
def __init__(self,
data_loader,
fp32_program,
feed_list,
fetch_list,
exe,
scope,
place,
quantized_op_pairs,
weight_op_pairs,
weight_quantize_type,
activation_bits,
weight_bits,
scale_dict,
regions,
region_weights_names,
recon_level,
simulate_activation_quant,
skip_tensor_list=None,
num_iterations=1000,
lr=0.1,
bias_correction=False,
epochs=20,
drop_prob=0.5,
limit=5):
'''
Reconstruction Quanter, used to optimize the rounding policy
by reconstructing the intermediate output.
Args:
data_loader(Python Generator, Paddle.io.DataLoader, optional): The
Generator or Dataloader provides calibrate data, and it could
return a batch every time.
executor(paddle.static.Executor): The executor to load, run and save the
quantized model.
scope(static.Scope, optional): The scope of the program, use it to load
and save variables. If scope=None, get scope by global_scope().
place(CPUPlace()|CUDAPlace(N)): This parameter represents
paddle run on which device.
quantized_op_pairs(dict, optional): Mapping of op's weight name
and output var name, where key of dict is the weight name of
op, and value is the output var name of op.
weight_quantize_type(str): quantization type for weights,
support 'abs_max' and 'channel_wise_abs_max'. This param only specifies
the fake ops in saving quantized model, and we save the scale obtained
by post training quantization in fake ops. Compared to 'abs_max',
the model accuracy is usually higher when it is 'channel_wise_abs_max'.
scale_dict(dict, optional): Mapping of var's name and var's scales, where key
of dict is the var name, and value is the quant scales of var.
recon_level(str, optional): The type of reconstruction granularity.
Currently support ['layer-wise', 'region-wise'] types. Default is layer-wise.
simulate_activation_quant(bool, optional): Whether we need the noise caused by activation
quantization during the reconstruction process.
skip_tensor_list(list): List of skip quant tensor name.
regions(list[list], optional): The list of some regions, each region is a subgraph of
fp32 program and it will have exact 1 input operation and 1 output operation. When
the recon-level is region, the reconstruction loss of each region is minimized.
Default is None.
region_weights_names(list[list], optional): The weight names inside every region.
Default is None.
lr(float, optional): The learning rate of Reconstruction Quanter. Default is 0.1.
bias_correction(bool, optional): If set as True, use the bias correction
method of https://arxiv.org/abs/1810.05723. Default is False.
drop_prob(float, optional): The dropout probability of activation quantization, and it is valid only if
simulate_activation_quant is True. Default is 0.5.
limit(int, optional): The size of each region. Default is 5.
Returns:
None
'''
assert recon_level in [
'layer-wise', 'region-wise'
], "recon_level must be one of the ['layer-wise', 'region-wise'], but received: {}".format(
recon_level)
self._simulate_activation_quant = simulate_activation_quant
self._program = fp32_program
self._data_loader = data_loader
self._recon_level = recon_level
self._feed_list = feed_list
self._fetch_list = fetch_list
self._exe = exe
self._scope = scope
self._place = place
self._quantized_op_pairs = quantized_op_pairs
self._weight_op_pairs = weight_op_pairs
self._weight_var_names = list(self._quantized_op_pairs.keys())
self._weight_quantize_type = weight_quantize_type
self._scale_dict = scale_dict
self._activation_bits = activation_bits
self._weight_bits = weight_bits
self._num_iterations = num_iterations
self._epochs = epochs
self._lr = lr
self._regions = regions
self._region_weights_names = region_weights_names
self._bias_correction = bias_correction
self._limit = limit
self._skip_tensor_list = skip_tensor_list
if recon_level == 'region-wise' and regions is None:
builder = RegionBuilder(program=self._program)
_logger.info('Begin Region division')
self._regions, self._region_weights_names = builder._create_regions(
limit=self._limit)
_logger.info('End Region division')
elif self._recon_level == 'layer-wise':
regions, region_weights_names = self._get_layers()
self._regions = regions
self._region_weights_names = region_weights_names
self._drop_prob = drop_prob
def _get_layers(self):
regions = []
region_weights_names = []
persistable_var_names = self._all_persistable_var_names()
self._input_weight_pairs = {}
for block_id in range(len(self._program.blocks)):
for op in self._program.blocks[block_id].ops:
in_var_names = utils._get_op_input_var_names(op)
for in_var_name in in_var_names:
if in_var_name in persistable_var_names:
in_var_names.remove(in_var_name)
self._input_weight_pairs[in_var_name] = in_var_names
break
for name in self._weight_var_names:
if self._skip_tensor_list is not None and name in self._skip_tensor_list:
continue
region_weights_names.append([name])
region_ = []
region_.append(self._input_weight_pairs[name][0])
region_.append(self._quantized_op_pairs[name])
regions.append(region_)
return regions, region_weights_names
def _preprocess(self):
if self._weight_quantize_type == 'channel_wise_abs_max':
for name in self._weight_var_names:
for i, s in enumerate(self._scale_dict[name]):
if s == 0.0:
self._scale_dict[name][i] = 1e-8
data_name_map = {}
for name in self._feed_list:
data_name_map[name] = name
self._student_program = self._program.clone()
merge(
self._program,
self._student_program,
data_name_map,
self._place,
teacher_scope=None,
name_prefix="teacher_",
merge_feed=True, )
self._graph = GraphWrapper(self._student_program)
if self._simulate_activation_quant:
self._insert_drop_quant_dequant()
self._insert_soft_rounding()
self._isolate_regions()
def _run(self):
self._preprocess()
startup_program = paddle.static.Program()
tmp_program = self._student_program.clone()
for k in range(len(self._regions)):
region_ = self._regions[k]
tmp_program.global_block().var(region_[0]).stop_gradient = True
quant_op_out_name = region_[1]
_logger.info(f"Region's input: {region_[0]} output: {region_[1]}")
names = self._region_weights_names[k]
_logger.info(f"Current quanted weights: {names}")
loss_function = ReconstructionQuanterLoss(
program=tmp_program, weight_region_names=names)
update_params = [
tmp_program.global_block().var(name + '.alpha')
for name in names
]
with paddle.static.program_guard(tmp_program, startup_program):
student_var = tmp_program.global_block().var(quant_op_out_name)
teacher_var = tmp_program.global_block().var(
"teacher_" + quant_op_out_name)
total_loss, recon_loss, round_loss = loss_function.get_loss(
student_var,
teacher_var, )
train_fetches_loss = {
"total_loss": total_loss,
"recon_loss": recon_loss,
"round_loss": round_loss,
}
optimizer = paddle.optimizer.Adam(
learning_rate=self._lr, parameters=update_params)
optimizer.minimize(total_loss)
self._exe.run(startup_program)
start_time = time.time()
prev_start_time = start_time
for epoch in range(self._epochs):
for i, data in (enumerate(self._data_loader())):
prev_start_time = start_time
start_time = time.time()
out = self._exe.run(
tmp_program,
feed=data,
fetch_list=[
v.name for v in train_fetches_loss.values()
],
return_numpy=True, )
_logger.info(
"Epoch {:d}, Iter {:d}, lr {}, total_loss {:.5f}, recon_loss {:.5f}, round_loss {:.5f}, time {:.5f}s"
.format(epoch, i, self._lr,
np.mean(out[0]),
np.mean(out[1]),
np.mean(out[2]),
start_time - prev_start_time), )
sys.stdout.flush()
if i + 1 == self._num_iterations:
break
if self._weight_quantize_type == 'channel_wise_abs_max':
self._update_scale()
self._update_weights_to_int()
if self._bias_correction:
self._bias_correction_w()
return self._program, self._scale_dict
def _init_alpha(self, name, scale):
_tensor = paddle.static.quantization.utils.load_variable_data(
self._scope, "teacher_" + name)
tensor_scaled = paddle.static.quantization.utils.quant_tensor(
x=_tensor,
scale=scale,
weight_bits=self._weight_bits,
quant_axis=0 if self._weight_op_pairs[name] not in
utils._channelwise_quant_axis1_ops else 1)
tensor_floor = np.floor(tensor_scaled)
tensor = tensor_scaled - tensor_floor
alpha = -np.log((ZETA - GAMMA) / (tensor - GAMMA) - 1)
return alpha
def _soft_rounding(self, weight, scale):
"""
Define network of soft rounding.
Args:
weight: The quanted weight with dtype=float32
"""
bnt = (1 << (self._weight_bits - 1)) - 1
def _quant(x, scale):
s = scale / bnt
quant_x = x / s
return quant_x
def _dequant(x, scale):
s = scale / bnt
dequant_x = s * x
return dequant_x
weight_copy = paddle.static.data(
shape=weight.shape,
dtype=weight.dtype,
name=weight.name + '_copy', )
v = paddle.static.create_parameter(
shape=weight.shape,
dtype=weight.dtype,
name=weight.name + ".alpha",
default_initializer=paddle.nn.initializer.Assign(
self._alpha, ), )
h_v = paddle.clip(
paddle.nn.functional.sigmoid(v) * (ZETA - GAMMA) + GAMMA,
0,
1, )
if self._weight_quantize_type == 'channel_wise_abs_max':
scale_var = paddle.static.create_parameter(
dtype=weight.dtype,
shape=weight.shape,
name=weight.name + '.scale',
default_initializer=paddle.nn.initializer.Assign(
scale, ))
else:
scale_var = scale
quantized_weight = _quant(weight_copy, scale_var)
floor_weight = (paddle.floor(quantized_weight) -
quantized_weight).detach() + quantized_weight
clip_weight = paddle.clip(floor_weight + h_v, -bnt, bnt)
w = _dequant(clip_weight, scale_var)
return w
def _insert_soft_rounding(self):
for name in self._weight_var_names:
weight = self._graph.var(name)
scale = self._scale_dict[name]
shape = weight.shape()
self._alpha = self._init_alpha(name, scale)
if self._weight_quantize_type == 'channel_wise_abs_max':
scale = np.array(scale)
scale = scale.reshape(scale.shape[0], 1)
if len(shape) == 2:
scale = scale.repeat(shape[0], axis=1).T
else:
scale = scale.repeat(shape[1] * shape[2] * shape[3], axis=1)
scale = scale.reshape(shape)
self._insert_func(var=weight, scale=scale, func="_soft_rounding")
def _drop_quant_dequant(self, inputs, scale):
x = paddle.static.data(
shape=inputs.shape,
dtype=inputs.dtype,
name=inputs.name + '.tmp', )
bnt = (1 << (self._weight_bits - 1)) - 1
scale = scale / bnt
dequantized_tensor = paddle.round(x / scale) * scale
quant_noise = x - dequantized_tensor
random_noise = paddle.nn.functional.dropout(
quant_noise, p=self._drop_prob)
return x - random_noise
def _insert_drop_quant_dequant(self):
for op in self._graph.ops():
if op.type() in [
'conv2d', 'depthwise_conv2d', 'mul', 'matmul', 'matmul_v2'
]:
if op.type() in ['conv2d', 'depthwise_conv2d']:
if op.inputs("Filter")[0].name().startswith("teacher"):
break
else:
input = op.inputs("Input")[0]
if op.type() in ['mul', 'matmul', 'matmul_v2']:
if op.inputs("Y")[0].name().startswith("teacher"):
break
else:
input = op.inputs("X")[0]
if input.name() in self._scale_dict.keys():
self._insert_func(
var=input,
scale=self._scale_dict[input.name()],
func="_drop_quant_dequant", )
def _insert_func(self, var, scale, func):
program = var._graph.program
ops = var.outputs()
inputs = var._var
startup_program = paddle.static.Program()
new_program = paddle.static.Program()
new_program._name_generator = program._name_generator
with paddle.static.program_guard(new_program, startup_program):
if func == "_soft_rounding":
out = self._soft_rounding(inputs, scale)
elif func == "_drop_quant_dequant":
out = self._drop_quant_dequant(inputs, scale)
self._exe.run(startup_program)
# create var in program
for new_var in new_program.list_vars():
if new_var.name == var._var.name + '_copy' or new_var.name == var._var.name + '.tmp':
continue
elif new_var.name == var._var.name + '.alpha':
program.global_block().create_parameter(
name=new_var.name,
shape=new_var.shape,
dtype=new_var.dtype,
type=new_var.type,
stop_gradient=False,
trainable=True)
elif new_var.name == var._var.name + '.scale':
program.global_block().create_parameter(
name=new_var.name,
shape=new_var.shape,
dtype=new_var.dtype,
type=new_var.type,
stop_gradient=True,
trainable=False)
else:
if func == "_soft_rounding":
program.global_block().create_var(
name=new_var.name + '.rounding',
shape=new_var.shape,
dtype=new_var.dtype,
type=new_var.type,
persistable=new_var.persistable,
stop_gradient=new_var.stop_gradient, )
else:
program.global_block().create_var(
name=new_var.name + '.qdrop',
shape=new_var.shape,
dtype=new_var.dtype,
type=new_var.type,
persistable=new_var.persistable,
stop_gradient=new_var.stop_gradient, )
op_list = new_program.global_block().ops
op_list = list(reversed(op_list))
block = var._var.block
# prepend new_program's op in program
for _op in ops:
if _op.type() not in [
'conv2d', 'depthwise_conv2d', 'mul', 'matmul', 'matmul_v2'
]:
continue
idx = block.ops.index(_op._op)
for op in op_list:
_type = op.type
_attrs = {
'use_mkldnn': False,
'with_quant_attr': False,
}
if _type == 'clip':
_attrs = {
'use_mkldnn': False,
'with_quant_attr': False,
'max': op.attr('max'),
'min': op.attr('min'),
}
elif _type == 'scale':
_attrs = {
'use_mkldnn': False,
'with_quant_attr': False,
'scale': op.attr('scale'),
'bias_after_scale': op.attr('bias_after_scale'),
}
elif _type in ['elementwise_mul', 'elementwise_div']:
_attrs = {
'use_mkldnn': False,
'with_quant_attr': False,
'Scale_out': op.attr('Scale_out'),
'Scale_x': op.attr('Scale_x'),
'Scale_y': op.attr('Scale_y'),
'axis': op.attr('axis'),
}
if func == "_soft_rounding":
_outputs = {'Out': op.output('Out')[0] + '.rounding'}
if _type in [
"elementwise_add", "elementwise_sub",
"elementwise_mul"
]:
_inputs = {
'X': op.input('X')[0] + '.rounding',
'Y': op.input('Y')[0] + '.rounding',
}
elif _type == "elementwise_div":
_inputs = {
'X': var._var,
'Y': op.input('Y')[0] + '.rounding',
}
elif (_type == 'scale' and
op.input('X')[0].endswith('scale')
) or _type == 'sigmoid':
_inputs = {'X': op.input('X')[0]}
elif (_type == 'scale' and
op.input('X')[0].endswith('copy')):
_inputs = {'X': var._var}
else:
_inputs = {'X': op.input('X')[0] + '.rounding'}
elif func == "_drop_quant_dequant":
if _type == 'dropout':
_outputs = {
'Out': op.output('Out')[0] + '.qdrop',
'Mask': op.output('Mask')[0] + '.qdrop',
}
else:
_outputs = {'Out': op.output('Out')[0] + '.qdrop'}
if _type == 'elementwise_add' or _type == 'elementwise_sub':
_inputs = {
'X': var._var,
'Y': op.input('Y')[0] + '.qdrop',
}
elif _type == 'scale' and op.input(
'X')[0] == inputs.name + '.tmp':
_inputs = {'X': var._var}
else:
_inputs = {'X': op.input('X')[0] + '.qdrop'}
block._insert_op(
idx,
type=_type,
attrs=_attrs,
inputs=_inputs,
outputs=_outputs, )
for op in ops:
if op.type() not in [
'conv2d', 'depthwise_conv2d', 'mul', 'matmul', 'matmul_v2'
]:
continue
if op.type() in [
'conv2d', 'depthwise_conv2d'
] and op.inputs('Filter')[0].name().startswith('teacher'):
continue
if op.type() in [
'mul', 'matmul', 'matmul_v2'
] and op.inputs('Y')[0].name().startswith('teacher'):
continue
if func == '_soft_rounding':
op._op._rename_input(inputs.name, out.name + '.rounding')
else:
op._op._rename_input(inputs.name, out.name + '.qdrop')
def _isolate_regions(self):
starts = [region[0] for region in self._regions]
var2duplications = self._duplicate_vars(starts)
for vars_ in var2duplications.values():
for var_ in vars_:
var_.stop_gradients = True
def _duplicate_vars(self, var_names):
result = {}
for var_name in var_names:
var = self._graph.var(var_name)
result[var_name] = self._duplicate_var(var)
return result
def _duplicate_var(self, var):
vars = []
block = var._var.block
index = 0
for op in var.outputs():
var_ = var._var
op_ = op._op
duplicated_var = block.create_var(
name=var_.name + ".assign" + str(index),
type=var_.type,
shape=var_.shape,
dtype=var_.dtype, )
vars.append(duplicated_var)
index += 1
idx = block.ops.index(op_)
block._insert_op(
idx,
type="assign",
inputs={"X": var_},
outputs={"Out": duplicated_var}, )
op_._rename_input(var_.name, duplicated_var.name)
return vars
def _update_scale(self):
for _name in self._weight_var_names:
if self._skip_tensor_list is not None and _name in self._skip_tensor_list:
continue
scale_name = _name + '.scale'
scale_tensor = utils.load_variable_data(self._scope, scale_name)
scale_list = []
if self._weight_op_pairs[
_name] in utils._channelwise_quant_axis1_ops:
scale_list = list(scale_tensor[0])
else:
for i in range(scale_tensor.shape[0]):
scale_list.append(scale_tensor[i][0][0][0])
self._scale_dict[scale_name] = scale_list
def _update_weights_to_int(self):
for weight_var_name in self._weight_var_names:
if self._skip_tensor_list is not None and weight_var_name in self._skip_tensor_list:
continue
alpha_tensor = utils.load_variable_data(
self._scope,
weight_var_name + '.alpha', )
h_alpha_tensor = self._compute_soft_rounding_np(alpha_tensor)
weight_tensor = utils.load_variable_data(
self._scope,
weight_var_name, )
weight_quant_tensor = utils.quant_tensor(
x=weight_tensor,
scale=self._scale_dict[weight_var_name],
weight_bits=self._weight_bits,
quant_axis=0 if self._weight_op_pairs[weight_var_name] not in
utils._channelwise_quant_axis1_ops else 1)
utils.set_variable_data(
self._scope,
self._place,
weight_var_name,
np.floor(weight_quant_tensor) + h_alpha_tensor, )
def _bias_correction_w(self):
for weight_var_name in self._weight_var_names:
weight_var_tensor = utils.load_variable_data(
self._scope,
"teacher_" + weight_var_name, )
weight_quant_tensor = utils.load_variable_data(
self._scope,
weight_var_name, )
scale = self._scale_dict[weight_var_name]
final_weight_tensor = utils.bias_correction_w(
weight_var_tensor,
weight_quant_tensor,
scale,
quant_axis=0 if self._weight_op_pairs[weight_var_name] not in
utils._channelwise_quant_axis1_ops else 1,
weight_bits=self._weight_bits, )
utils.set_variable_data(
self._scope,
self._place,
weight_var_name,
final_weight_tensor, )
def _compute_soft_rounding_np(self, alpha_v):
return np.clip(
utils.stable_sigmoid(alpha_v) * (ZETA - GAMMA) + GAMMA,
a_min=0,
a_max=1, )
def _all_persistable_var_names(self):
persistable_var_names = []
for var in self._program.list_vars():
if var.persistable:
persistable_var_names.append(var.name)
return persistable_var_names
class ReconstructionQuanterLoss(object):
def __init__(self,
program,
weight_region_names=None,
round_loss_type='relaxation',
rec_loss_type='mse',
beta_type='const',
weight=0.1):
"""
The loss function of Rounding Optimizer.
Args:
program(Program): The student program.
weight_region_names(list, optional): The weight names inside a region.
round_loss_type(str): The type of rounding loss function.
rec_loss_type(str): The type of reconstruction loss function.
beta_type(str): The type of hyper-parameter beta.
Returns:
total_loss(Variable): The sum of rounding loss and reconstruction loss.
rec_loss(Variable): The reconstruction loss.
round_loss(Variable): The rounding loss.
"""
self.program = program
self.round_loss_type = round_loss_type
self.weight = weight
self.rec_loss_type = rec_loss_type
self.weight_region_names = weight_region_names
self.beta_type = beta_type
def compute_soft_rounding(self, alpha_v):
return paddle.clip(
paddle.nn.functional.sigmoid(alpha_v) * (ZETA - GAMMA) + GAMMA, 0,
1)
def get_loss(self, student_tensor, teacher_tensor, scheduler=None):
if self.rec_loss_type == 'mse':
rec_loss = paddle.nn.functional.mse_loss(
student_tensor,
teacher_tensor, )
else:
raise ValueError(
'Not supported reconstruction loss function: {}'.format(
self.rec_loss, ), )
if self.beta_type == 'const':
self.beta = 3
else:
self.beta = scheduler.get_lr()
if self.round_loss_type == 'relaxation':
round_loss = 0.0
for name in self.weight_region_names:
alpha_v = self.program.global_block().var(name + '.alpha')
h_v = self.compute_soft_rounding(alpha_v)
round_loss += self.weight * \
paddle.sum(-paddle.pow(paddle.abs(2 * h_v-1), self.beta) + 1)
else:
raise NotImplementedError
total_loss = rec_loss + round_loss
return total_loss, rec_loss, round_loss
class PriorityQueue:
def __init__(self):
self._data = []
self._ops = set()
self._idx = 0
self._lazy_tag = True
def pop(self):
if not self._lazy_tag:
self._data = sorted(self._data, key=lambda x: x[0])
self._lazy_tag = True
if self._idx >= len(self._data): raise IndexError('Index out of range!')
ele = self._data[self._idx]
self._idx += 1
return ele
def push(self, depth, op):
if op in self._ops: return
self._data.append((depth, op))
self._ops.add(op)
self._lazy_tag = False
def empty(self):
return self._idx >= len(self._data)
class RegionBuilder(object):
def __init__(self, program):
self._program = program
self._graph = GraphWrapper(self._program)
self._op_idx_map = {}
for op in self._graph.ops():
self._op_idx_map[op.idx()] = op
self._depth = {}
self._init_depth()
self._cache = {}
self._regions = []
self._region_weights_names = []
def _init_depth(self):
for op in self._graph.ops():
if len(self._graph.pre_ops(op)) == 0:
self._depth[op.idx()] = 0
continue
depths_cache = []
for up_op in self._graph.pre_ops(op):
assert up_op.idx() in self._depth
depths_cache.append(self._depth[up_op.idx()])
self._depth[op.idx()] = max(depths_cache) + 1
def _build(self, op, limit):
def _find_multi_input_ep(op):
least_first_queue = PriorityQueue()
for down_op in self._graph.next_ops(op):
least_first_queue.push(self._depth[down_op.idx()],
down_op.idx())
while not least_first_queue.empty():
iter_op_idx = least_first_queue.pop()[-1]
iter_op = self._op_idx_map[iter_op_idx]
if (least_first_queue.empty() and
len(self._graph.pre_ops(iter_op)) > 1):
return iter_op
for down_op in self._graph.next_ops(iter_op):
least_first_queue.push(self._depth[down_op.idx()],
down_op.idx())
return None
def _find_coherent_ep(op):
ops = self._graph.next_ops(op)
if len(ops) == 1:
following_op = ops[0]
if following_op.type() == 'fetch':
return None
inps = op.all_inputs()
non_parameter_input = 0
for var in inps:
if not var._var.persistable:
non_parameter_input += 1
upstream_ops = len(self._graph.pre_ops(following_op))
if non_parameter_input == 1 and upstream_ops == 1:
return ops[0]
return None
sp, ep, future_ep = op, op, op
while future_ep is not None:
if len(self._graph.next_ops(ep)) <= 1:
future_ep = _find_coherent_ep(ep)
else:
future_ep = _find_multi_input_ep(ep)
if future_ep is None or self._depth[future_ep.idx(
)] - self._depth[sp.idx()] >= limit:
return self._create_region(sp, ep)
ep = future_ep
return self._create_region(sp=sp, ep=ep)
def _opset_matching(self, sp, ep):
if sp.idx() in self._cache: return self._cache[sp.idx()]
ret_collection = set()
following_ops = self._graph.next_ops(sp)
if (len(following_ops)) == 0:
return ret_collection.add(sp.idx())
for op in following_ops:
if op == ep:
ret_collection.update([sp.idx(), op.idx()])
else:
further_res = self._opset_matching(sp=op, ep=ep)
if further_res is None: