forked from intel/neural-compressor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
247 lines (212 loc) · 8.79 KB
/
Copy pathmain.py
File metadata and controls
247 lines (212 loc) · 8.79 KB
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
#
# -*- 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 time
import sys
import numpy as np
import unicodedata
import six
import re
import tensorflow as tf
from absl import app
from argparse import ArgumentParser
import pandas as pd
from utils import tokenizer
from utils.tokenizer import Subtokenizer
from utils import metrics
flags = tf.compat.v1.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer("batch_size", 64,
"run batch size")
flags.DEFINE_string("input_graph", None,
"The path of input model file.")
flags.DEFINE_string("inputs_file", None,
"File saved to an output file.")
flags.DEFINE_string("reference_file", None,
"File containing reference translation.")
flags.DEFINE_string("vocab_file", None,
"Path to subtoken vocabulary file.")
flags.DEFINE_string("config", None,
"Config json file")
flags.DEFINE_string("output_model", None,
"The output model of the quantized model.")
flags.DEFINE_string("mode", "tune",
"One of three options: 'benchmark'/'accuracy'/'tune'.")
flags.DEFINE_integer("iters", -1,
"The iteration used for benchmark.")
class UnicodeRegex(object):
def __init__(self):
punctuation = self.property_chars("P")
self.nondigit_punct_re = re.compile(r"([^\d])([" + punctuation + r"])")
self.punct_nondigit_re = re.compile(r"([" + punctuation + r"])([^\d])")
self.symbol_re = re.compile("([" + self.property_chars("S") + "])")
def property_chars(self, prefix):
return "".join(six.unichr(x) for x in range(sys.maxunicode)
if unicodedata.category(six.unichr(x)).startswith(prefix))
uregex = UnicodeRegex()
def bleu_tokenize(string):
string = uregex.nondigit_punct_re.sub(r"\1 \2 ", string)
string = uregex.punct_nondigit_re.sub(r" \1 \2", string)
string = uregex.symbol_re.sub(r" \1 ", string)
return string.split()
class bleu(object):
def __init__(self):
self.translations = []
self.labels = []
def reset(self):
self.translations = []
self.labels = []
def update(self, pred, label):
if len(label) != len(pred):
raise ValueError("Reference and translation files have different number "
"of lines. If training only a few steps (100-200), the "
"translation may be empty.")
label = [x.lower() for x in label]
pred = [x.lower() for x in pred]
label = [bleu_tokenize(x) for x in label]
pred = [bleu_tokenize(x) for x in pred]
self.labels.extend(label)
self.translations.extend(pred)
def result(self):
return metrics.compute_bleu(self.labels, self.translations) * 100
def collate_fn(batch):
"""Puts each data field into a pd frame with outer dimension batch size"""
elem = batch[0]
if isinstance(elem, tuple):
batch = zip(*batch)
return [collate_fn(samples) for samples in batch]
elif isinstance(elem, np.ndarray):
return [list(elem) for elem in batch]
elif isinstance(elem, str):
return batch
else:
return pd.DataFrame(batch).fillna(0).values.astype(np.int32)
def load_graph(file_name):
tf.compat.v1.logging.info('Loading graph from: ' + file_name)
with tf.io.gfile.GFile(file_name, "rb") as f:
graph_def = tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def, name='')
return graph
def eval_func(infer_graph, iteration=-1):
if isinstance(infer_graph, tf.compat.v1.GraphDef):
graph = tf.Graph()
with graph.as_default():
tf.import_graph_def(infer_graph, name='')
infer_graph = graph
subtokenizer = Subtokenizer(FLAGS.vocab_file)
input_tensor = infer_graph.get_tensor_by_name('input_tensor:0')
output_tensor = infer_graph.get_tensor_by_name(\
'model/Transformer/strided_slice_19:0')
ds = Dataset(FLAGS.inputs_file, FLAGS.reference_file, FLAGS.vocab_file)
from neural_compressor.data import DATALOADERS
dataloader = DATALOADERS['tensorflow'](ds, batch_size=FLAGS.batch_size,
collate_fn=collate_fn)
config = tf.compat.v1.ConfigProto()
config.use_per_session_threads = 1
config.inter_op_parallelism_threads = 1
sess = tf.compat.v1.Session(graph=infer_graph, config=config)
time_list = []
bleu_eval = bleu()
predictions = []
labels = []
warmup = 10
if iteration != -1:
assert iteration >= warmup, 'iteration must be larger than warmup'
for idx, (input_data, label) in enumerate(dataloader):
if idx < iteration or iteration == -1:
time_start = time.time()
out = sess.run([output_tensor], {input_tensor: input_data})
duration = time.time() - time_start
time_list.append(duration)
predictions.append(out)
labels.extend(label)
else:
break
latency = np.array(time_list[warmup: ]).mean() / FLAGS.batch_size
print('Batch size = {}'.format(FLAGS.batch_size))
print('Latency: {:.3f} ms'.format(latency * 1000))
print('Throughput: {:.3f} items/sec'.format(1./ latency))
# only calculate accuracy when running out all predictions
if iteration == -1:
decode = []
for i,tr in enumerate(predictions):
for j,itr in enumerate(tr):
for k, otr in enumerate(itr):
try:
index = list(otr).index(tokenizer.EOS_ID)
decode.append(subtokenizer.decode(otr[:index]))
except:
decode.append(subtokenizer.decode(otr))
bleu_eval.update(decode, labels)
print('Accuracy is {:.3f}'.format(bleu_eval.result()))
return bleu_eval.result()
class Dataset(object):
def __init__(self, inputs_file, reference_file, vocab_file):
with tf.io.gfile.GFile(inputs_file) as f:
records = f.read().split("\n")
inputs = [record.strip() for record in records]
if not inputs[-1]:
inputs.pop()
self.ref_lines = tokenizer.native_to_unicode(
tf.io.gfile.GFile(reference_file).read()).strip().splitlines()
subtokenizer = Subtokenizer(vocab_file)
self.batch = []
token_lens=[]
for i, line in enumerate(inputs):
enc = subtokenizer.encode(line, add_eos=True)
token_lens.append((i, len(enc)))
sorted_by_token_input_lens = sorted(token_lens, key=lambda x: x[1], reverse=True)
sorted_inputs = [None] * len(sorted_by_token_input_lens)
sorted_keys = [0] * len(sorted_by_token_input_lens)
lines = []
for i, (index, _) in enumerate(sorted_by_token_input_lens):
sorted_inputs[i] = inputs[index]
sorted_keys[index] = i
enc=subtokenizer.encode(sorted_inputs[i], add_eos=True)
lines.append([enc])
for i in sorted_keys:
self.batch.append(lines[i])
def __getitem__(self, index):
data = self.batch[index]
label = self.ref_lines[index]
return data[0], label
def __len__(self):
return len(self.batch)
def main(_):
graph = load_graph(FLAGS.input_graph)
if FLAGS.mode == 'tune':
from neural_compressor.experimental import Quantization, common
quantizer = Quantization(FLAGS.config)
ds = Dataset(FLAGS.inputs_file, FLAGS.reference_file, FLAGS.vocab_file)
quantizer.calib_dataloader = common.DataLoader(ds, collate_fn=collate_fn, \
batch_size=FLAGS.batch_size)
quantizer.model = common.Model(graph)
quantizer.eval_func = eval_func
q_model = quantizer.fit()
try:
q_model.save(FLAGS.output_model)
except Exception as e:
print("Failed to save model due to {}".format(str(e)))
elif FLAGS.mode == 'benchmark':
eval_func(graph, FLAGS.iters)
elif FLAGS.mode == 'accuracy':
eval_func(graph, -1)
if __name__ == "__main__":
tf.compat.v1.app.run()