-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
158 lines (134 loc) · 4.31 KB
/
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
"""
deepspeed --num_gpus=1 model.py
"""
from argparse import ArgumentParser
import os
import pandas as pd
import numpy as np
import random
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelWithLMHead
from torch.optim import AdamW
import deepspeed
import wandb
############################################# -> 실험결과 FIX
random_seed = 42
torch.manual_seed(random_seed)
torch.cuda.manual_seed(random_seed)
torch.cuda.manual_seed_all(random_seed) # if use multi-GPU
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(random_seed)
random.seed(random_seed)
##################################
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": "[sep]",
}
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=10, 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="kommongen", name=f"kommongen-{model_name}")
train_data = pd.read_csv("data/train_data.csv", delimiter="\t")
train_text, train_labels = (
train_data["concept_set"].values,
train_data["label"].values,
)
dataset = [
{"data": t + str(args.sep_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/val_data.csv", delimiter="\t")
eval_text, eval_labels = (
eval_data["concept_set"].values,
eval_data["label"].values,
)
dataset = [
{"data": t + str(args.sep_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,
)
engine, _, _, _ = deepspeed.initialize(
args=args,
model=model,
model_parameters=model.parameters(),
)
for epoch in range(args.epoch):
model.train()
for train in tqdm(train_loader):
engine.zero_grad()
text, label = train["data"], train["label"]
text_tokens = tokenizer(
text,
return_tensors="pt",
max_length=70,
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
# print({"loss": loss})
wandb.log({"loss": loss})
engine.backward(loss)
engine.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=70,
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,
)
eval_loss = eval_out.loss
# print({"eval_loss": eval_loss})
wandb.log({"eval_loss": eval_loss})
wandb.log({"epoch": epoch + 1})
torch.save(
model.state_dict(),
f"model_save/{model_name.replace('/', '-')}-{epoch+1}.pt",
)