forked from Morizeyao/GPT2-Chinese
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
235 lines (214 loc) · 7.02 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
from transformers import GPT2LMHeadModel, GPT2Config
from transformers import AdamW, get_linear_schedule_with_warmup, BertTokenizer
from torch.utils.data import Dataset, DataLoader
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
import pytorch_lightning as pl
import torch
import json
import argparse
# 11846807
class DS(Dataset):
def __init__(self, lines, vocab_path="vocab/vocab.txt", max_length=1024):
self.data = lines
self.tok = BertTokenizer(vocab_file=vocab_path)
self.max_length = max_length
def __len__(self):
return len(self.data)
def __getitem__(self, index):
line = self.data[index]
line = self.tok.encode_plus(
line,
max_length=self.max_length,
truncation=True,
padding="max_length",
return_tensors="pt",
)
return line
class Net(pl.LightningModule):
def __init__(
self,
batch_size,
epochs,
t_total=100000,
config_path="config/model_config.json",
data_path="data/train.json",
valid_examples=100,
vocab_path="vocab/vocab.txt",
max_length=1024,
warm_up_steps=0,
lr=1e-4,
):
super(Net, self).__init__()
self.batch_size = batch_size
self.epochs = epochs
self.t_total = t_total
self.warm_up_steps = warm_up_steps
self.lr = lr
self.model_name = "bert_pretrained_model"
self.config = GPT2Config.from_json_file(config_path)
self.model = GPT2LMHeadModel(config=self.config)
self.data = [json.loads(line.strip()) for line in open(data_path)]
self.dataset_train = DS(
self.data[:-valid_examples], vocab_path=vocab_path, max_length=max_length
)
self.dataset_valid = DS(
self.data[-valid_examples:], vocab_path=vocab_path, max_length=max_length
)
def forward(self, input_ids, attention_mask):
input_ids = input_ids
attention_mask = attention_mask
r = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=input_ids,
return_dict=True,
)
return r["loss"]
def train_dataloader(self):
return DataLoader(
self.dataset_train,
batch_size=self.batch_size,
num_workers=8,
shuffle=True,
drop_last=True,
)
def val_dataloader(self):
return DataLoader(
self.dataset_valid,
batch_size=self.batch_size,
num_workers=8,
shuffle=True,
drop_last=True,
)
def configure_optimizers(self):
optimizer = AdamW(self.parameters(), lr=self.lr, weight_decay=0.001)
scheduler = get_linear_schedule_with_warmup(
optimizer, self.warm_up_steps, self.t_total
)
scheduler = {"scheduler": scheduler, "interval": "step", "frequency": 1}
return [optimizer], [scheduler]
def training_step(self, batch, batch_nb):
loss = self.forward(batch["input_ids"], batch["attention_mask"])
self.log(
"train_loss",
loss,
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True,
)
return loss
def validation_step(self, batch, batch_nb):
loss = self.forward(batch["input_ids"], batch["attention_mask"])
return loss
def validation_epoch_end(self, outputs):
avg_loss = torch.stack(outputs).mean()
self.log(
"val_loss",
avg_loss,
on_epoch=True,
prog_bar=True,
logger=True,
)
return {"val_loss": avg_loss}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--device", default="0", type=str, required=False, help="设置使用哪些显卡,用逗号分割"
)
parser.add_argument(
"--config_path",
default="config/model_config.json",
type=str,
required=False,
help="选择模型参数",
)
parser.add_argument(
"--vocab_path",
default="vocab/vocab.txt",
type=str,
required=False,
help="选择词库",
)
parser.add_argument(
"--data_path",
default="data/train.json",
type=str,
required=False,
help="原始训练语料",
)
parser.add_argument("--epochs", default=5, type=int, required=False, help="训练循环")
parser.add_argument(
"--batch_size", default=8, type=int, required=False, help="训练batch size"
)
parser.add_argument("--lr", default=1.5e-4, type=float, required=False, help="学习率")
parser.add_argument(
"--warmup_steps", default=2000, type=int, required=False, help="warm up步数"
)
parser.add_argument(
"--max_length", default=1024, type=int, required=False, help="单条文本最长长度"
)
parser.add_argument(
"--eval_interval", default=100, type=int, required=False, help="eval 步数"
)
parser.add_argument(
"--val_examples", default=100, type=int, required=False, help="选择多少验证集样本"
)
parser.add_argument(
"--t_total", default=100000, type=int, required=False, help="计划训练多少步"
)
parser.add_argument(
"--log_step", default=1, type=int, required=False, help="多少步汇报一次loss"
)
parser.add_argument(
"--output_dir", default="model/", type=str, required=False, help="模型输出路径"
)
args = parser.parse_args()
val_examples = args.val_examples
vocab_path = args.vocab_path
max_length = args.max_length
batch_size = args.batch_size
epochs = args.epochs
output_path = args.output_dir
eval_interval = args.eval_interval
lr = args.lr
warmup_steps = args.warmup_steps
data_path = args.data_path
config_path = args.config_path
t_total = args.t_total
checkpoint_callback = ModelCheckpoint(
dirpath=output_path,
verbose=True,
period=1,
save_top_k=1,
monitor="val_loss",
mode="min",
)
learning_rate_callback = LearningRateMonitor()
trainer = pl.Trainer(
default_root_dir=output_path,
gradient_clip_val=1,
max_epochs=epochs,
gpus=args.device,
distributed_backend="dp",
val_check_interval=eval_interval,
callbacks=[learning_rate_callback, checkpoint_callback],
precision=32,
)
net = Net(
batch_size,
epochs,
t_total=t_total,
config_path=config_path,
data_path=data_path,
valid_examples=val_examples,
vocab_path=vocab_path,
max_length=max_length,
warm_up_steps=warmup_steps,
lr=lr,
)
# d = torch.load('output_old/best.ckpt', map_location=torch.device("cpu"))["state_dict"]
# d.pop('model.classifier.bias')
# d.pop('model.classifier.weight')
# net.load_state_dict(d, strict=False)
trainer.fit(net)