forked from kh-kim/simple-nmt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
executable file
·361 lines (316 loc) · 10.6 KB
/
train.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
import argparse
import pprint
import torch
from torch import optim
import torch.nn as nn
import torch_optimizer as custom_optim
from simple_nmt.data_loader import DataLoader
import simple_nmt.data_loader as data_loader
from simple_nmt.models.seq2seq import Seq2Seq
from simple_nmt.models.transformer import Transformer
from simple_nmt.models.rnnlm import LanguageModel
from simple_nmt.trainer import SingleTrainer
from simple_nmt.rl_trainer import MinimumRiskTrainingEngine
from simple_nmt.trainer import MaximumLikelihoodEstimationEngine
def define_argparser(is_continue=False):
p = argparse.ArgumentParser()
if is_continue:
p.add_argument(
'--load_fn',
required=True,
help='Model file name to continue.'
)
p.add_argument(
'--model_fn',
required=not is_continue,
help='Model file name to save. Additional information would be annotated to the file name.'
)
p.add_argument(
'--train',
required=not is_continue,
help='Training set file name except the extention. (ex: train.en --> train)'
)
p.add_argument(
'--valid',
required=not is_continue,
help='Validation set file name except the extention. (ex: valid.en --> valid)'
)
p.add_argument(
'--lang',
required=not is_continue,
help='Set of extention represents language pair. (ex: en + ko --> enko)'
)
p.add_argument(
'--gpu_id',
type=int,
default=-1,
help='GPU ID to train. Currently, GPU parallel is not supported. -1 for CPU. Default=%(default)s'
)
p.add_argument(
'--off_autocast',
action='store_true',
help='Turn-off Automatic Mixed Precision (AMP), which speed-up training.',
)
p.add_argument(
'--batch_size',
type=int,
default=32,
help='Mini batch size for gradient descent. Default=%(default)s'
)
p.add_argument(
'--n_epochs',
type=int,
default=20,
help='Number of epochs to train. Default=%(default)s'
)
p.add_argument(
'--verbose',
type=int,
default=2,
help='VERBOSE_SILENT, VERBOSE_EPOCH_WISE, VERBOSE_BATCH_WISE = 0, 1, 2. Default=%(default)s'
)
p.add_argument(
'--init_epoch',
required=is_continue,
type=int,
default=1,
help='Set initial epoch number, which can be useful in continue training. Default=%(default)s'
)
p.add_argument(
'--max_length',
type=int,
default=100,
help='Maximum length of the training sequence. Default=%(default)s'
)
p.add_argument(
'--dropout',
type=float,
default=.2,
help='Dropout rate. Default=%(default)s'
)
p.add_argument(
'--word_vec_size',
type=int,
default=512,
help='Word embedding vector dimension. Default=%(default)s'
)
p.add_argument(
'--hidden_size',
type=int,
default=768,
help='Hidden size of LSTM. Default=%(default)s'
)
p.add_argument(
'--n_layers',
type=int,
default=4,
help='Number of layers in LSTM. Default=%(default)s'
)
p.add_argument(
'--max_grad_norm',
type=float,
default=5.,
help='Threshold for gradient clipping. Default=%(default)s'
)
p.add_argument(
'--iteration_per_update',
type=int,
default=1,
help='Number of feed-forward iterations for one parameter update. Default=%(default)s'
)
p.add_argument(
'--lr',
type=float,
default=1.,
help='Initial learning rate. Default=%(default)s',
)
p.add_argument(
'--lr_step',
type=int,
default=1,
help='Number of epochs for each learning rate decay. Default=%(default)s',
)
p.add_argument(
'--lr_gamma',
type=float,
default=.5,
help='Learning rate decay rate. Default=%(default)s',
)
p.add_argument(
'--lr_decay_start',
type=int,
default=10,
help='Learning rate decay start at. Default=%(default)s',
)
p.add_argument(
'--use_adam',
action='store_true',
help='Use Adam as optimizer instead of SGD. Other lr arguments should be changed.',
)
p.add_argument(
'--use_radam',
action='store_true',
help='Use rectified Adam as optimizer. Other lr arguments should be changed.',
)
p.add_argument(
'--rl_lr',
type=float,
default=.01,
help='Learning rate for reinforcement learning. Default=%(default)s'
)
p.add_argument(
'--rl_n_samples',
type=int,
default=1,
help='Number of samples to get baseline. Default=%(default)s'
)
p.add_argument(
'--rl_n_epochs',
type=int,
default=10,
help='Number of epochs for reinforcement learning. Default=%(default)s'
)
p.add_argument(
'--rl_n_gram',
type=int,
default=6,
help='Maximum number of tokens to calculate BLEU for reinforcement learning. Default=%(default)s'
)
p.add_argument(
'--rl_reward',
type=str,
default='gleu',
help='Method name to use as reward function for RL training. Default=%(default)s'
)
p.add_argument(
'--use_transformer',
action='store_true',
help='Set model architecture as Transformer.',
)
p.add_argument(
'--n_splits',
type=int,
default=8,
help='Number of heads in multi-head attention in Transformer. Default=%(default)s',
)
config = p.parse_args()
return config
def get_model(input_size, output_size, config):
if config.use_transformer:
model = Transformer(
input_size, # Source vocabulary size
config.hidden_size, # Transformer doesn't need word_vec_size.
output_size, # Target vocabulary size
n_splits=config.n_splits, # Number of head in Multi-head Attention.
n_enc_blocks=config.n_layers, # Number of encoder blocks
n_dec_blocks=config.n_layers, # Number of decoder blocks
dropout_p=config.dropout, # Dropout rate on each block
)
else:
model = Seq2Seq(
input_size,
config.word_vec_size, # Word embedding vector size
config.hidden_size, # LSTM's hidden vector size
output_size,
n_layers=config.n_layers, # number of layers in LSTM
dropout_p=config.dropout # dropout-rate in LSTM
)
return model
def get_crit(output_size, pad_index):
# Default weight for loss equals to 1, but we don't need to get loss for PAD token.
# Thus, set a weight for PAD to zero.
loss_weight = torch.ones(output_size)
loss_weight[pad_index] = 0.
# Instead of using Cross-Entropy loss,
# we can use Negative Log-Likelihood(NLL) loss with log-probability.
crit = nn.NLLLoss(
weight=loss_weight,
reduction='sum'
)
return crit
def get_optimizer(model, config):
if config.use_adam:
if config.use_transformer:
optimizer = optim.Adam(model.parameters(), lr=config.lr, betas=(.9, .98))
else: # case of rnn based seq2seq.
optimizer = optim.Adam(model.parameters(), lr=config.lr)
elif config.use_radam:
optimizer = custom_optim.RAdam(model.parameters(), lr=config.lr)
else:
optimizer = optim.SGD(model.parameters(), lr=config.lr)
return optimizer
def get_scheduler(optimizer, config):
if config.lr_step > 0:
lr_scheduler = optim.lr_scheduler.MultiStepLR(
optimizer,
milestones=[i for i in range(
max(0, config.lr_decay_start - 1),
(config.init_epoch - 1) + config.n_epochs,
config.lr_step
)],
gamma=config.lr_gamma,
last_epoch=config.init_epoch - 1 if config.init_epoch > 1 else -1,
)
else:
lr_scheduler = None
return lr_scheduler
def main(config, model_weight=None, opt_weight=None):
def print_config(config):
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(vars(config))
print_config(config)
loader = DataLoader(
config.train, # Train file name except extention, which is language.
config.valid, # Validation file name except extension.
(config.lang[:2], config.lang[-2:]), # Source and target language.
batch_size=config.batch_size,
device=-1, # Lazy loading
max_length=config.max_length, # Loger sequence will be excluded.
dsl=False, # Turn-off Dual-supervised Learning mode.
)
input_size, output_size = len(loader.src.vocab), len(loader.tgt.vocab)
model = get_model(input_size, output_size, config)
crit = get_crit(output_size, data_loader.PAD)
if model_weight is not None:
model.load_state_dict(model_weight)
# Pass models to GPU device if it is necessary.
if config.gpu_id >= 0:
model.cuda(config.gpu_id)
crit.cuda(config.gpu_id)
optimizer = get_optimizer(model, config)
if opt_weight is not None and (config.use_adam or config.use_radam):
optimizer.load_state_dict(opt_weight)
lr_scheduler = get_scheduler(optimizer, config)
if config.verbose >= 2:
print(model)
print(crit)
print(optimizer)
# Start training. This function maybe equivalant to 'fit' function in Keras.
mle_trainer = SingleTrainer(MaximumLikelihoodEstimationEngine, config)
mle_trainer.train(
model,
crit,
optimizer,
train_loader=loader.train_iter,
valid_loader=loader.valid_iter,
src_vocab=loader.src.vocab,
tgt_vocab=loader.tgt.vocab,
n_epochs=config.n_epochs,
lr_scheduler=lr_scheduler,
)
if config.rl_n_epochs > 0:
optimizer = optim.SGD(model.parameters(), lr=config.rl_lr)
mrt_trainer = SingleTrainer(MinimumRiskTrainingEngine, config)
mrt_trainer.train(
model,
None, # We don't need criterion for MRT.
optimizer,
train_loader=loader.train_iter,
valid_loader=loader.valid_iter,
src_vocab=loader.src.vocab,
tgt_vocab=loader.tgt.vocab,
n_epochs=config.rl_n_epochs,
)
if __name__ == '__main__':
config = define_argparser()
main(config)