Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yiming-wange
GitHub Repository: yiming-wange/cs224n-2023-solution
Path: blob/main/a4/run.py
995 views
1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
4
"""
5
CS224N 2022-23: Homework 4
6
run.py: Run Script for Simple NMT Model
7
Pencheng Yin <[email protected]>
8
Sahil Chopra <[email protected]>
9
Vera Lin <[email protected]>
10
Siyan Li <[email protected]>
11
12
Usage:
13
run.py train --train-src=<file> --train-tgt=<file> --dev-src=<file> --dev-tgt=<file> --vocab=<file> [options]
14
run.py decode [options] MODEL_PATH TEST_SOURCE_FILE OUTPUT_FILE
15
run.py decode [options] MODEL_PATH TEST_SOURCE_FILE TEST_TARGET_FILE OUTPUT_FILE
16
17
Options:
18
-h --help show this screen.
19
--cuda use GPU
20
--train-src=<file> train source file
21
--train-tgt=<file> train target file
22
--dev-src=<file> dev source file
23
--dev-tgt=<file> dev target file
24
--vocab=<file> vocab file
25
--seed=<int> seed [default: 0]
26
--batch-size=<int> batch size [default: 32]
27
--embed-size=<int> embedding size [default: 256]
28
--hidden-size=<int> hidden size [default: 256]
29
--clip-grad=<float> gradient clipping [default: 5.0]
30
--log-every=<int> log every [default: 10]
31
--max-epoch=<int> max epoch [default: 30]
32
--input-feed use input feeding
33
--patience=<int> wait for how many iterations to decay learning rate [default: 5]
34
--max-num-trial=<int> terminate training after how many trials [default: 5]
35
--lr-decay=<float> learning rate decay [default: 0.5]
36
--beam-size=<int> beam size [default: 5]
37
--sample-size=<int> sample size [default: 5]
38
--lr=<float> learning rate [default: 0.001]
39
--uniform-init=<float> uniformly initialize all parameters [default: 0.1]
40
--save-to=<file> model save path [default: model.bin]
41
--valid-niter=<int> perform validation after how many iterations [default: 2000]
42
--dropout=<float> dropout [default: 0.3]
43
--max-decoding-time-step=<int> maximum number of decoding time steps [default: 70]
44
"""
45
import math
46
import sys
47
import pickle
48
import time
49
50
51
from docopt import docopt
52
# from nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction
53
import sacrebleu
54
from nmt_model import Hypothesis, NMT
55
import numpy as np
56
from typing import List, Tuple, Dict, Set, Union
57
from tqdm import tqdm
58
from utils import read_corpus, batch_iter
59
from vocab import Vocab, VocabEntry
60
61
import torch
62
import torch.nn.utils
63
from torch.utils.tensorboard import SummaryWriter
64
65
66
def evaluate_ppl(model, dev_data, batch_size=32):
67
""" Evaluate perplexity on dev sentences
68
@param model (NMT): NMT Model
69
@param dev_data (list of (src_sent, tgt_sent)): list of tuples containing source and target sentence
70
@param batch_size (batch size)
71
@returns ppl (perplixty on dev sentences)
72
"""
73
was_training = model.training
74
model.eval()
75
76
cum_loss = 0.
77
cum_tgt_words = 0.
78
79
# no_grad() signals backend to throw away all gradients
80
with torch.no_grad():
81
for src_sents, tgt_sents in batch_iter(dev_data, batch_size):
82
loss = -model(src_sents, tgt_sents).sum()
83
84
cum_loss += loss.item()
85
tgt_word_num_to_predict = sum(len(s[1:]) for s in tgt_sents) # omitting leading `<s>`
86
cum_tgt_words += tgt_word_num_to_predict
87
88
ppl = np.exp(cum_loss / cum_tgt_words)
89
90
if was_training:
91
model.train()
92
93
return ppl
94
95
96
def compute_corpus_level_bleu_score(references: List[List[str]], hypotheses: List[Hypothesis]) -> float:
97
""" Given decoding results and reference sentences, compute corpus-level BLEU score.
98
@param references (List[List[str]]): a list of gold-standard reference target sentences
99
@param hypotheses (List[Hypothesis]): a list of hypotheses, one for each reference
100
@returns bleu_score: corpus-level BLEU score
101
"""
102
# remove the start and end tokens
103
if references[0][0] == '<s>':
104
references = [ref[1:-1] for ref in references]
105
106
# detokenize the subword pieces to get full sentences
107
detokened_refs = [''.join(pieces).replace('▁', ' ') for pieces in references]
108
detokened_hyps = [''.join(hyp.value).replace('▁', ' ') for hyp in hypotheses]
109
110
# sacreBLEU can take multiple references (golden example per sentence) but we only feed it one
111
bleu = sacrebleu.corpus_bleu(detokened_hyps, [detokened_refs])
112
113
return bleu.score
114
115
116
def train(args: Dict):
117
""" Train the NMT Model.
118
@param args (Dict): args from cmd line
119
"""
120
train_data_src = read_corpus(args['--train-src'], source='src', vocab_size=21000) # EDIT: NEW VOCAB SIZE
121
train_data_tgt = read_corpus(args['--train-tgt'], source='tgt', vocab_size=8000)
122
123
dev_data_src = read_corpus(args['--dev-src'], source='src', vocab_size=3000)
124
dev_data_tgt = read_corpus(args['--dev-tgt'], source='tgt', vocab_size=2000)
125
126
train_data = list(zip(train_data_src, train_data_tgt))
127
dev_data = list(zip(dev_data_src, dev_data_tgt))
128
129
train_batch_size = int(args['--batch-size'])
130
clip_grad = float(args['--clip-grad'])
131
valid_niter = int(args['--valid-niter'])
132
log_every = int(args['--log-every'])
133
model_save_path = args['--save-to']
134
135
vocab = Vocab.load(args['--vocab'])
136
137
# model = NMT(embed_size=int(args['--embed-size']), # EDIT: 4X EMBED AND HIDDEN SIZES
138
# hidden_size=int(args['--hidden-size']),
139
# dropout_rate=float(args['--dropout']),
140
# vocab=vocab)
141
142
model = NMT(embed_size=1024,
143
hidden_size=768,
144
dropout_rate=float(args['--dropout']),
145
vocab=vocab)
146
147
tensorboard_path = "nmt" if args['--cuda'] else "nmt_local"
148
writer = SummaryWriter(log_dir=f"./runs/{tensorboard_path}")
149
model.train()
150
151
uniform_init = float(args['--uniform-init'])
152
if np.abs(uniform_init) > 0.:
153
print('uniformly initialize parameters [-%f, +%f]' % (uniform_init, uniform_init), file=sys.stderr)
154
for p in model.parameters():
155
p.data.uniform_(-uniform_init, uniform_init)
156
157
vocab_mask = torch.ones(len(vocab.tgt))
158
vocab_mask[vocab.tgt['<pad>']] = 0
159
160
device = torch.device("cuda:0" if args['--cuda'] else "cpu")
161
print('use device: %s' % device, file=sys.stderr)
162
163
model = model.to(device)
164
165
optimizer = torch.optim.Adam(model.parameters(), lr=float(args['--lr']))
166
# optimizer = torch.optim.Adam(model.parameters(), lr=5e-5) # EDIT: SMALLER LEARNING RATE
167
168
num_trial = 0
169
train_iter = patience = cum_loss = report_loss = cum_tgt_words = report_tgt_words = 0
170
cum_examples = report_examples = epoch = valid_num = 0
171
hist_valid_scores = []
172
train_time = begin_time = time.time()
173
print('begin Maximum Likelihood training')
174
175
while True:
176
epoch += 1
177
178
for src_sents, tgt_sents in batch_iter(train_data, batch_size=train_batch_size, shuffle=True):
179
train_iter += 1
180
181
optimizer.zero_grad()
182
183
batch_size = len(src_sents)
184
185
example_losses = -model(src_sents, tgt_sents) # (batch_size,)
186
batch_loss = example_losses.sum()
187
loss = batch_loss / batch_size
188
189
loss.backward()
190
191
# clip gradient
192
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), clip_grad)
193
194
optimizer.step()
195
196
batch_losses_val = batch_loss.item()
197
report_loss += batch_losses_val
198
cum_loss += batch_losses_val
199
200
tgt_words_num_to_predict = sum(len(s[1:]) for s in tgt_sents) # omitting leading `<s>`
201
report_tgt_words += tgt_words_num_to_predict
202
cum_tgt_words += tgt_words_num_to_predict
203
report_examples += batch_size
204
cum_examples += batch_size
205
206
if train_iter % log_every == 0:
207
writer.add_scalar("loss/train", report_loss / report_examples, train_iter)
208
writer.add_scalar("perplexity/train", math.exp(report_loss / report_tgt_words), train_iter)
209
print('epoch %d, iter %d, avg. loss %.2f, avg. ppl %.2f ' \
210
'cum. examples %d, speed %.2f words/sec, time elapsed %.2f sec' % (epoch, train_iter,
211
report_loss / report_examples,
212
math.exp(report_loss / report_tgt_words),
213
cum_examples,
214
report_tgt_words / (time.time() - train_time),
215
time.time() - begin_time), file=sys.stderr)
216
217
train_time = time.time()
218
report_loss = report_tgt_words = report_examples = 0.
219
220
# perform validation
221
if train_iter % valid_niter == 0:
222
writer.add_scalar("loss/val", cum_loss / cum_examples, train_iter)
223
print('epoch %d, iter %d, cum. loss %.2f, cum. ppl %.2f cum. examples %d' % (epoch, train_iter,
224
cum_loss / cum_examples,
225
np.exp(cum_loss / cum_tgt_words),
226
cum_examples), file=sys.stderr)
227
228
cum_loss = cum_examples = cum_tgt_words = 0.
229
valid_num += 1
230
231
print('begin validation ...', file=sys.stderr)
232
233
# compute dev. ppl and bleu
234
dev_ppl = evaluate_ppl(model, dev_data, batch_size=128) # dev batch size can be a bit larger
235
valid_metric = -dev_ppl
236
237
writer.add_scalar("perplexity/val", dev_ppl, train_iter)
238
print('validation: iter %d, dev. ppl %f' % (train_iter, dev_ppl), file=sys.stderr)
239
240
is_better = len(hist_valid_scores) == 0 or valid_metric > max(hist_valid_scores)
241
hist_valid_scores.append(valid_metric)
242
243
if is_better:
244
patience = 0
245
print('save currently the best model to [%s]' % model_save_path, file=sys.stderr)
246
model.save(model_save_path)
247
248
# also save the optimizers' state
249
torch.save(optimizer.state_dict(), model_save_path + '.optim')
250
elif patience < int(args['--patience']):
251
patience += 1
252
print('hit patience %d' % patience, file=sys.stderr)
253
254
if patience == int(args['--patience']):
255
num_trial += 1
256
print('hit #%d trial' % num_trial, file=sys.stderr)
257
if num_trial == int(args['--max-num-trial']):
258
print('early stop!', file=sys.stderr)
259
exit(0)
260
261
# decay lr, and restore from previously best checkpoint
262
lr = optimizer.param_groups[0]['lr'] * float(args['--lr-decay'])
263
print('load previously best model and decay learning rate to %f' % lr, file=sys.stderr)
264
265
# load model
266
params = torch.load(model_save_path, map_location=lambda storage, loc: storage)
267
model.load_state_dict(params['state_dict'])
268
model = model.to(device)
269
270
print('restore parameters of the optimizers', file=sys.stderr)
271
optimizer.load_state_dict(torch.load(model_save_path + '.optim'))
272
273
# set new lr
274
for param_group in optimizer.param_groups:
275
param_group['lr'] = lr
276
277
# reset patience
278
patience = 0
279
280
if epoch == int(args['--max-epoch']):
281
print('reached maximum number of epochs!', file=sys.stderr)
282
exit(0)
283
284
285
def decode(args: Dict[str, str]):
286
""" Performs decoding on a test set, and save the best-scoring decoding results.
287
If the target gold-standard sentences are given, the function also computes
288
corpus-level BLEU score.
289
@param args (Dict): args from cmd line
290
"""
291
292
print("load test source sentences from [{}]".format(args['TEST_SOURCE_FILE']), file=sys.stderr)
293
test_data_src = read_corpus(args['TEST_SOURCE_FILE'], source='src', vocab_size=3000)
294
if args['TEST_TARGET_FILE']:
295
print("load test target sentences from [{}]".format(args['TEST_TARGET_FILE']), file=sys.stderr)
296
test_data_tgt = read_corpus(args['TEST_TARGET_FILE'], source='tgt', vocab_size=2000)
297
298
print("load model from {}".format(args['MODEL_PATH']), file=sys.stderr)
299
model = NMT.load(args['MODEL_PATH'])
300
301
if args['--cuda']:
302
model = model.to(torch.device("cuda:0"))
303
304
hypotheses = beam_search(model, test_data_src,
305
# beam_size=int(args['--beam-size']), EDIT: BEAM SIZE USED TO BE 5
306
beam_size=10,
307
max_decoding_time_step=int(args['--max-decoding-time-step']))
308
309
if args['TEST_TARGET_FILE']:
310
top_hypotheses = [hyps[0] for hyps in hypotheses]
311
bleu_score = compute_corpus_level_bleu_score(test_data_tgt, top_hypotheses)
312
print('Corpus BLEU: {}'.format(bleu_score), file=sys.stderr)
313
314
with open(args['OUTPUT_FILE'], 'w') as f:
315
for src_sent, hyps in zip(test_data_src, hypotheses):
316
top_hyp = hyps[0]
317
hyp_sent = ''.join(top_hyp.value).replace('▁', ' ')
318
f.write(hyp_sent + '\n')
319
320
321
def beam_search(model: NMT, test_data_src: List[List[str]], beam_size: int, max_decoding_time_step: int) -> List[List[Hypothesis]]:
322
""" Run beam search to construct hypotheses for a list of src-language sentences.
323
@param model (NMT): NMT Model
324
@param test_data_src (List[List[str]]): List of sentences (words) in source language, from test set.
325
@param beam_size (int): beam_size (# of hypotheses to hold for a translation at every step)
326
@param max_decoding_time_step (int): maximum sentence length that Beam search can produce
327
@returns hypotheses (List[List[Hypothesis]]): List of Hypothesis translations for every source sentence.
328
"""
329
was_training = model.training
330
model.eval()
331
332
hypotheses = []
333
with torch.no_grad():
334
for src_sent in tqdm(test_data_src, desc='Decoding', file=sys.stdout):
335
example_hyps = model.beam_search(src_sent, beam_size=beam_size, max_decoding_time_step=max_decoding_time_step)
336
337
hypotheses.append(example_hyps)
338
339
if was_training: model.train(was_training)
340
341
return hypotheses
342
343
344
def main():
345
""" Main func.
346
"""
347
args = docopt(__doc__)
348
349
# Check pytorch version
350
assert(torch.__version__ >= "1.0.0"), "Please update your installation of PyTorch. You have {} and you should have version 1.0.0".format(torch.__version__)
351
352
# seed the random number generators
353
seed = int(args['--seed'])
354
torch.manual_seed(seed)
355
if args['--cuda']:
356
torch.cuda.manual_seed(seed)
357
np.random.seed(seed * 13 // 7)
358
359
if args['train']:
360
train(args)
361
elif args['decode']:
362
decode(args)
363
else:
364
raise RuntimeError('invalid run mode')
365
366
367
if __name__ == '__main__':
368
main()
369
370