/
test.py
504 lines (431 loc) · 20.4 KB
/
test.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
# src: https://github.com/facebookresearch/DrQA/blob/master/scripts/reader/train.py
import sys
sys.path.append(".")
sys.path.append("..")
import os
import json
import torch
import logging
import subprocess
import argparse
import numpy as np
import c2nl.config as config
import c2nl.inputters.utils as util
import c2nl.inputters.vector as vector
import c2nl.inputters.dataset as data
from tqdm import tqdm
from main.model import Code2NaturalLanguage
from main.train import compute_eval_score
from collections import OrderedDict
from c2nl.utils.copy_utils import collapse_copy_scores, make_src_map, align
from c2nl.inputters.timer import AverageMeter, Timer
from c2nl.inputters import constants
from c2nl.eval.bleu import Bleu, nltk_corpus_bleu, corpus_bleu
from c2nl.eval.rouge import Rouge
from c2nl.eval.meteor import Meteor
from c2nl.translator.translator import Translator
from c2nl.translator.beam import GNMTGlobalScorer
from c2nl.translator.translation import TranslationBuilder
logger = logging.getLogger()
def str2bool(v):
return v.lower() in ('yes', 'true', 't', '1', 'y')
def add_test_args(parser):
"""Adds commandline arguments pertaining to training a model. These
are different from the arguments dictating the model architecture.
"""
parser.register('type', 'bool', str2bool)
# Runtime environment
runtime = parser.add_argument_group('Environment')
runtime.add_argument('--data_workers', type=int, default=5,
help='Number of subprocesses for data loading')
runtime.add_argument('--random_seed', type=int, default=1013,
help=('Random seed for all numpy/torch/cuda '
'operations (for reproducibility)'))
runtime.add_argument('--test_batch_size', type=int, default=128,
help='Batch size during validation/testing')
# Files
files = parser.add_argument_group('Filesystem')
files.add_argument('--dataset_name', nargs='+', type=str, default='methodcom',
help='Name of the experimental dataset')
files.add_argument('--model_dir', type=str, default='/tmp/qa_models/',
help='Directory for saved models/checkpoints/logs')
files.add_argument('--model_name', type=str, default='',
help='Unique model identifier (.mdl, .txt, .checkpoint)')
files.add_argument('--data_dir', type=str, default='/data/',
help='Directory of training/validation data')
files.add_argument('--dev_src', nargs='+', type=str, required=True,
help='Preprocessed dev source file')
files.add_argument('--dev_src_tag', nargs='+', type=str, required=True,
help='Preprocessed dev source tag file')
files.add_argument('--dev_tgt', nargs='+', type=str, required=True,
help='Preprocessed dev target file')
# Data preprocessing
preprocess = parser.add_argument_group('Preprocessing')
preprocess.add_argument('--max_examples', type=int, default=-1,
help='Maximum number of examples for training')
preprocess.add_argument('--uncase', type='bool', default=False,
help='Code and summary words will be lower-cased')
preprocess.add_argument('--max_characters_per_token', type=int, default=30,
help='Maximum number of characters allowed per token')
# General
general = parser.add_argument_group('General')
general.add_argument('--sort_by_len', type='bool', default=True,
help='Sort batches by length for speed')
# Beam Search
bsearch = parser.add_argument_group('Beam Search arguments')
bsearch.add_argument('--beam_size', type=int, default=4,
help='Set the beam size (=1 means greedy decoding)')
bsearch.add_argument('--n_best', type=int, default=1,
help="""If verbose is set, will output the n_best
decoded sentences""")
bsearch.add_argument('--stepwise_penalty', type='bool', default=False,
help="""Apply penalty at every decoding step.
Helpful for summary penalty.""")
bsearch.add_argument('--length_penalty', default='none',
choices=['none', 'wu', 'avg'],
help="""Length Penalty to use.""")
bsearch.add_argument('--coverage_penalty', default='none',
choices=['none', 'wu', 'summary'],
help="""Coverage Penalty to use.""")
bsearch.add_argument('--block_ngram_repeat', type=int, default=0,
help='Block repetition of ngrams during decoding.')
bsearch.add_argument('--ignore_when_blocking', nargs='+', type=str,
default=[],
help="""Ignore these strings when blocking repeats.
You want to block sentence delimiters.""")
bsearch.add_argument('--gamma', type=float, default=0.,
help="""Google NMT length penalty parameter
(higher = longer generation)""")
bsearch.add_argument('--beta', type=float, default=0.,
help="""Coverage penalty parameter""")
bsearch.add_argument('--replace_unk', action="store_true",
help="""Replace the generated UNK tokens with the
source token that had highest attention weight. If
phrase_table is provided, it will lookup the
identified source token and give the corresponding
target token. If it is not provided(or the identified
source token does not exist in the table) then it
will copy the source token""")
bsearch.add_argument('--verbose', action="store_true",
help='Print scores and predictions for each sentence')
def set_defaults(args):
"""Make sure the commandline arguments are initialized properly."""
# Check critical files exist
args.dev_src_files = []
args.dev_tgt_files = []
args.dev_src_tag_files = []
num_dataset = len(args.dataset_name)
if num_dataset > 1:
if len(args.dev_src) == 1:
args.dev_src = args.dev_src * num_dataset
if len(args.dev_tgt) == 1:
args.dev_tgt = args.dev_tgt * num_dataset
if len(args.dev_src_tag) == 1:
args.dev_src_tag = args.dev_src_tag * num_dataset
for i in range(num_dataset):
dataset_name = args.dataset_name[i]
data_dir = os.path.join(args.data_dir, dataset_name)
dev_src = os.path.join(data_dir, args.dev_src[i])
dev_tgt = os.path.join(data_dir, args.dev_tgt[i])
if not os.path.isfile(dev_src):
raise IOError('No such file: %s' % dev_src)
if not os.path.isfile(dev_tgt):
raise IOError('No such file: %s' % dev_tgt)
if args.use_code_type:
dev_src_tag = os.path.join(data_dir, args.dev_src_tag[i])
if not os.path.isfile(dev_src_tag):
raise IOError('No such file: %s' % dev_src_tag)
else:
dev_src_tag = None
args.dev_src_files.append(dev_src)
args.dev_tgt_files.append(dev_tgt)
args.dev_src_tag_files.append(dev_src_tag)
# Set model directory
subprocess.call(['mkdir', '-p', args.model_dir])
# Set model name
if not args.model_name:
import uuid
import time
args.model_name = time.strftime("%Y%m%d-") + str(uuid.uuid4())[:8]
# Set log + model file names
args.log_file = os.path.join(args.model_dir, args.model_name + '_beam.txt')
args.model_file = os.path.join(args.model_dir, args.model_name + '.mdl')
args.pred_file = os.path.join(args.model_dir, args.model_name + '_beam.json')
# ------------------------------------------------------------------------------
# Validation loops. Includes both "unofficial" and "official" functions that
# use different metrics and implementations.
# ------------------------------------------------------------------------------
def build_translator(model, args):
scorer = GNMTGlobalScorer(args.gamma,
args.beta,
args.coverage_penalty,
args.length_penalty)
translator = Translator(model,
args.cuda,
args.beam_size,
n_best=args.n_best,
max_length=args.max_tgt_len,
copy_attn=model.args.copy_attn,
global_scorer=scorer,
min_length=0,
stepwise_penalty=args.stepwise_penalty,
block_ngram_repeat=args.block_ngram_repeat,
ignore_when_blocking=args.ignore_when_blocking,
replace_unk=args.replace_unk)
return translator
def prepare_batch(batch, model):
# To enable copy attn, collect source map and alignment info
batch_inputs = dict()
if model.args.copy_attn:
assert 'src_map' in batch and 'alignment' in batch
source_map = make_src_map(batch['src_map'])
source_map = source_map.cuda(non_blocking=True) if args.cuda \
else source_map
if batch['alignment'][0] is not None:
alignment = align(batch['alignment'])
alignment = alignment.cuda(non_blocking=True) if args.cuda \
else alignment
else:
alignment = None
blank, fill = collapse_copy_scores(model.tgt_dict, batch['src_vocab'])
else:
source_map, alignment = None, None
blank, fill = None, None
batch_inputs['src_map'] = source_map
batch_inputs['alignment'] = alignment
batch_inputs['blank'] = blank
batch_inputs['fill'] = fill
code_word_rep = batch['code_word_rep']
code_char_rep = batch['code_char_rep']
code_type_rep = batch['code_type_rep']
code_mask_rep = batch['code_mask_rep']
code_len = batch['code_len']
if args.cuda:
code_len = batch['code_len'].cuda(non_blocking=True)
if code_word_rep is not None:
code_word_rep = code_word_rep.cuda(non_blocking=True)
if code_char_rep is not None:
code_char_rep = code_char_rep.cuda(non_blocking=True)
if code_type_rep is not None:
code_type_rep = code_type_rep.cuda(non_blocking=True)
if code_mask_rep is not None:
code_mask_rep = code_mask_rep.cuda(non_blocking=True)
batch_inputs['code_word_rep'] = code_word_rep
batch_inputs['code_char_rep'] = code_char_rep
batch_inputs['code_type_rep'] = code_type_rep
batch_inputs['code_mask_rep'] = code_mask_rep
batch_inputs['code_len'] = code_len
return batch_inputs
def validate_official(args, data_loader, model):
"""Run one full official validation. Uses exact spans and same
exact match/F1 score computation as in the SQuAD script.
Extra arguments:
offsets: The character start/end indices for the tokens in each context.
texts: Map of qid --> raw text of examples context (matches offsets).
answers: Map of qid --> list of accepted answers.
"""
eval_time = Timer()
translator = build_translator(model, args)
builder = TranslationBuilder(model.tgt_dict,
n_best=args.n_best,
replace_unk=args.replace_unk)
# Run through examples
examples = 0
trans_dict, sources = dict(), dict()
with torch.no_grad():
pbar = tqdm(data_loader)
for batch_no, ex in enumerate(pbar):
batch_size = ex['batch_size']
ids = list(range(batch_no * batch_size,
(batch_no * batch_size) + batch_size))
batch_inputs = prepare_batch(ex, model)
ret = translator.translate_batch(batch_inputs)
targets = [[summ] for summ in ex['summ_text']]
translations = builder.from_batch(ret,
ex['code_tokens'],
targets,
ex['src_vocab'])
src_sequences = [code for code in ex['code_text']]
for eid, trans, src in zip(ids, translations, src_sequences):
trans_dict[eid] = trans
sources[eid] = src
examples += batch_size
hypotheses, references = dict(), dict()
for eid, trans in trans_dict.items():
hypotheses[eid] = [' '.join(pred) for pred in trans.pred_sents]
hypotheses[eid] = [constants.PAD_WORD if len(hyp.split()) == 0
else hyp for hyp in hypotheses[eid]]
references[eid] = trans.targets
bleu, rouge_l, meteor, precision, recall, f1, ind_bleu, ind_rouge = \
eval_accuracies(hypotheses, references)
logger.info('beam evaluation official: '
'bleu = %.2f | rouge_l = %.2f | meteor = %.2f | ' %
(bleu, rouge_l, meteor) +
'Precision = %.2f | Recall = %.2f | F1 = %.2f | '
'examples = %d | ' %
(precision, recall, f1, examples) +
'test time = %.2f (s)' % eval_time.time())
with open(args.pred_file, 'w') as fw:
for eid, translation in trans_dict.items():
out_dict = OrderedDict()
out_dict['id'] = eid
out_dict['code'] = sources[eid]
# printing all beam search predictions
out_dict['predictions'] = [' '.join(pred) for pred in translation.pred_sents]
out_dict['references'] = references[eid]
out_dict['bleu'] = ind_bleu[eid]
out_dict['rouge_l'] = ind_rouge[eid]
fw.write(json.dumps(out_dict) + '\n')
def eval_accuracies(hypotheses, references):
"""An unofficial evalutation helper.
Arguments:
hypotheses: A mapping from instance id to predicted sequences.
references: A mapping from instance id to ground truth sequences.
copy_info: Map of id --> copy information.
sources: Map of id --> input text sequence.
filename:
print_copy_info:
"""
assert sorted(references.keys()) == sorted(hypotheses.keys())
# Compute BLEU scores
# bleu_scorer = Bleu(n=4)
# _, _, bleu = bleu_scorer.compute_score(references, hypotheses, verbose=0)
# bleu = compute_bleu(references, hypotheses, max_order=4)['bleu']
# _, bleu, _ = nltk_corpus_bleu(hypotheses, references)
_, bleu, ind_bleu = corpus_bleu(hypotheses, references)
# Compute ROUGE scores
rouge_calculator = Rouge()
rouge_l, ind_rouge = rouge_calculator.compute_score(references, hypotheses)
# Compute METEOR scores
meteor_calculator = Meteor()
meteor, _ = meteor_calculator.compute_score(references, hypotheses)
f1 = AverageMeter()
precision = AverageMeter()
recall = AverageMeter()
for key in references.keys():
_prec, _rec, _f1 = compute_eval_score(hypotheses[key][0], references[key])
precision.update(_prec)
recall.update(_rec)
f1.update(_f1)
return bleu * 100, rouge_l * 100, meteor * 100, precision.avg * 100, \
recall.avg * 100, f1.avg * 100, ind_bleu, ind_rouge
# ------------------------------------------------------------------------------
# Batchifying examples.
# ------------------------------------------------------------------------------
def get_batches(examples, bsz, shuffle=True):
lengths = [len(ex.document) for ex in examples]
clusters = dict()
for i, num_pass in enumerate(lengths):
if num_pass in clusters:
clusters[num_pass].append(i)
else:
clusters[num_pass] = [i]
batches = []
for key, indices in clusters.items():
if shuffle:
np.random.shuffle(indices)
for i, idx in enumerate(indices):
if i % bsz == 0:
batches.append([examples[idx]])
else:
batches[len(batches) - 1].append(examples[idx])
if shuffle:
np.random.shuffle(batches)
return batches
# ------------------------------------------------------------------------------
# Main.
# ------------------------------------------------------------------------------
def main(args):
# --------------------------------------------------------------------------
# DATA
logger.info('-' * 100)
logger.info('Load and process data files')
dev_exs = []
for dev_src, dev_src_tag, dev_tgt, dataset_name in \
zip(args.dev_src_files, args.dev_src_tag_files,
args.dev_tgt_files, args.dataset_name):
dev_files = dict()
dev_files['src'] = dev_src
dev_files['src_tag'] = dev_src_tag
dev_files['tgt'] = dev_tgt
exs = util.load_data(args,
dev_files,
max_examples=args.max_examples,
dataset_name=dataset_name,
test_split=True)
dev_exs.extend(exs)
logger.info('Num dev examples = %d' % len(dev_exs))
# --------------------------------------------------------------------------
# MODEL
logger.info('-' * 100)
if not os.path.isfile(args.model_file):
raise IOError('No such file: %s' % args.model_file)
model = Code2NaturalLanguage.load(args.model_file)
# Use the GPU?
if args.cuda:
model.cuda()
# Use multiple GPUs?
if args.parallel:
model.parallelize()
# --------------------------------------------------------------------------
# DATA ITERATORS
# Two datasets: train and dev. If we sort by length it's faster.
logger.info('-' * 100)
logger.info('Make data loaders')
dev_dataset = data.CommentDataset(dev_exs, model)
dev_sampler = torch.utils.data.sampler.SequentialSampler(dev_dataset)
# if args.sort_by_len:
# dev_sampler = data.SortedBatchSampler(dev_dataset.lengths(),
# args.test_batch_size,
# shuffle=False)
# else:
# dev_sampler = torch.utils.data.sampler.SequentialSampler(dev_dataset)
dev_loader = torch.utils.data.DataLoader(
dev_dataset,
batch_size=args.test_batch_size,
sampler=dev_sampler,
num_workers=args.data_workers,
collate_fn=vector.batchify,
pin_memory=args.cuda,
drop_last=args.parallel
)
# -------------------------------------------------------------------------
# PRINT CONFIG
logger.info('-' * 100)
logger.info('CONFIG:\n%s' %
json.dumps(vars(args), indent=4, sort_keys=True))
# --------------------------------------------------------------------------
# DO TEST
validate_official(args, dev_loader, model)
if __name__ == '__main__':
# Parse cmdline args and setup environment
parser = argparse.ArgumentParser(
'Open Keyphrase Generation',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
add_test_args(parser)
config.add_model_args(parser)
args = parser.parse_args()
set_defaults(args)
# Set cuda
args.cuda = torch.cuda.is_available()
args.parallel = torch.cuda.device_count() > 1
# Set random state
np.random.seed(args.random_seed)
torch.manual_seed(args.random_seed)
if args.cuda:
torch.cuda.manual_seed(args.random_seed)
# Set logging
logger.setLevel(logging.INFO)
fmt = logging.Formatter('%(asctime)s: [ %(message)s ]',
'%m/%d/%Y %I:%M:%S %p')
console = logging.StreamHandler()
console.setFormatter(fmt)
logger.addHandler(console)
if args.log_file:
logfile = logging.FileHandler(args.log_file, 'w')
logfile.setFormatter(fmt)
logger.addHandler(logfile)
logger.info('COMMAND: %s' % ' '.join(sys.argv))
# Run!
main(args)