forked from intel/neural-compressor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tensorflow.py
1727 lines (1534 loc) · 81.8 KB
/
tensorflow.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 os
import copy
import yaml
import math
import numpy as np
from collections import OrderedDict, UserDict
from .query import QueryBackendCapability
from .adaptor import adaptor_registry, Adaptor
from ..utils.utility import LazyImport, CpuInfo, singleton, Dequantize, dump_elapsed_time
from ..utils.utility import Statistics, GLOBAL_STATE, MODE, version1_lt_version2
from ..utils import logger
from ..conf.dotdict import deep_get
from ..experimental.data.dataloaders.base_dataloader import BaseDataLoader
tensorflow = LazyImport('tensorflow')
@adaptor_registry
class TensorFlowAdaptor(Adaptor):
unify_op_type_mapping = {
"Conv2D": "conv2d",
"Conv3D": "conv3d",
"DepthwiseConv2dNative": "conv2d",
"FusedBatchNormV3": "batchnorm",
"MaxPool": "pooling",
"MaxPool3D": "pooling",
"AvgPool": "pooling",
"ConcatV2": "concat",
"MatMul": "matmul",
"BatchMatMulV2": "matmul",
"Pad": "pad"
}
def __init__(self, framework_specific_info):
super().__init__(framework_specific_info)
self.quantize_config = {'op_wise_config': {}}
self.framework_specific_info = framework_specific_info
self.approach = deep_get(self.framework_specific_info, 'approach', False)
self.device = self.framework_specific_info['device']
self.work_dir = os.path.abspath(self.framework_specific_info['workspace_path'])
self.recipes = deep_get(self.framework_specific_info, 'recipes', {})
os.makedirs(self.work_dir, exist_ok=True)
self.pre_optimized_model = None
self.pre_optimizer_handle = None
self.bf16_ops = []
self.fp32_ops = []
self.dump_times = 0 # for tensorboard
cfg_yaml_name = "{}.yaml".format(self.__class__.__name__[:-len('Adaptor')].lower())
self.query_handler = TensorflowQuery(local_config_file=os.path.join(
os.path.dirname(__file__), cfg_yaml_name))
self.itex_mode = cfg_yaml_name == 'tensorflow_itex.yaml'
self.qdq_enabled = cfg_yaml_name == 'inteltensorflow.yaml' or \
cfg_yaml_name == 'tensorflow_itex.yaml'
self.op_wise_sequences = self.query_handler.get_eightbit_patterns(self.qdq_enabled)
self.optimization = self.query_handler.get_grappler_optimization_cfg()
self.fp32_results = []
self.fp32_preds_as_label = False
self.benchmark = (GLOBAL_STATE.STATE == MODE.BENCHMARK)
self.callbacks = []
self.new_api = False
def log_histogram(self, writer, tag, values, step=0, bins=1000):
import tensorflow as tf
# Convert to a numpy array
values = np.array(values)
# Create histogram using numpy
counts, bin_edges = np.histogram(values, bins=bins)
# Fill fields of histogram proto
hist = tf.compat.v1.HistogramProto()
hist.min = float(np.min(values))
hist.max = float(np.max(values))
hist.num = int(np.prod(values.shape))
hist.sum = float(np.sum(values))
hist.sum_squares = float(np.sum(values**2))
bin_edges = bin_edges[1:]
for edge in bin_edges:
hist.bucket_limit.append(edge)
for c in counts:
hist.bucket.append(c)
# Create and write Summary
summary = tf.compat.v1.Summary(value=[tf.compat.v1.Summary.Value(tag=tag, histo=hist)])
writer.add_summary(summary, step)
writer.flush()
def _pre_hook_for_hvd(self):
import horovod.tensorflow as hvd
self.hvd = hvd
self.hvd.init()
@dump_elapsed_time(customized_msg="Model training")
def train(self, model, dataloader, optimizer_tuple,
criterion_tuple, hooks, postprocess, **kwargs):
# check model is savedmodel or not
import tensorflow as tf
from neural_compressor.model.model import get_model_type
tf.random.set_seed(1)
self.model_type = get_model_type(model._model)
optimizer = optimizer_tuple[0](**optimizer_tuple[1])
criterion = criterion_tuple[0](**criterion_tuple[1])
start_epochs = kwargs['kwargs'].get('start_epoch', None)
end_epochs = kwargs['kwargs'].get('end_epoch', None)
epochs = kwargs['kwargs'].get('epoch', None)
iters = kwargs['kwargs'].get('iteration', None)
callbacks = kwargs['kwargs'].get('callbacks', None)
execution_mode = kwargs['kwargs'].get('execution_mode', None)
distributed = getattr(dataloader, 'distributed', False)
from neural_compressor.experimental.common.criterion import TensorflowKnowledgeDistillationLoss
if isinstance(criterion, TensorflowKnowledgeDistillationLoss):
input_model = model._model
else:
input_model = tf.keras.models.load_model(model._model)
hooks = callbacks['tf_pruning'](model, input_model, hooks)
hooks['on_train_begin']() # on_train_begin hook
train_loss_results = []
if distributed:
try:
len_dataloader = len(dataloader)
except:
logger.info("The length of the distributed training dataloader is unknown."
"When the iteration of training dataloader in each process is "
"inconsistent, an error may occur.")
else:
list_len_dataloader = self.hvd.allgather_object(len_dataloader)
if self.hvd.rank() == 0:
for i in range(len(list_len_dataloader)-1):
if list_len_dataloader[i] != list_len_dataloader[i+1]:
raise AttributeError("The traning dataloader's iteration is"
"different between processes, please reset dataloader's batch_size.")
def training_step(x, y, first_batch):
with tf.GradientTape() as tape:
tape.watch(input_model.trainable_variables)
y_ = input_model(x, training=True)
loss_value = criterion(y, y_)
loss_value = hooks['on_after_compute_loss'](x, y_, loss_value)
tape = self.hvd.DistributedGradientTape(tape) if distributed else tape
# Get gradient
grads = tape.gradient(loss_value, input_model.trainable_variables) # pylint: disable=no-member
# Optimize the model
optimizer.apply_gradients(zip(grads, input_model.trainable_variables)) # pylint: disable=no-member
if distributed and first_batch:
self.hvd.broadcast_variables(input_model.variables, root_rank=0)
self.hvd.broadcast_variables(optimizer.variables(), root_rank=0)
return loss_value
training_step = training_step if execution_mode=='eager' else tf.function(training_step)
if start_epochs is not None and end_epochs is not None:
epochs = end_epochs - start_epochs
for epoch in range(epochs):
cnt = 0
epoch_loss_avg = tf.keras.metrics.Mean()
hooks['on_epoch_begin'](epoch) # on_epoch_begin hook
# Training loop
for iter, data in enumerate(dataloader):
x, y = postprocess(data) if postprocess is not None else data
hooks['on_step_begin'](iter) # on_step_begin hook
cnt += 1
loss_value = training_step(x, y, iter==0)
# Track progress
epoch_loss_avg.update_state(loss_value) # Add current batch loss
hooks['on_step_end']() # on_step_end hook
if iters is not None and cnt >= iters:
break
model._sess = None
hooks['on_epoch_end']() # on_epoch_end hook
# End epoch
train_loss_results.append(epoch_loss_avg.result())
if distributed:
logger.info("Epoch-{:03d} training on rank {!s} have been done." \
.format(epoch+1, self.hvd.allgather_object(self.hvd.rank())))
logger.info("Epoch {:03d}: Loss: {:.3f}".format(epoch+1, epoch_loss_avg.result()))
hooks['on_train_end']() # on_train_end hook
model._sess = None
if not isinstance(criterion, TensorflowKnowledgeDistillationLoss):
if distributed:
if self.hvd.rank() == 0:
# Update the input model with pruned weights manually due to keras API limitation.
input_model.save(model._model)
rank_list = self.hvd.allgather_object(self.hvd.rank())
logger.info(f"rank 0 has saved the pruned model to '{model._model}',"
f"all ranks {rank_list} ready.")
else:
input_model.save(model._model)
else:
input_model.save('distillation_model')
@dump_elapsed_time(customized_msg="Model inference")
def evaluate(self, model, dataloader, postprocess=None,
metrics=None, measurer=None, iteration=-1,
tensorboard=False, fp32_baseline=False):
"""Evaluate the model for specified metric on validation dataset.
Args:
model ([Graph, GraphDef or Path String]): The model could be the graph,
graph_def object, the frozen pb or ckpt/savedmodel folder path.
dataloader (generator): generate the data and labels.
postprocess (object, optional): process the result from the model
metrics (list, optional): Depends on model category. Defaults to None.
measurer (object, optional): for precise benchmark measurement.
iteration(int, optional): control steps of mini-batch
tensorboard (boolean, optional): for tensorboard inspect tensor.
fp32_baseline (boolen, optional): only for compare_label=False pipeline
Returns:
[float]: evaluation result, the larger is better.
"""
import tensorflow as tf
from .tf_utils.util import iterator_sess_run
outputs = model.output_tensor_names
if getattr(dataloader, 'distributed', False):
import horovod.tensorflow as hvd
hvd.init()
# If metric.hvd is not None then run distributed inference
for metric in metrics:
metric.hvd = hvd
try:
len_dataloader = len(dataloader)
except:
logger.info("The length of the distributed evaluation dataloader is unknown."
"When the iteration of evaluation dataloader in each process is "
"inconsistent, an error may occur.")
else:
list_len_dataloader = hvd.allgather_object(len_dataloader)
if hvd.rank() == 0:
for i in range(len(list_len_dataloader)-1):
if list_len_dataloader[i] != list_len_dataloader[i+1]:
raise AttributeError("The evaluation dataloader's iteration is"
"different between processes, please reset dataloader's batch_size.")
logger.info("Rank {!s} dataloaders' data distribution balance check for evaluation have been finnished." \
.format(hvd.allgather_object(hvd.rank())))
if tensorboard:
from .tf_utils.graph_util import GraphAnalyzer
from tensorflow.python.framework import tensor_util
output_postfix = "_fp32.output"
inspect_node_types = ["Conv2D", "DepthwiseConv2dNative", "MaxPool", "AvgPool",
"ConcatV2", "MatMul", "FusedBatchNormV3", "FusedBatchNorm", "BiasAdd",
"Relu", "Relu6", "Dequantize"]
fp32_inspect_node_name = []
int8_inspect_node_name = []
q_node_scale = {}
if self.dump_times == 0:
temp_dir = "./runs/eval/baseline"
else:
temp_dir = "./runs/eval/tune_" + str(self.dump_times)
if os.path.isdir(temp_dir):
import shutil
shutil.rmtree(temp_dir, ignore_errors=True)
writer = tf.compat.v1.summary.FileWriter(temp_dir, model.graph)
cur_graph = GraphAnalyzer()
cur_graph.graph = model.graph_def
cur_graph.parse_graph()
graph_info = cur_graph.node_name_details
for node in model.graph_def.node:
if node.op in inspect_node_types:
fp32_inspect_node_name.append(node.name)
# Tensor dump supported quantized op including,
# Requantize, QuantizedConv2DAndRequantize,
# QuantizedConv2DAndReluAndRequantize,
# QuantizedConv2DWithBiasAndRequantize,
# QuantizedConv2DWithBiasAndReluAndRequantize,
# QuantizedConv2DWithBiasSignedSumAndReluAndRequantize,
# QuantizedConv2DWithBiasSumAndReluAndRequantize,
# QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize,
# QuantizedMatMulWithBiasAndReluAndRequantize,
# QuantizedMatMulWithBiasAndRequantize
elif node.op.find("Requantize") != -1:
out_min = -2
out_max = -1
if node.op.find("Sum") != -1:
out_min = -5
out_max = -4
q_out_min = graph_info[node.input[out_min]
].node.attr["value"].tensor.float_val[0]
q_out_max = graph_info[node.input[out_max]
].node.attr["value"].tensor.float_val[0]
q_node_scale[node.name] = (node.op, q_out_min, q_out_max)
int8_inspect_node_name.append(node.name)
# Inspect weights, bias. Need further optimize
if node.op == "Const" and graph_info[graph_info[node.name].outputs[0]].node.op \
in ["Conv2D", "DepthwiseConv2dNative", "MatMul",
"FusedBatchNormV3", "BiasAdd"]:
const_value = tensor_util.MakeNdarray(node.attr.get(
'value').tensor).astype(np.float32)
self.log_histogram(writer, node.name, const_value)
outputs.extend(fp32_inspect_node_name)
if len(int8_inspect_node_name) > 0:
output_postfix = "_int8.output"
outputs.extend(int8_inspect_node_name)
if metrics:
for metric in metrics:
metric.reset()
self.fp32_preds_as_label = any([hasattr(metric, "compare_label") and \
not metric.compare_label for metric in metrics])
origin_output_tensor_names = model.output_tensor_names
model.output_tensor_names = outputs
input_tensor = model.input_tensor
output_tensor = model.output_tensor if len(model.output_tensor)>1 else \
model.output_tensor[0]
logger.info("Start to evaluate the TensorFlow model.")
def eval_func(dataloader):
results = []
for idx, (inputs, labels) in enumerate(dataloader):
# dataloader should keep the order and len of inputs same with input_tensor
if len(input_tensor) == 1:
feed_dict = {}
if isinstance(inputs, dict) or isinstance(inputs, OrderedDict) \
or isinstance(inputs, UserDict):
for name in inputs:
for tensor in input_tensor:
pos = tensor.name.rfind(":")
t_name = tensor.name if pos < 0 else tensor.name[:pos]
if name == t_name:
feed_dict[tensor] = inputs[name]
break
else:
feed_dict = {input_tensor[0]: inputs} # get raw tensor using index [0]
else:
assert len(input_tensor) == len(inputs), \
'inputs len must equal with input_tensor'
feed_dict = {}
if isinstance(inputs, dict) or isinstance(inputs, OrderedDict) \
or isinstance(inputs, UserDict):
for name in inputs:
for tensor in input_tensor:
pos = tensor.name.rfind(":")
t_name = tensor.name if pos < 0 else tensor.name[:pos]
if name == t_name:
feed_dict[tensor] = inputs[name]
break
else:
feed_dict = dict(zip(input_tensor, inputs))
if model.iter_op:
predictions = iterator_sess_run(model.sess, model.iter_op, \
feed_dict, output_tensor, iteration, measurer)
elif measurer is not None:
measurer.start()
predictions = model.sess.run(output_tensor, feed_dict)
measurer.end()
else:
predictions = model.sess.run(output_tensor, feed_dict)
if self.fp32_preds_as_label:
self.fp32_results.append(predictions) if fp32_baseline else \
results.append(predictions)
# Inspect node output, just get 1st iteration output tensors for now
if idx == 0 and tensorboard:
for index, node_name in enumerate(outputs):
tensor = predictions[index]
if node_name in int8_inspect_node_name:
tensor = Dequantize(predictions[index], q_node_scale[node_name])
self.log_histogram(writer, node_name + output_postfix, tensor.astype(
np.float32), idx)
writer.close()
if isinstance(predictions, list):
if len(origin_output_tensor_names) == 1:
predictions = predictions[0]
elif len(origin_output_tensor_names) > 1:
predictions = predictions[:len(origin_output_tensor_names)]
if postprocess is not None:
predictions, labels = postprocess((predictions, labels))
if metrics:
for metric in metrics:
if not hasattr(metric, "compare_label") or \
(hasattr(metric, "compare_label") and metric.compare_label):
metric.update(predictions, labels)
if idx + 1 == iteration:
break
return results
if isinstance(dataloader, BaseDataLoader) and not self.benchmark:
try:
results = eval_func(dataloader)
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 = eval_func(dataloader)
else: # pragma: no cover
results = eval_func(dataloader)
if self.fp32_preds_as_label:
from .tf_utils.util import collate_tf_preds
if fp32_baseline:
results = collate_tf_preds(self.fp32_results)
reference = results
else:
reference = collate_tf_preds(self.fp32_results)
results = collate_tf_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]
if tensorboard:
new_dir = temp_dir + "_acc_" + str(acc)
writer.close()
if os.path.isdir(new_dir):
import shutil
shutil.rmtree(new_dir, ignore_errors=True)
os.rename(temp_dir, new_dir)
self.dump_times += 1
model.output_tensor_names = origin_output_tensor_names
return acc if not isinstance(acc, list) or len(acc) > 1 else acc[0]
def tuning_cfg_to_fw(self, tuning_cfg):
"""Parse the neural_compressor wrapped configuration to Tensorflow.
Args:
tuning_cfg (dict): configuration for quantization.
"""
self.quantize_config['calib_iteration'] = tuning_cfg['calib_iteration']
self.quantize_config['device'] = self.device
self.quantize_config['advance'] = deep_get(tuning_cfg, 'advance')
fp32_ops = []
bf16_ops = []
int8_ops = []
dispatched_op_names = [j[0] for j in tuning_cfg['op']]
invalid_op_names = [i for i in self.quantize_config['op_wise_config']
if i not in dispatched_op_names]
for op_name in invalid_op_names:
self.quantize_config['op_wise_config'].pop(op_name)
for each_op_info in tuning_cfg['op']:
op_name = each_op_info[0]
if tuning_cfg['op'][each_op_info]['activation']['dtype'] in ['fp32', 'bf16']:
if op_name in self.quantize_config['op_wise_config']:
self.quantize_config['op_wise_config'].pop(op_name)
if tuning_cfg['op'][each_op_info]['activation']['dtype'] == 'fp32':
fp32_ops.append(op_name)
if tuning_cfg['op'][each_op_info]['activation']['dtype'] == 'bf16':
bf16_ops.append(op_name)
continue
is_perchannel = False
bit = None
if 'weight' in tuning_cfg['op'][each_op_info]:
is_perchannel = tuning_cfg['op'][each_op_info]['weight'][
'granularity'] == 'per_channel'
bit = tuning_cfg['op'][each_op_info]['weight']['bit']
weight_bit = bit if bit else 7.0
algorithm = tuning_cfg['op'][each_op_info]['activation']['algorithm']
is_asymmetric = False
if 'activation' in tuning_cfg['op'][each_op_info]:
is_asymmetric = tuning_cfg['op'][each_op_info]['activation']['scheme'] == 'asym'
int8_ops.append(op_name)
self.quantize_config['op_wise_config'][op_name] = (is_perchannel,
algorithm,
is_asymmetric,
weight_bit)
self.fp32_ops = fp32_ops
self.bf16_ops = bf16_ops
@dump_elapsed_time("Pass quantize model")
def quantize(self, tune_cfg, model, data_loader, q_func=None):
"""Execute the quantize process on the specified model.
Args:
tune_cfg (dict): quantization configuration
model (tf.compat.v1.GraphDef): fp32 model
data_loader (generator): generator the data and labels
q_func (optional): training function for quantization aware training mode,
which not enabled for tensorflow yet.
Returns:
tf.compat.v1.GraphDef: the quantized model
"""
if self.approach == "quant_aware_training":
assert q_func is not None, "quantization aware training mode \
is not configured correctly"
from neural_compressor.experimental import common
qat_model = q_func(model)
return self.convert(common.Model(qat_model), 'QAT', 'default')
assert q_func is None, "quantization aware training mode is not support on tensorflow"
self.tuning_cfg_to_fw(tune_cfg)
logger.debug("Dump quantization configurations:")
logger.debug(self.quantize_config)
from .tf_utils.graph_converter import GraphConverter
calib_sampling_size = tune_cfg.get('calib_sampling_size', 1)
if isinstance(data_loader, BaseDataLoader):
batch_size = data_loader.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: # pragma: no cover
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))
data_loader.batch(calib_batch_size)
self.quantize_config['calib_iteration'] = tmp_iterations
converted_model = GraphConverter(model,
qt_config=self.quantize_config,
recipes=self.recipes,
int8_sequences=self.op_wise_sequences,
fp32_ops=self.fp32_ops,
bf16_ops=self.bf16_ops,
data_loader=data_loader,
qdq_enabled=self.qdq_enabled,
new_api=self.new_api).convert()
except Exception: # pragma: no cover
from .tf_utils.util import get_model_input_shape
batch_size = get_model_input_shape(model)
logger.warning(
"Fail to forward with batch size={}, set to {} now.".
format(batch_size, batch_size))
data_loader.batch(batch_size)
self.quantize_config['calib_iteration'] = calib_sampling_size
converted_model = GraphConverter(model,
qt_config=self.quantize_config,
recipes=self.recipes,
int8_sequences=self.op_wise_sequences,
fp32_ops=self.fp32_ops,
bf16_ops=self.bf16_ops,
data_loader=data_loader,
qdq_enabled=self.qdq_enabled,
new_api=self.new_api).convert()
else: # pragma: no cover
if hasattr(data_loader, 'batch_size') and \
calib_sampling_size % data_loader.batch_size != 0:
iter = self.quantize_config['calib_iteration']
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, data_loader.batch_size,
data_loader.batch_size * iter))
converted_model = GraphConverter(model,
qt_config=self.quantize_config,
recipes=self.recipes,
int8_sequences=self.op_wise_sequences,
fp32_ops=self.fp32_ops,
bf16_ops=self.bf16_ops,
data_loader=data_loader,
qdq_enabled=self.qdq_enabled,
new_api=self.new_api).convert()
#just save framework_specific_info feature for recover
converted_model.q_config.update({'framework_specific_info': \
self.framework_specific_info})
self._dump_model_op_stats(converted_model.graph_def)
return converted_model
def _dump_model_op_stats(self, model_graphdef):
fp32_op_list_uint8 = copy.deepcopy(
self.query_handler.get_op_types_by_precision(precision='uint8'))
fp32_op_list_int8 = copy.deepcopy(
self.query_handler.get_op_types_by_precision(precision='int8'))
fp32_op_list=list(set(fp32_op_list_uint8).union(set(fp32_op_list_int8)))
int8_op_prefix_list = ['QuantizedConv2D', '_QuantizedConv3D', 'QuantizedDepthwise',
'QuantizedMaxPool', 'QuantizedAvgPool',
'QuantizedConcatV2', 'QuantizedMatMul',
'_QuantizedFusedBatchNorm']
from tensorflow.python.framework import dtypes
res = {}
for op_type in fp32_op_list:
res[op_type] = {'INT8': 0, 'BF16': 0, 'FP32': 0}
res['QuantizeV2'] = {'INT8': 0, 'BF16': 0, 'FP32': 0}
res['Dequantize'] = {'INT8': 0, 'BF16': 0, 'FP32': 0}
res['Cast'] = {'INT8': 0, 'BF16': 0, 'FP32': 0}
fp32_op_list.extend(['QuantizeV2', 'Dequantize', 'Cast'])
for i in model_graphdef.node:
if i.op == 'Const':
continue
possible_int8_res = [name for name in int8_op_prefix_list if i.op.find(name) != -1]
if any(possible_int8_res):
origin_op_type = possible_int8_res[0].split('Quantized')[-1]
if origin_op_type == 'FusedBatchNorm':
origin_op_type = 'FusedBatchNormV3'
if origin_op_type == 'Depthwise':
origin_op_type = 'DepthwiseConv2dNative'
res[origin_op_type]['INT8'] += 1
if i.op in fp32_op_list:
if 'T' not in i.attr and i.op != 'Cast':
continue
if i.attr['T'].type == dtypes.bfloat16:
res[i.op]['BF16'] += 1
elif i.attr['T'].type in (dtypes.quint8,dtypes.qint8):
res[i.op]['INT8'] += 1
elif i.op == 'Cast':
if i.attr['DstT'].type == dtypes.bfloat16:
res[i.op]['BF16'] += 1
elif i.attr['DstT'].type == dtypes.float32:
res[i.op]['FP32'] += 1
else:
res[i.op]['FP32'] += 1
output_data = [[op_type, sum(res[op_type].values()), res[op_type]['INT8'],
res[op_type]['BF16'], res[op_type]['FP32']] for op_type in fp32_op_list]
Statistics(output_data,
header='Mixed Precision Statistics',
field_names=["Op Type", "Total", "INT8", "BF16", "FP32"]).print_stat()
def _query_bf16_ops(self, matched_nodes):
self.bf16_op_details = OrderedDict()
valid_precision = self.query_handler.get_mixed_precision_combination()
if ('bf16' in valid_precision and CpuInfo().bf16) or os.getenv('FORCE_BF16') == '1':
for details in matched_nodes:
node_op = details[-1][0]
node_name = details[0]
self.bf16_op_details[(node_name, node_op)] = {'weight': {'dtype': ['bf16']}, \
'activation': {'dtype': ['bf16']}}
def _query_quantizable_ops(self, matched_nodes):
"""Collect the op-wise configuration for quantization.
Returns:
OrderDict: op-wise configuration.
"""
uint8_type = self.query_handler.get_op_types_by_precision(precision='uint8')
int8_type = self.query_handler.get_op_types_by_precision(precision='int8')
tf_quantizable_op_type = list(set(uint8_type).union(set(int8_type)))
valid_precision = self.query_handler.get_mixed_precision_combination()
op_capability = self.query_handler.get_quantization_capability()
conv_config = copy.deepcopy(op_capability['uint8']['Conv2D'])
conv3d_config = copy.deepcopy(op_capability['uint8']['Conv3D']) if 'Conv3D' in op_capability['uint8'] else None
matmul_config = copy.deepcopy(op_capability['uint8']['MatMul'])
other_config = copy.deepcopy(op_capability['uint8']['default'])
if ('bf16' in valid_precision and CpuInfo().bf16) or os.getenv('FORCE_BF16') == '1':
#TODO we need to enhance below logic by introducing precision priority.
conv_config['weight']['dtype'].insert(-1, 'bf16')
matmul_config['weight']['dtype'].insert(-1, 'bf16')
conv_config['activation']['dtype'].insert(-1, 'bf16')
matmul_config['activation']['dtype'].insert(-1, 'bf16')
other_config['activation']['dtype'].insert(-1, 'bf16')
self.quantizable_op_details = OrderedDict()
self._init_op_stat = {i: [] for i in tf_quantizable_op_type}
exclude_first_quantizable_op = True if 'first_conv_or_matmul_quantization' in \
self.recipes and not self.recipes['first_conv_or_matmul_quantization'] \
else False
for details in matched_nodes:
node_op = details[-1][0]
node_name = details[0]
patterns = details[-1]
pat_length = len(patterns)
pattern_info = {
'sequence': [[','.join(patterns[:pat_length - i]) for i in range(pat_length)][0]],
'precision': ['int8']
}
if node_op in tf_quantizable_op_type and node_name not in self.exclude_node_names and (
node_name, self.unify_op_type_mapping[node_op]) not in self.quantizable_op_details:
if exclude_first_quantizable_op and \
(self.unify_op_type_mapping[node_op].find("conv2d") != -1 or \
self.unify_op_type_mapping[node_op].find("matmul") != -1):
exclude_first_quantizable_op = False
self.exclude_node_names.append(node_name)
continue
self._init_op_stat[node_op].append(node_name)
if self.unify_op_type_mapping[node_op].find("conv2d") != -1:
conv2d_int8_config = copy.deepcopy(conv_config)
conv2d_int8_config['pattern'] = pattern_info
self.quantizable_op_details[(
node_name, self.unify_op_type_mapping[node_op]
)] = conv2d_int8_config
elif self.unify_op_type_mapping[node_op].find("conv3d") != -1:
conv3d_int8_config = copy.deepcopy(conv3d_config)
conv3d_int8_config['pattern'] = pattern_info
self.quantizable_op_details[(
node_name, self.unify_op_type_mapping[node_op]
)] = conv3d_int8_config
elif self.unify_op_type_mapping[node_op].find("matmul") != -1:
matmul_int8_config = copy.deepcopy(matmul_config)
matmul_int8_config['pattern'] = pattern_info
# TODO enable the sym mode once the tf fixed the mkldequantize_op.cc bug.
# is_positive_input = self.pre_optimizer_handle.has_positive_input(node_name)
# matmul_scheme = 'sym' if is_positive_input else 'asym'
matmul_scheme = ['asym']
matmul_int8_config['activation']['scheme'] = matmul_scheme
self.quantizable_op_details[(
node_name, self.unify_op_type_mapping[node_op]
)] = matmul_int8_config
else:
self.quantizable_op_details[(
node_name, self.unify_op_type_mapping[node_op]
)] = copy.deepcopy(other_config)
self.quantize_config['op_wise_config'][node_name] = (False, "minmax", False)
return self.quantizable_op_details
def filter_unquantizable_concat(self, matched_nodes):
target_concat_nodes = [i[0] for i in matched_nodes if i[-1][0] == 'ConcatV2']
from neural_compressor.adaptor.tf_utils.util import GraphAnalyzer
from neural_compressor.adaptor.tf_utils.graph_util import GraphRewriterHelper
g = GraphAnalyzer()
g.graph = self.pre_optimized_model.graph_def
graph_info = g.parse_graph()
concat_nodes = g.query_fusion_pattern_nodes([['ConcatV2']])
for i in concat_nodes:
concat_node_name = i[0]
if concat_node_name not in target_concat_nodes:
continue
input_positive_status = []
for index in range(graph_info[concat_node_name].node.attr['N'].i):
each_input_name = GraphRewriterHelper.node_name_from_input(
graph_info[concat_node_name].node.input[index])
each_input_node = graph_info[each_input_name].node
positive_input = False
if each_input_node.op in ('Relu', 'Relu6'):
positive_input = True
else:
positive_input = g.has_positive_input(each_input_node.name)
input_positive_status.append(positive_input)
if not any(input_positive_status):
matched_nodes.remove(i)
def query_fw_capability(self, model):
"""Collect the model-wise and op-wise configuration for quantization.
Args:
model (tf.compat.v1.GraphDef): model definition.
Returns:
[dict]: model-wise & op-wise configuration for quantization.
"""
from .tf_utils.graph_rewriter.generic.pre_optimize import PreOptimization
self.pre_optimizer_handle = PreOptimization(model, self.optimization, self.new_api)
self.pre_optimized_model = self.pre_optimizer_handle.get_optimized_model(self.itex_mode)
model.graph_def = self.pre_optimized_model.graph_def
self.exclude_node_names = self.pre_optimizer_handle.get_excluded_node_names()
patterns = self.query_handler.generate_internal_patterns()
bf16_patterns = self.query_handler.get_bf16_patterns()
matched_nodes = self.pre_optimizer_handle.get_matched_nodes(patterns)
matched_bf16_nodes = self.pre_optimizer_handle.get_matched_nodes(bf16_patterns)
original_graph_node_name = [i.name for i in model.graph_def.node]
matched_nodes = sorted(matched_nodes, reverse=True, key=lambda i: (
original_graph_node_name.index(i[0]), len(i[-1])))
def check_match(patterns, input_pattern):
for i in patterns:
if input_pattern == [i for i in i.replace('+', ' ').strip().split(' ') if i]:
return True
return False
self.filter_unquantizable_concat(matched_nodes)
copied_matched_nodes = copy.deepcopy(matched_nodes)
for i in copied_matched_nodes:
if i[-1][0] in self.query_handler.get_op_types()['int8']:
continue
if not self.pre_optimizer_handle.has_positive_input(i[0]) and \
not check_match(self.query_handler.get_fuse_patterns()['int8'], i[-1]):
matched_nodes.remove(i)
del copied_matched_nodes
copied_matched_nodes = copy.deepcopy(matched_bf16_nodes)
for i in copied_matched_nodes:
for j in matched_nodes:
if i[0] == j[0] and i in matched_bf16_nodes:
matched_bf16_nodes.remove(i)
del copied_matched_nodes
self._query_quantizable_ops(matched_nodes)
self._query_bf16_ops(matched_bf16_nodes)
capability = {
'optypewise': self.get_optype_wise_ability(),
}
capability['opwise'] = copy.deepcopy(self.quantizable_op_details)
capability['opwise'].update(self.bf16_op_details)
logger.debug("Dump framework quantization capability:")
logger.debug(capability)
return capability
def set_tensor(self, model, tensor_dict):
from .tf_utils.graph_util import GraphAnalyzer
g = GraphAnalyzer()
g.graph = model.graph_def
graph_info = g.parse_graph()
def _get_fp32_op_name(model, tensor_name):
is_weight = False
is_biasadd = False
last_node_name = None
current_node_name = None
for each_node in model.graph_def.node:
if tensor_name in each_node.input:
tensor_index = list(each_node.input).index(tensor_name)
if each_node.op.find("Quantized") != -1 and tensor_index == 2:
is_biasadd = True
last_node_name = each_node.input[0]
current_node_name = each_node.name
if tensor_name + "_qint8_const" in each_node.input:
pass
return is_weight, is_biasadd, current_node_name, last_node_name
from neural_compressor.adaptor.tf_utils.graph_util import GraphRewriterHelper as Helper
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_util
from tensorflow.core.framework import attr_value_pb2
qint32_type = dtypes.qint32.as_datatype_enum
for tensor_name, tensor_content in tensor_dict.items():
is_weight, is_biasadd, current_node_name, last_node_name = \
_get_fp32_op_name(model, tensor_name)
if is_biasadd:
is_biasadd_dtype_is_fp32 = graph_info[\
current_node_name].node.attr['Tbias'] == attr_value_pb2.AttrValue(
type=dtypes.float32.as_datatype_enum)
current_node = graph_info[current_node_name].node
bias_add_node = graph_info[current_node.input[2]].node
if is_biasadd_dtype_is_fp32:
bias_add_node.attr["value"].CopyFrom(
attr_value_pb2.AttrValue(
tensor=tensor_util.make_tensor_proto(tensor_content,
dtypes.float32, tensor_content.shape)))
else:
last_node = graph_info[last_node_name].node
min_input = graph_info[\
last_node.input[-2]].node.attr['value'].tensor.float_val[0]
max_input = graph_info[\
last_node.input[-1]].node.attr['value'].tensor.float_val[0]
channel_size = tensor_content.shape[0]
max_filter_node = graph_info[current_node.input[6]].node
min_filter_node = graph_info[current_node.input[5]].node
if max_filter_node.attr['value'].tensor.float_val:
max_filter_tensor = []
min_filter_tensor = []
max_filter_tensor.append(\
(max_filter_node.attr['value'].tensor.float_val)[0])
min_filter_tensor.append(\
(min_filter_node.attr['value'].tensor.float_val)[0])
else:
max_filter_tensor = tensor_util.MakeNdarray(\
min_filter_node.attr['value'].tensor)
min_filter_tensor = tensor_util.MakeNdarray(\
min_filter_node.attr['value'].tensor)
activation_range = 127.0 if \
current_node.attr["Tinput"].type == dtypes.qint8 else 255.0
updated_bias = Helper.generate_int32_bias_for_conv(\
tensor_content, channel_size, max_input, min_input, \
max_filter_tensor, min_filter_tensor, activation_range)
bias_add_node.attr['dtype'].CopyFrom(\
attr_value_pb2.AttrValue(type=qint32_type))
bias_add_node.attr["value"].CopyFrom(\
attr_value_pb2.AttrValue(
tensor=tensor_util.make_tensor_proto(updated_bias,
dtypes.int32, tensor_content.shape)))
bias_add_node.attr['value'].tensor.dtype = qint32_type
current_node.attr["Tbias"].CopyFrom(attr_value_pb2.AttrValue(type=qint32_type))
if is_weight:
tmp_const_node = Helper.create_constant_node(\
current_node.name + '_weights_tmp',
tensor_content.transpose(2,3,1,0), dtypes.float32)
min_filter_node = graph_info[current_node.input[5]].node
per_channel = True if min_filter_node.attr['value'].tensor.tensor_shape else False
from .tf_utils.quantize_graph_common import QuantizeGraphHelper
original_fp32_op = current_node.op.split("With")[0].split("Quantized")[-1]
if original_fp32_op.find("Depthwise") != -1:
original_fp32_op = "DepthwiseConv2dNative"
qint8_const_node, min_node, max_node = \
QuantizeGraphHelper.generate_quantized_weight_node(
original_fp32_op, tmp_const_node, per_channel)
g.add_node(qint8_const_node, [], [current_node.name])
g.add_node(min_node, [], [current_node.name])
g.add_node(max_node, [], [current_node.name])
g.replace_constant_graph_with_constant_node(qint8_const_node, tensor_name)
g.replace_constant_graph_with_constant_node(min_node, current_node.input[5])
g.replace_constant_graph_with_constant_node(max_node, current_node.input[6])
def inspect_weight_and_bias(self, node_list, graph_def, graph_info, graph_node_name_mapping):
"""
Inspect the weights
"""
from neural_compressor.utils.utility import DequantizeWeight
from neural_compressor.adaptor.tf_utils.util import get_tensor_val_from_graph_node
from .tf_utils.util import int8_node_name_reverse
import tensorflow as tf
weights_result = {}
inspect_nodes = []
node_set = set(node_list)
for node in graph_def.node:
node_name = node.name
if 'Quantized' in node.op:
node_name = int8_node_name_reverse(node)
if node_name in node_set and ('Conv' in node.op or 'Mul' in node.op):
inspect_nodes.append(node)
logger.debug(f'Start to inspect weight and bias for: {[node.name for node in inspect_nodes]}.')
for node in inspect_nodes:
# inspect weights and bias
node_name = node.name
weight_node_name = node.input[1]
weight_node = graph_node_name_mapping[weight_node_name]
if weight_node.op != 'Const': # skip the matmul whose two inputs are previous output
continue
weight_node_val = get_tensor_val_from_graph_node(graph_node_name_mapping, weight_node_name)
weight_node_val = weight_node_val.astype('float32')
# dequantize the weight for quantized model
if 'Quantized' in node.op:
node_name = int8_node_name_reverse(node)
weight_node_name_pre = weight_node_name.split('_qint8_const')[0]
min_filter_node = weight_node_name_pre + '_min'
max_filter_node = weight_node_name_pre + '_max'
if graph_info[min_filter_node].node.attr['value'].tensor.float_val:
min_filter_val = graph_info[min_filter_node].node.attr['value'].tensor.float_val
max_filter_val = graph_info[max_filter_node].node.attr['value'].tensor.float_val
else:
min_filter_val = get_tensor_val_from_graph_node(graph_node_name_mapping, min_filter_node)
max_filter_val = get_tensor_val_from_graph_node(graph_node_name_mapping, max_filter_node)
DequantizeWeight(weight_node_val, min_filter_val, max_filter_val)
weights_result[node_name] = {weight_node_name: weight_node_val}
# get bias from quantized model directly
if 'Quantized' in node.op:
if 'Bias' in node.op:
bias_node_name = node.input[2]
bias_val = get_tensor_val_from_graph_node(graph_node_name_mapping, bias_node_name)
weights_result[node_name][bias_node_name] = bias_val.astype('float32')
# get bias from fp32 model
else:
bias_add_node = None
if graph_info[node.name].outputs:
bias_add_node = graph_info[graph_info[node.name].outputs[0]].node
if bias_add_node and bias_add_node.op == 'BiasAdd':
bias_node_name = bias_add_node.input[1]
bias_node_val = get_tensor_val_from_graph_node(graph_node_name_mapping, bias_node_name)
weights_result[node_name][bias_node_name] = bias_node_val
return weights_result
def fused_node_mapping(self, node_list, pattern_mapping, graph_info, graph_node_name_mapping):
"""
Create the mapping between first node and last node in fused sequence
Args:
node_list: node name list
pattern_mapping: key: node name, val: node pattern mapping
graph_info: key: node name, val: node details
graph_node_name_mapping: key: node name, val: node
Returns:
fused_mapping: key: first node name in fused seq, val: last node in fused seq