-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrun_train_model.py
266 lines (225 loc) · 7.12 KB
/
run_train_model.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
import argparse
import os
import torch
import torch.utils.tensorboard
from tqdm import tqdm
from s2s.dset import DSET_OPTS
from s2s.model import MODEL_OPTS
from s2s.path import EXP_PATH
from s2s.tknzr import TKNZR_OPTS
from s2s.util import load_cfg, save_cfg, set_seed
def parse_arg() -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog='python run_train_model.py',
description='Train sequence-to-sequence model.',
)
subparsers = parser.add_subparsers(dest='model_name')
for model_name, model_cstr in MODEL_OPTS.items():
subparser = subparsers.add_parser(
model_name,
help=f'Train {model_name} sequence-to-sequence model.',
)
subparser.add_argument(
'--batch_size',
help='Training batch size.',
required=True,
type=int,
)
subparser.add_argument(
'--ckpt_step',
help='Checkpoint save interval.',
required=True,
type=int,
)
subparser.add_argument(
'--dec_max_len',
help='Decoder max sequence length.',
required=True,
type=int,
)
subparser.add_argument(
'--dec_tknzr_exp',
help='Experiment name of the decoder paired tokenizer.',
required=True,
type=str,
)
subparser.add_argument(
'--dset_name',
choices=DSET_OPTS.keys(),
help='Name of the dataset to train model.',
required=True,
type=str,
)
subparser.add_argument(
'--enc_max_len',
help='Encoder max sequence length.',
required=True,
type=int,
)
subparser.add_argument(
'--enc_tknzr_exp',
help='Experiment name of the encoder paired tokenizer.',
required=True,
type=str,
)
subparser.add_argument(
'--epoch',
help='Number of training epochs.',
required=True,
type=int,
)
subparser.add_argument(
'--exp_name',
help='Current experiment name.',
required=True,
type=str,
)
subparser.add_argument(
'--log_step',
help='Performance log interval.',
required=True,
type=int,
)
subparser.add_argument(
'--lr',
help='Gradient decent learning rate.',
required=True,
type=float,
)
subparser.add_argument(
'--max_norm',
help='Gradient bound to avoid gradient explosion.',
required=True,
type=float,
)
subparser.add_argument(
'--seed',
help='Control random seed.',
required=True,
type=int,
)
model_cstr.update_subparser(subparser=subparser)
return parser.parse_args()
def main():
r"""Main function."""
# Load command line arguments.
args = parse_arg()
# Control random seed.
set_seed(args.seed)
# Load encoder tokenizer and its configuration.
enc_tknzr_cfg = load_cfg(exp_name=args.enc_tknzr_exp)
enc_tknzr = TKNZR_OPTS[enc_tknzr_cfg.tknzr_name].load(cfg=enc_tknzr_cfg)
# Load decoder tokenizer and its configuration.
dec_tknzr_cfg = load_cfg(exp_name=args.dec_tknzr_exp)
dec_tknzr = TKNZR_OPTS[dec_tknzr_cfg.tknzr_name].load(cfg=dec_tknzr_cfg)
# Load training dataset and create dataloader.
dset = DSET_OPTS[args.dset_name]()
dldr = torch.utils.data.DataLoader(
dataset=dset,
batch_size=args.batch_size,
shuffle=True,
)
# Get model running device.
device = torch.device('cpu')
if torch.cuda.is_available():
device = torch.device('cuda')
# Create model.
model = MODEL_OPTS[args.model_name](
dec_tknzr_cfg=dec_tknzr_cfg,
enc_tknzr_cfg=enc_tknzr_cfg,
model_cfg=args,
)
model.train()
model = model.to(device)
# Create optimizer.
optim = torch.optim.Adam(
params=model.parameters(),
lr=args.lr,
)
# Create objective function.
objtv = torch.nn.CrossEntropyLoss()
# Save model configuration.
save_cfg(cfg=args.__dict__, exp_name=args.exp_name)
# Global step.
step = 0
# Create experiment folder.
exp_path = os.path.join(EXP_PATH, args.exp_name)
if not os.path.exists(exp_path):
os.makedirs(exp_path)
# Create logger and log folder.
writer = torch.utils.tensorboard.SummaryWriter(
os.path.join(EXP_PATH, 'log', args.exp_name)
)
# Log average loss.
total_loss = 0.0
pre_total_loss = 0.0
for cur_epoch in range(args.epoch):
tqdm_dldr = tqdm(
dldr,
desc=f'epoch: {cur_epoch}, loss: {pre_total_loss:.6f}'
)
for batch in tqdm_dldr:
src, src_len = enc_tknzr.batch_enc(
batch_text=batch[0],
max_len=args.enc_max_len,
)
tgt, tgt_len = dec_tknzr.batch_enc(
batch_text=batch[1],
max_len=args.dec_max_len,
)
src = torch.tensor(src).to(device)
src_len = torch.tensor(src_len).to(device)
tgt = torch.tensor(tgt).to(device)
tgt_len = torch.tensor(tgt_len).to(device)
# Forward pass.
logits = model(
src=src,
src_len=src_len,
tgt=tgt[:, :-1],
tgt_len=tgt_len - 1,
)
# Calculate loss.
loss = objtv(
logits.reshape(-1, dec_tknzr_cfg.n_vocab),
tgt[:, 1:].reshape(-1),
)
# Accumulate loss.
total_loss += loss.item() / args.log_step
# Backward pass.
loss.backward()
# Perform gradient clipping.
torch.nn.utils.clip_grad_norm_(
parameters=model.parameters(),
max_norm=args.max_norm,
)
# Gradient descent.
optim.step()
# Clean up gradient.
optim.zero_grad()
# Increment global step.
step += 1
# Save checkpoint for each `ckpt_step`.
if step % args.ckpt_step == 0:
torch.save(
model.state_dict(),
os.path.join(exp_path, f'model-{step}.pt'),
)
if step % args.log_step == 0:
# Log average loss on CLI.
tqdm_dldr.set_description(
f'epoch: {cur_epoch}, loss: {total_loss:.6f}'
)
# Log average loss on tensorboard.
writer.add_scalar('loss', total_loss, step)
# Clean up average loss.
pre_total_loss = total_loss
total_loss = 0.0
# Save last checkpoint.
torch.save(
model.state_dict(),
os.path.join(exp_path, f'model-{step}.pt'),
)
# Close logger.
writer.close()
if __name__ == '__main__':
main()