-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
558 lines (474 loc) · 15.1 KB
/
main.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
"""Script for training and evaluating QA models.
Example command to train the (medium-sized) baseline model on SQuAD
with a GPU, and write its predictions to an output file:
Usage:
python3 main.py \
--use_gpu \
--model "baseline" \
--model_path "squad_model.pt" \
--train_path "datasets/squad_train.jsonl.gz" \
--dev_path "datasets/squad_dev.jsonl.gz" \
--output_path "squad_predictions.txt" \
--hidden_dim 256 \
--bidirectional \
--do_train \
--do_test
Author:
Shrey Desai and Yasumasa Onoe
"""
import argparse
import pprint
import json
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm
from data import QADataset, Tokenizer, Vocabulary
from model import BaselineReader
from utils import cuda, search_span_endpoints, unpack
_TQDM_BAR_SIZE = 75
_TQDM_LEAVE = False
_TQDM_UNIT = ' batches'
_TQDM_OPTIONS = {
'ncols': _TQDM_BAR_SIZE, 'leave': _TQDM_LEAVE, 'unit': _TQDM_UNIT
}
parser = argparse.ArgumentParser()
# Training arguments.
parser.add_argument('--device', type=int)
parser.add_argument(
'--use_gpu',
action='store_true',
help='whether to use GPU',
)
parser.add_argument(
'--model',
type=str,
required=True,
choices=['baseline'],
help='which model to use',
)
parser.add_argument(
'--model_path',
type=str,
required=True,
help='path to load/save model checkpoints',
)
parser.add_argument(
'--embedding_path',
type=str,
default='glove/glove.6B.300d.txt',
help='GloVe embedding path',
)
parser.add_argument(
'--train_path',
type=str,
required=True,
help='training dataset path',
)
parser.add_argument(
'--dev_path',
type=str,
required=True,
help='dev dataset path',
)
parser.add_argument(
'--max_context_length',
type=int,
default=384,
help='maximum context length (do not change!)',
)
parser.add_argument(
'--max_question_length',
type=int,
default=64,
help='maximum question length (do not change!)',
)
parser.add_argument(
'--output_path',
type=str,
required=False,
help='predictions output path',
)
parser.add_argument(
'--shuffle_examples',
action='store_true',
help='shuffle training example at the beginning of each epoch',
)
# Optimization arguments.
parser.add_argument(
'--epochs',
type=int,
default=10,
help='number of training epochs',
)
parser.add_argument(
'--batch_size',
type=int,
default=64,
help='training and evaluation batch size',
)
parser.add_argument(
'--learning_rate',
type=float,
default=1e-3,
help='training learning rate',
)
parser.add_argument(
'--weight_decay',
type=float,
default=0.,
help='training weight decay',
)
parser.add_argument(
'--grad_clip',
type=float,
default=0.5,
help='gradient norm clipping value',
)
parser.add_argument(
'--early_stop',
type=int,
default=3,
help='number of epochs to wait until early stopping',
)
parser.add_argument(
'--do_train',
action='store_true',
help='flag to enable training',
)
parser.add_argument(
'--do_test',
action='store_true',
help='flag to enable testing',
)
# Model arguments.
parser.add_argument(
'--vocab_size',
type=int,
default=50000,
help='vocabulary size (dynamically set, do not change!)',
)
parser.add_argument(
'--embedding_dim',
type=int,
default=1024,
help='embedding dimension',
)
parser.add_argument(
'--hidden_dim',
type=int,
default=256,
help='hidden state dimension',
)
parser.add_argument(
'--rnn_cell_type',
choices=['lstm', 'gru'],
default='lstm',
help='Type of RNN cell',
)
parser.add_argument(
'--bidirectional',
action='store_true',
help='use bidirectional RNN',
)
parser.add_argument(
'--dropout',
type=float,
default=0.,
help='dropout on passage and question vectors',
)
def _print_arguments(args):
"""Pretty prints command line args to stdout.
Args:
args: `argparse` object.
"""
args_dict = vars(args)
pprint.pprint(args_dict)
def _select_model(args):
"""
Selects and initializes model. To integrate custom models, (1)
add the model name to the parser choices above, and (2) modify
the conditional statements to include an instance of the model.
Args:
args: `argparse` object.
Returns:
Instance of a PyTorch model supplied with args.
"""
if args.model == 'baseline':
return BaselineReader(args)
else:
raise RuntimeError(f'model \'{args.model}\' not recognized!')
def _early_stop(args, eval_history):
"""
Determines early stopping conditions. If the evaluation loss has
not improved after `args.early_stop` epoch(s), then training
is ended prematurely.
Args:
args: `argparse` object.
eval_history: List of booleans that indicate whether an epoch resulted
in a model checkpoint, or in other words, if the evaluation loss
was lower than previous losses.
Returns:
Boolean indicating whether training should stop.
"""
return (
len(eval_history) > args.early_stop
and not any(eval_history[-args.early_stop:])
)
def _calculate_loss(
start_logits, end_logits, start_positions, end_positions
):
"""
Calculates cross-entropy loss for QA samples, which is defined as
the mean of the loss values incurred by the starting and ending position
distributions when compared to the gold endpoints.
Args:
start_logits: Predicted distribution over start positions.
end_logits: Predicted distribution over end positions.
start_positions: Gold start positions.
end_positions: Gold end positions.
Returns:
Loss value for a batch of sasmples.
"""
# If the gold span is outside the scope of the maximum
# context length, then ignore these indices when computing the loss.
ignored_index = start_logits.size(1)
start_positions.clamp_(0, ignored_index)
end_positions.clamp_(0, ignored_index)
# Compute the cross-entropy loss for the start and end logits.
criterion = nn.CrossEntropyLoss(ignore_index=ignored_index)
start_loss = criterion(start_logits, start_positions)
end_loss = criterion(end_logits, end_positions)
return (start_loss + end_loss) / 2.
def train(args, epoch, model, dataset):
"""
Trains the model for a single epoch using the training dataset.
Args:
args: `argparse` object.
epoch: Epoch number (used in the `tqdm` bar).
model: Instance of the PyTorch model.
dataset: Training dataset.
Returns:
Training cross-entropy loss normalized across all samples.
"""
# Set the model in "train" mode.
model.train()
# Cumulative loss and steps.
train_loss = 0.
train_steps = 0
# Set up optimizer.
optimizer = optim.Adam(
model.parameters(),
lr=args.learning_rate,
weight_decay=args.weight_decay,
)
# Set up training dataloader. Creates `args.batch_size`-sized
# batches from available samples.
train_dataloader = tqdm(
dataset.get_batch(shuffle_examples=args.shuffle_examples),
**_TQDM_OPTIONS,
)
for batch in train_dataloader:
# Zero gradients.
optimizer.zero_grad()
# Forward inputs, calculate loss, optimize model.
start_logits, end_logits = model(batch)
loss = _calculate_loss(
start_logits,
end_logits,
batch['start_positions'],
batch['end_positions'],
)
loss.backward()
if args.grad_clip > 0.:
torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
optimizer.step()
# Update tqdm bar.
train_loss += loss.item()
train_steps += 1
train_dataloader.set_description(
f'[train] epoch = {epoch}, loss = {train_loss / train_steps:.6f}'
)
return train_loss / train_steps
def evaluate(args, epoch, model, dataset):
"""
Evaluates the model for a single epoch using the development dataset.
Args:
args: `argparse` object.
epoch: Epoch number (used in the `tqdm` bar).
model: Instance of the PyTorch model.
dataset: Development dataset.
Returns:
Evaluation cross-entropy loss normalized across all samples.
"""
# Set the model in "evaluation" mode.
model.eval()
# Cumulative loss and steps.
eval_loss = 0.
eval_steps = 0
# Set up evaluation dataloader. Creates `args.batch_size`-sized
# batches from available samples. Does not shuffle.
eval_dataloader = tqdm(
dataset.get_batch(shuffle_examples=False),
**_TQDM_OPTIONS,
)
with torch.no_grad():
for batch in eval_dataloader:
# Forward inputs, calculate loss.
start_logits, end_logits = model(batch)
loss = _calculate_loss(
start_logits,
end_logits,
batch['start_positions'],
batch['end_positions'],
)
# Update tqdm bar.
eval_loss += loss.item()
eval_steps += 1
eval_dataloader.set_description(
f'[eval] epoch = {epoch}, loss = {eval_loss / eval_steps:.6f}'
)
return eval_loss / eval_steps
def write_predictions(args, model, dataset):
"""
Writes model predictions to an output file. The official QA metrics (EM/F1)
can be computed using `evaluation.py`.
Args:
args: `argparse` object.
model: Instance of the PyTorch model.
dataset: Test dataset (technically, the development dataset since the
official test datasets are blind and hosted by official servers).
"""
# Load model checkpoint.
model.eval()
# Set up test dataloader.
test_dataloader = tqdm(
dataset.get_batch(shuffle_examples=False),
**_TQDM_OPTIONS,
)
# Output predictions.
outputs = []
with torch.no_grad():
for (i, batch) in enumerate(test_dataloader):
# Forward inputs.
start_logits, end_logits = model(batch)
# Form distributions over start and end positions.
batch_start_probs = F.softmax(start_logits, 1)
batch_end_probs = F.softmax(end_logits, 1)
for j in range(start_logits.size(0)):
# Find question index and passage.
sample_index = args.batch_size * i + j
qid, passage, _, _, _, _, _ = dataset.samples[sample_index]
# Unpack start and end probabilities. Find the constrained
# (start, end) pair that has the highest joint probability.
start_probs = unpack(batch_start_probs[j])
end_probs = unpack(batch_end_probs[j])
start_index, end_index = search_span_endpoints(
start_probs, end_probs
)
# Grab predicted span.
pred_span = ' '.join(passage[start_index:(end_index + 1)])
# Add prediction to outputs.
outputs.append({'qid': qid, 'answer': pred_span})
# Write predictions to output file.
with open(args.output_path, 'w+') as f:
for elem in outputs:
f.write(f'{json.dumps(elem)}\n')
def main(args):
"""
Main function for training, evaluating, and checkpointing.
Args:
args: `argparse` object.
"""
# Print arguments.
print('\nusing arguments:')
_print_arguments(args)
print()
# Check if GPU is available.
if not args.use_gpu and torch.cuda.is_available():
print('warning: GPU is available but args.use_gpu = False')
print()
# Set up datasets.
train_dataset = QADataset(args, args.train_path)
dev_dataset = QADataset(args, args.dev_path)
# Create vocabulary and tokenizer.
vocabulary = Vocabulary(train_dataset.samples, args.vocab_size)
tokenizer = Tokenizer(vocabulary)
for dataset in (train_dataset, dev_dataset):
dataset.register_tokenizer(tokenizer)
args.vocab_size = len(vocabulary)
args.pad_token_id = tokenizer.pad_token_id
print(f'vocab words = {len(vocabulary)}')
# Print number of samples.
print(f'train samples = {len(train_dataset)}')
print(f'dev samples = {len(dev_dataset)}')
print()
sentencesPlsDontLetThisVarBeTaken = list()
for sample in train_dataset.samples:
passage = sample[1]
sentencesPlsDontLetThisVarBeTaken.append(passage)
# Select model.
model = _select_model(args)
num_pretrained = model.load_pretrained_embeddings(
vocabulary, args.embedding_path, sentencesPlsDontLetThisVarBeTaken
)
pct_pretrained = round(num_pretrained / len(vocabulary) * 100., 2)
print(f'using pre-trained embeddings from \'{args.embedding_path}\'')
print(
f'initialized {num_pretrained}/{len(vocabulary)} '
f'embeddings ({pct_pretrained}%)'
)
print()
if args.use_gpu:
model = cuda(args, model)
params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'using model \'{args.model}\' ({params} params)')
print(model)
print()
if args.do_train:
# Track training statistics for checkpointing.
eval_history = []
best_eval_loss = float('inf')
# Begin training.
for epoch in range(1, args.epochs + 1):
# Perform training and evaluation steps.
train_loss = train(args, epoch, model, train_dataset)
eval_loss = evaluate(args, epoch, model, dev_dataset)
# If the model's evaluation loss yields a global improvement,
# checkpoint the model.
eval_history.append(eval_loss < best_eval_loss)
if eval_loss < best_eval_loss:
best_eval_loss = eval_loss
torch.save(model.state_dict(), args.model_path)
print(
f'epoch = {epoch} | '
f'train loss = {train_loss:.6f} | '
f'eval loss = {eval_loss:.6f} | '
f"{'saving model!' if eval_history[-1] else ''}"
)
# If early stopping conditions are met, stop training.
if _early_stop(args, eval_history):
suffix = 's' if args.early_stop > 1 else ''
print(
f'no improvement after {args.early_stop} epoch{suffix}. '
'early stopping...'
)
print()
break
if args.do_test:
# Write predictions to the output file. Use the printed command
# below to obtain official EM/F1 metrics.
write_predictions(args, model, dev_dataset)
eval_cmd = (
'python3 evaluate.py '
f'--dataset_path {args.dev_path} '
f'--output_path {args.output_path}'
)
print()
print(f'predictions written to \'{args.output_path}\'')
print(f'compute EM/F1 with: \'{eval_cmd}\'')
print()
if __name__ == '__main__':
main(parser.parse_args())