-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_nat.py
200 lines (164 loc) · 7.69 KB
/
train_nat.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
import argparse
import logging
import os
from tqdm import tqdm
import math
import pytorch_lightning as pl
import torch
from pytorch_lightning import loggers as pl_loggers
from transformers.optimization import AdamW, get_cosine_schedule_with_warmup
from datamodule import KMAModule
from nat_base import NATransformer
from mytokenizer import MyTokenizer
parser = argparse.ArgumentParser(description='KoBART Summarization')
parser.add_argument('--resume_from_checkpoint ',
type=str,
help='resume')
parser.add_argument('--checkpoint_path',
type=str,
help='checkpoint path')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class ArgsBase():
@staticmethod
def add_model_specific_args(parent_parser):
parser = argparse.ArgumentParser(
parents=[parent_parser], add_help=False)
parser.add_argument('--train_file',
type=str,
default='data/train',
help='train file')
parser.add_argument('--valid_file',
type=str,
default='data/valid',
help='valid file')
parser.add_argument('--batch_size',
type=int,
default=32,
help='')
return parser
class Base(pl.LightningModule):
def __init__(self, args, **kwargs) -> None:
super(Base, self).__init__()
self.save_hyperparameters(args)
self.args = args
@staticmethod
def add_model_specific_args(parent_parser):
# add model specific args
parser = argparse.ArgumentParser(
parents=[parent_parser], add_help=False)
parser.add_argument('--batch-size',
type=int,
default=32,
help='batch size for training (default: 96)')
parser.add_argument('--lr',
type=float,
default=5e-4,
help='The initial learning rate')
parser.add_argument('--warmup_ratio',
type=float,
default=0.05,
help='warmup ratio')
parser.add_argument('--model_path',
type=str,
default=None,
help='kobart model path')
parser.add_argument('--n_heads', type=int, default=8)
parser.add_argument('--n_layers', type=int, default=6)
parser.add_argument('--d_model', type=int, default=512)
parser.add_argument('--feedforward', type=int, default=2048)
parser.add_argument('--dropout', type=int, default=0.1)
parser.add_argument("--max_len", type=int, default=256, help="Maximum length of the output utterances")
return parser
def configure_optimizers(self):
# Prepare optimizer
param_optimizer = list(self.model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(
nd in n for nd in no_decay)], 'weight_decay': 0.01},
{'params': [p for n, p in param_optimizer if any(
nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters,
lr=self.hparams.lr, correct_bias=False)
num_workers = self.hparams.num_workers
data_len = len(self.train_dataloader().dataset)
logging.info(f'number of workers {num_workers}, data length {data_len}')
num_train_steps = int(data_len / (self.hparams.batch_size) * self.hparams.max_epochs)
logging.info(f'num_train_steps : {num_train_steps}')
num_warmup_steps = int(num_train_steps * self.hparams.warmup_ratio)
logging.info(f'num_warmup_steps : {num_warmup_steps}')
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=num_warmup_steps, num_training_steps=num_train_steps)
lr_scheduler = {'scheduler': scheduler,
'monitor': 'loss', 'interval': 'step',
'frequency': 1}
return [optimizer], [lr_scheduler]
class Model(Base):
def __init__(self, args, **kwargs):
super(Model, self).__init__(args, **kwargs)
src_tok = MyTokenizer()
src_tok.read_vocab(args.train_file + '_src_vocab.txt')
self.src_tok = src_tok
morph_tok = MyTokenizer()
morph_tok.read_vocab(args.train_file + '_morph_vocab.txt')
self.morph_tok = morph_tok
tag_tok = MyTokenizer()
tag_tok.read_vocab(args.train_file +'_tag_vocab.txt')
self.tag_tok = tag_tok
self.pad_token_id = src_tok.index("<pad>")
self.model = NATransformer(args, self.src_tok, self.morph_tok, self.tag_tok)
def forward(self, inputs):
return self.model(inputs['input_ids'],
inputs['attention_mask'],
inputs['morph_input_ids'],
inputs['tag_input_ids'],
inputs['dec_attention_mask'],
inputs['morph_labels'],
inputs['tag_labels'],
inputs['len_labels'])
def training_step(self, batch, batch_idx):
outs = self(batch)
loss = outs[-1]
self.log('train_loss', loss, prog_bar=True, on_step=True, on_epoch=True)
return loss
def validation_step(self, batch, batch_idx):
outs = self(batch)
loss = outs[-1]
return (loss)
def validation_epoch_end(self, outputs):
losses = []
for loss in outputs:
losses.append(loss)
val_loss_mean = torch.stack(losses).mean()
self.log('val_loss', val_loss_mean, prog_bar=True)
if __name__ == '__main__':
parser = Base.add_model_specific_args(parser)
parser = ArgsBase.add_model_specific_args(parser)
parser = KMAModule.add_model_specific_args(parser)
parser = pl.Trainer.add_argparse_args(parser)
args = parser.parse_args()
logging.info(args)
model = Model(args)
dm = KMAModule(args.train_file,
args.valid_file,
model.src_tok, model.morph_tok, model.tag_tok,
args.max_len,
batch_size=args.batch_size,
num_workers=args.num_workers)
###
#early_stop_callback = pl.callbacks.EarlyStopping(monitor="val_loss", patience=200, mode="min")
##
checkpoint_callback = pl.callbacks.ModelCheckpoint(monitor=None,
dirpath=args.default_root_dir,
filename='version_4/{epoch:02d}-{val_loss:.3f}',
verbose=True,
save_last=True,
mode='min')
tb_logger = pl_loggers.TensorBoardLogger(os.path.join(args.default_root_dir, 'tb_logs'))
lr_logger = pl.callbacks.LearningRateMonitor()
trainer = pl.Trainer.from_argparse_args(args, gpus=args.gpus, accelerator="dp", logger=tb_logger,
callbacks=[checkpoint_callback, lr_logger], gradient_clip_val=5)
trainer.fit(model, dm)