-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGPT-2_fine_tune.py
142 lines (121 loc) · 3.93 KB
/
GPT-2_fine_tune.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
'''
deepspeed --num_gpus=1 GPT-2_fine_tune.py
'''
from argparse import ArgumentParser
import os
import pandas as pd
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelWithLMHead
import deepspeed
from deepspeed.ops.adam import DeepSpeedCPUAdam
import wandb
os.environ["TOKENIZERS_PARALLELISM"] = "true"
model_name = "skt/kogpt2-base-v2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
SPECIAL_TOKENS = {
"bos_token": "<bos>",
"eos_token": "<eos>",
"pad_token": "<pad>",
"sep_token": "<seq>"
}
tokenizer.add_special_tokens(SPECIAL_TOKENS)
model = AutoModelWithLMHead.from_pretrained(
model_name
).cuda()
model.resize_token_embeddings(len(tokenizer))
parser = ArgumentParser()
parser.add_argument("--deepspeed_config", type=str, default="ds_config.json")
parser.add_argument("--local_rank", type=int)
parser.add_argument("--epoch", default=50, type=int)
parser.add_argument("--batch_size", default=128, type=int)
parser.add_argument("--sep_token", default=tokenizer.sep_token, type=str)
parser.add_argument("--bos_token", default=tokenizer.bos_token, type=str)
parser.add_argument("--eos_token", default=tokenizer.eos_token, type=str)
args = parser.parse_args()
wandb.init(project="mobot", name=f"mobot-{model_name}")
train_data = pd.read_csv("data/cafe_clear_data_test.tsv", delimiter="\t")
train_data = train_data[:3000]
train_text, train_labels = (
train_data["text"].values,
train_data["label"].values,
)
dataset = [
{"data": t + str(args.bos_token) + l + str(args.eos_token), "label": l}
for t, l in zip(train_text, train_labels)
]
train_loader = DataLoader(
dataset,
batch_size=args.batch_size,
num_workers=8,
drop_last=True,
pin_memory=True,
)
eval_data = pd.read_csv("data/cafe_clear_data_test.tsv", delimiter="\t")
eval_data = eval_data[3000:]
eval_text, eval_labels = (
eval_data["text"].values,
eval_data["label"].values,
)
dataset = [
{"data": t + str(args.bos_token) + l + str(args.eos_token), "label": l }
for t, l in zip(eval_text, eval_labels)
]
eval_loader = DataLoader(
dataset,
batch_size=args.batch_size,
num_workers=8,
drop_last=True,
pin_memory=True,
)
optimizer = DeepSpeedCPUAdam(
lr=3e-5, weight_decay=3e-7, model_params=model.parameters()
)
engine, optimizer, _, _ = deepspeed.initialize(
args=args, model=model, optimizer=optimizer
)
for epoch in range(args.epoch):
model.train()
for train in tqdm(train_loader):
optimizer.zero_grad()
text, label = train["data"], train["label"]
text_tokens = tokenizer(
text,
return_tensors="pt",
max_length=50,
truncation=True,
padding=True,
)
input_ids = text_tokens.input_ids.cuda()
attention_mask = text_tokens.attention_mask.cuda()
output = engine.forward(
input_ids=input_ids,
attention_mask=attention_mask,
labels=input_ids,
)
loss = output.loss
wandb.log({"loss": loss})
engine.backward(loss)
optimizer.step()
with torch.no_grad():
model.eval()
for eval in tqdm(eval_loader):
eval_text, eval_label = eval["data"], eval["label"]
eval_text_tokens = tokenizer(
eval_text,
return_tensors="pt",
max_length=50,
truncation=True,
padding=True,
)
input_ids = eval_text_tokens.input_ids.cuda()
attention_mask = eval_text_tokens.attention_mask.cuda()
eval_out = engine.forward(
input_ids=input_ids,
attention_mask=attention_mask,
labels=input_ids,
)
wandb.log({"eval_loss": eval_out.loss})
wandb.log({"epoch": epoch+1})
torch.save(model.state_dict(), f"model_save/{model_name.replace('/', '-')}.pt")