-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
288 lines (225 loc) · 9.85 KB
/
trainer.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
from sklearn.metrics import accuracy_score
from tqdm import tqdm
from sklearn import metrics
import wandb
from utils import *
def run(args, tokenizer, train_data, valid_data, cv_count):
train_loader, valid_loader = get_loaders(args, train_data, valid_data)
# only when using warmup scheduler
args.total_steps = int(len(train_loader.dataset) / args.batch_size) * args.n_epochs
args.warmup_steps = int(args.total_steps * args.warmup_ratio)
model = get_model(args)
optimizer = get_optimizer(model, args)
scheduler = get_scheduler(optimizer, args)
best_acc = -1
early_stopping_counter = 0
for epoch in range(args.n_epochs):
print(f"Start Training: Epoch {epoch + 1}")
if not args.cv_strategy:
model_name = args.run_name
else:
model_name = f"{args.run_name.split('.pt')[0]}_{cv_count}.pt"
# TRAIN
train_acc, train_loss = train(args, model, tokenizer, train_loader, optimizer)
# VALID
acc, val_loss = validate(args, model, tokenizer, valid_loader)
# TODO: model save or early stopping
if args.scheduler == 'plateau':
last_lr = optimizer.param_groups[0]['lr']
else:
last_lr = scheduler.get_last_lr()[0]
wandb.log({"epoch": epoch + 1, "train_loss": train_loss, "train_acc": train_acc,
"valid_acc": acc, "val_loss": val_loss, "learning_rate": last_lr})
if acc > best_acc:
best_acc = acc
# torch.nn.DataParallel로 감싸진 경우 원래의 model을 가져옵니다.
model_to_save = model.module if hasattr(model, 'module') else model
save_checkpoint({
'epoch': epoch + 1,
'state_dict': model_to_save.state_dict(),
},
args.model_dir, model_name,
)
early_stopping_counter = 0
else:
early_stopping_counter += 1
if early_stopping_counter >= args.patience:
print(f'EarlyStopping counter: {early_stopping_counter} out of {args.patience}')
break
# scheduler
if args.scheduler == 'plateau':
scheduler.step(best_acc)
else:
scheduler.step()
return best_acc
def train(args, model, tokenizer, train_loader, optimizer):
model.train()
total_preds = []
total_targets = []
losses = []
for step, batch in tqdm(enumerate(train_loader), desc='Training', total=len(train_loader)):
idx, text, label = batch
label = label.to(args.device)
# text = ["{} [SEP] {}".format(a_, b_) for a_, b_ in zip(text, summary)]
tokenized_examples = tokenizer(
text,
max_length=args.max_seq_len,
padding="max_length",
return_tensors="pt"
).to(args.device)
# tokenize
# 모델의 입력으로
# label은 one-hot?
# loss 주고
# argmax를 golden
logits = model(**tokenized_examples)['logits']
if args.classifier == "CNN" and len(list(logits.shape)) == 1:
logits = torch.unsqueeze(logits, 0)
# print(preds)
# logits = preds['logits']
# logits = logits[:,0,:]
# softmax_logits = nn.Softmax(dim=1)(logits)
argmax_logits = torch.argmax(logits, dim=1)
# one_hot_logits = one_hot(argmax_logits, num_classes=7).float()
# print(one_hot(argmax_logits, num_classes=7).type(torch.FloatTensor))
loss = compute_loss(logits,
label, args)
# print(loss)
update_params(loss, model, optimizer, step, len(train_loader), args)
if step % args.log_steps == 0:
print(f"Training steps: {step} Loss: {str(loss.item())}")
wandb.log({"steps": step, "train_loss": loss.item()})
if args.device == 'cuda':
argmax_logits = argmax_logits.to('cpu').detach().numpy()
label = label.to('cpu').detach().numpy()
loss = loss.to('cpu').detach().numpy()
else: # cpu
argmax_logits = argmax_logits.detach().numpy()
label = label.detach().numpy()
loss = loss.detach().numpy()
total_preds.append(argmax_logits)
total_targets.append(label)
losses.append(loss)
total_preds = np.concatenate(total_preds)
total_targets = np.concatenate(total_targets)
# Train AUC / ACC
acc = accuracy_score(total_targets, total_preds)
loss_avg = sum(losses) / len(losses)
print(f'TRAIN ACC : {acc}, TRAIN LOSS : {loss_avg}')
return acc, loss_avg
def validate(args, model, tokenizer, valid_loader):
model.eval()
total_preds = []
total_targets = []
losses = []
for step, batch in tqdm(enumerate(valid_loader), desc='Validation', total=len(valid_loader)):
idx, text, label = batch
# text = ["{} [SEP] {}".format(a_, b_) for a_, b_ in zip(text, summary)]
label = label.to(args.device)
tokenized_examples = tokenizer(
text,
max_length=args.max_seq_len,
padding="max_length",
return_tensors="pt"
).to(args.device)
# tokenize
# 모델의 입력으로
# label은 one-hot?
# loss 주고
# argmax를 golden
logits = model(**tokenized_examples)['logits']
if args.classifier == "CNN" and len(list(logits.shape)) == 1:
logits = torch.unsqueeze(logits, 0)
# softmax_logits = nn.Softmax(dim=1)(logits)
argmax_logits = torch.argmax(logits, dim=1)
# one_hot_logits = one_hot(argmax_logits, num_classes=7).float()
# print(one_hot(argmax_logits, num_classes=7).type(torch.FloatTensor))
loss = compute_loss(logits,
label, args)
if step % args.log_steps == 0:
print(f"Validation steps: {step} Loss: {str(loss.item())}")
if args.device == 'cuda':
argmax_logits = argmax_logits.to('cpu').detach().numpy()
label = label.to('cpu').detach().numpy()
loss = loss.to('cpu').detach().numpy()
else: # cpu
argmax_logits = argmax_logits.detach().numpy()
label = label.detach().numpy()
loss = loss.detach().numpy()
total_preds.append(argmax_logits)
total_targets.append(label)
losses.append(loss)
total_preds = np.concatenate(total_preds)
total_targets = np.concatenate(total_targets)
# Train AUC / ACC
target_names = ['IT과학', '경제', '사회', '생활문화', '세계', '스포츠', '정치']
print(metrics.classification_report(total_targets, total_preds, target_names=target_names))
matrix = metrics.confusion_matrix(total_targets, total_preds)
print(matrix.diagonal() / matrix.sum(axis=1))
# Train AUC / ACC
acc = accuracy_score(total_targets, total_preds)
loss_avg = sum(losses) / len(losses)
print(f'VALID ACC : {acc}, VALID LOSS : {loss_avg}')
return acc, loss_avg
def inference(args, test_data):
# ckpt_file_names = []
all_fold_preds = []
all_fold_argmax_preds = []
if not args.cv_strategy:
ckpt_file_names = [args.model_name]
else:
ckpt_file_names = [f"{args.model_name.split('.pt')[0]}_{i + 1}.pt" for i in range(args.fold_num)]
tokenizer = load_tokenizer(args)
for fold_idx, ckpt in enumerate(ckpt_file_names):
model = load_model(args, ckpt)
model.eval()
test_loader = get_loaders(args, None, test_data, True)
total_preds = []
total_argmax_preds = []
total_ids = []
for step, batch in tqdm(enumerate(test_loader), desc='Inferencing', total=len(test_loader)):
idx, text = batch
# text = ["{} [SEP] {}".format(a_, b_) for a_, b_ in zip(text, summary)]
tokenized_examples = tokenizer(
text,
max_length=args.max_seq_len,
padding="max_length",
return_tensors="pt"
).to(args.device)
# preds = model(**tokenized_examples)
logits = model(**tokenized_examples)['logits']
if args.classifier == "CNN" and len(list(logits.shape)) == 1:
logits = torch.unsqueeze(logits, 0)
argmax_logits = torch.argmax(logits, dim=1)
if args.device == 'cuda':
argmax_preds = argmax_logits.to('cpu').detach().numpy()
preds = logits.to('cpu').detach().numpy()
else: # cpu
argmax_preds = argmax_logits.detach().numpy()
preds = logits.detach().numpy()
total_preds += list(preds)
total_argmax_preds += list(argmax_preds)
total_ids += list(idx)
all_fold_preds.append(total_preds)
all_fold_argmax_preds.append(total_argmax_preds)
output_file_name = "output.csv" if not args.cv_strategy else f"output_{fold_idx + 1}.csv"
write_path = os.path.join(args.output_dir, output_file_name)
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
with open(write_path, 'w', encoding='utf8') as w:
print("writing prediction : {}".format(write_path))
w.write("index,topic_idx\n")
for index, p in zip(total_ids, total_argmax_preds):
w.write('{},{}\n'.format(index, p))
if len(all_fold_preds) > 1:
# Soft voting ensemble
votes = np.sum(all_fold_preds, axis=0)
votes = np.argmax(votes, axis=1)
write_path = os.path.join(args.output_dir, "output_softvote.csv")
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
with open(write_path, 'w', encoding='utf8') as w:
print("writing prediction : {}".format(write_path))
w.write("index,topic_idx\n")
for id, p in zip(total_ids, votes):
w.write('{},{}\n'.format(id, p))