-
Notifications
You must be signed in to change notification settings - Fork 19
/
evalu.py
280 lines (214 loc) · 8.48 KB
/
evalu.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
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
import tensorflow as tf
from utils import queuer, util, metric
def decode_target_token(id_seq, vocab):
"""Convert sequence ids into tokens"""
valid_id_seq = []
for tok_id in id_seq:
if tok_id == vocab.eos() \
or tok_id == vocab.pad():
break
valid_id_seq.append(tok_id)
return vocab.to_tokens(valid_id_seq)
def decode_hypothesis(seqs, scores, params, mask=None):
"""Generate decoded sequence from seqs"""
if mask is None:
mask = [1.] * len(seqs)
hypoes = []
marks = []
for _seqs, _scores, _m in zip(seqs, scores, mask):
if _m < 1.: continue
for seq, score in zip(_seqs, _scores):
# Temporarily, Use top-1 decoding
best_seq = seq[0]
best_score = score[0]
hypo = decode_target_token(best_seq, params.tgt_vocab)
mark = best_score
hypoes.append(hypo)
marks.append(mark)
return hypoes, marks
def decoding(session, features, out_seqs, out_scores, dataset, params):
"""Performing decoding with exising information"""
translations = []
scores = []
indices = []
eval_queue = queuer.EnQueuer(
dataset.batcher(params.eval_batch_size,
buffer_size=params.buffer_size,
shuffle=False,
train=False),
lambda x: x,
worker_processes_num=params.process_num,
input_queue_size=params.input_queue_size,
output_queue_size=params.output_queue_size,
)
def _predict_one_batch(_data_on_gpu):
feed_dicts = {}
_step_indices = []
for fidx, shard_data in enumerate(_data_on_gpu):
# define feed_dict
_feed_dict = {
features[fidx]["source"]: shard_data['src'],
}
feed_dicts.update(_feed_dict)
# collect data indices
_step_indices.extend(shard_data['index'])
# pick up valid outputs
data_size = len(_data_on_gpu)
valid_out_seqs = out_seqs[:data_size]
valid_out_scores = out_scores[:data_size]
_decode_seqs, _decode_scores = session.run(
[valid_out_seqs, valid_out_scores], feed_dict=feed_dicts)
_step_translations, _step_scores = decode_hypothesis(
_decode_seqs, _decode_scores, params
)
return _step_translations, _step_scores, _step_indices
very_begin_time = time.time()
data_on_gpu = []
for bidx, data in enumerate(eval_queue):
if bidx == 0:
# remove the data reading time
very_begin_time = time.time()
data_on_gpu.append(data)
# use multiple gpus, and data samples is not enough
if len(params.gpus) > 0 and len(data_on_gpu) < len(params.gpus):
continue
start_time = time.time()
step_outputs = _predict_one_batch(data_on_gpu)
data_on_gpu = []
translations.extend(step_outputs[0])
scores.extend(step_outputs[1])
indices.extend(step_outputs[2])
tf.logging.info(
"Decoding Batch {} using {:.3f} s, translating {} "
"sentences using {:.3f} s in total".format(
bidx, time.time() - start_time,
len(translations), time.time() - very_begin_time
)
)
if len(data_on_gpu) > 0:
start_time = time.time()
step_outputs = _predict_one_batch(data_on_gpu)
translations.extend(step_outputs[0])
scores.extend(step_outputs[1])
indices.extend(step_outputs[2])
tf.logging.info(
"Decoding Batch {} using {:.3f} s, translating {} "
"sentences using {:.3f} s in total".format(
'final', time.time() - start_time,
len(translations), time.time() - very_begin_time
)
)
return translations, scores, indices
def scoring(session, features, out_scores, dataset, params):
"""Performing decoding with exising information"""
scores = []
indices = []
eval_queue = queuer.EnQueuer(
dataset.batcher(params.eval_batch_size,
buffer_size=params.buffer_size,
shuffle=False,
train=False),
lambda x: x,
worker_processes_num=params.process_num,
input_queue_size=params.input_queue_size,
output_queue_size=params.output_queue_size,
)
total_entropy = 0.
total_tokens = 0.
def _predict_one_batch(_data_on_gpu):
feed_dicts = {}
_step_indices = []
for fidx, shard_data in enumerate(_data_on_gpu):
# define feed_dict
_feed_dict = {
features[fidx]["source"]: shard_data['src'],
features[fidx]["target"]: shard_data['tgt'],
}
feed_dicts.update(_feed_dict)
# collect data indices
_step_indices.extend(shard_data['index'])
# pick up valid outputs
data_size = len(_data_on_gpu)
valid_out_scores = out_scores[:data_size]
_decode_scores = session.run(
valid_out_scores, feed_dict=feed_dicts)
_batch_entropy = sum([s * float((d > 0).sum())
for shard_data, shard_scores in zip(_data_on_gpu, _decode_scores)
for d, s in zip(shard_data['tgt'], shard_scores.tolist())])
_batch_tokens = sum([(shard_data['tgt'] > 0).sum() for shard_data in _data_on_gpu])
_decode_scores = [s for _scores in _decode_scores for s in _scores]
return _decode_scores, _step_indices, _batch_entropy, _batch_tokens
very_begin_time = time.time()
data_on_gpu = []
for bidx, data in enumerate(eval_queue):
if bidx == 0:
# remove the data reading time
very_begin_time = time.time()
data_on_gpu.append(data)
# use multiple gpus, and data samples is not enough
if len(params.gpus) > 0 and len(data_on_gpu) < len(params.gpus):
continue
start_time = time.time()
step_outputs = _predict_one_batch(data_on_gpu)
data_on_gpu = []
scores.extend(step_outputs[0])
indices.extend(step_outputs[1])
total_entropy += step_outputs[2]
total_tokens += step_outputs[3]
tf.logging.info(
"Decoding Batch {} using {:.3f} s, translating {} "
"sentences using {:.3f} s in total".format(
bidx, time.time() - start_time,
len(scores), time.time() - very_begin_time
)
)
if len(data_on_gpu) > 0:
start_time = time.time()
step_outputs = _predict_one_batch(data_on_gpu)
scores.extend(step_outputs[0])
indices.extend(step_outputs[1])
total_entropy += step_outputs[2]
total_tokens += step_outputs[3]
tf.logging.info(
"Decoding Batch {} using {:.3f} s, translating {} "
"sentences using {:.3f} s in total".format(
'final', time.time() - start_time,
len(scores), time.time() - very_begin_time
)
)
scores = [data[1] for data in
sorted(zip(indices, scores), key=lambda x: x[0])]
ppl = np.exp(total_entropy / total_tokens)
return scores, ppl
def eval_metric(trans, target_file, indices=None):
"""BLEU Evaluate """
target_valid_files = util.fetch_valid_ref_files(target_file)
if target_valid_files is None:
return 0.0
if indices is not None:
trans = [data[1] for data in sorted(zip(indices, trans), key=lambda x: x[0])]
references = []
for ref_file in target_valid_files:
cur_refs = tf.gfile.Open(ref_file).readlines()
cur_refs = [line.strip().split() for line in cur_refs]
references.append(cur_refs)
references = list(zip(*references))
return metric.bleu(trans, references)
def dump_tanslation(tranes, output, indices=None):
"""save translation"""
if indices is not None:
tranes = [data[1] for data in
sorted(zip(indices, tranes), key=lambda x: x[0])]
with tf.gfile.Open(output, 'w') as writer:
for hypo in tranes:
if isinstance(hypo, list):
writer.write(' '.join(hypo) + "\n")
else:
writer.write(str(hypo) + "\n")
tf.logging.info("Saving translations into {}".format(output))