-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfinetune_trainer.py
174 lines (140 loc) · 6.44 KB
/
finetune_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
# This file is a modification of MIDI-BERT/MidiBERT/CP/finetune_trainer.py
# from https://github.com/wazenmai/MIDI-BERT.git
# Fixed a bug on line 92 and adjusted some things so that it can fine-tune on GLUE tasks
import shutil
import numpy as np
from collections import Counter
import tqdm
import torch
import torch.nn as nn
from transformers import AdamW
from torch.nn.utils import clip_grad_norm_
from datasets import load_dataset, load_metric
from finetune_model import TokenClassification, SequenceClassification
class FinetuneTrainer:
def __init__(self, midibert, train_dataloader, valid_dataloader, test_dataloader, layer,
lr, class_num, task, hs, testset_shape, cpu, cuda_devices=None, model=None, SeqClass=False, max_seq_len=512):
self.device = torch.device("cuda" if torch.cuda.is_available() and not cpu else 'cpu')
print(' device:',self.device)
self.midibert = midibert
self.SeqClass = SeqClass
self.layer = layer
self.max_seq_len = max_seq_len
self.task = task
if model != None: # load model
print('load a fine-tuned model')
self.model = model.to(self.device)
else:
print('init a fine-tune model, sequence-level task?', SeqClass)
if SeqClass:
self.model = SequenceClassification(self.midibert, class_num, hs).to(self.device)
else:
self.model = TokenClassification(self.midibert, class_num, hs).to(self.device)
# for name, param in self.model.named_parameters():
# if 'midibert.bert' in name:
# param.requires_grad = False
# print(name, param.requires_grad)
if torch.cuda.device_count() > 1 and not cpu:
print("Use %d GPUS" % torch.cuda.device_count())
self.model = nn.DataParallel(self.model, device_ids=cuda_devices)
self.train_data = train_dataloader
self.valid_data = valid_dataloader
self.test_data = test_dataloader
self.optim = AdamW(self.model.parameters(), lr=lr, weight_decay=0.01)
self.loss_func = nn.CrossEntropyLoss(reduction='none')
self.testset_shape = testset_shape
def compute_loss(self, predict, target, loss_mask, seq):
loss = self.loss_func(predict, target)
if not seq:
loss = loss * loss_mask
loss = torch.sum(loss) / torch.sum(loss_mask)
else:
loss = torch.sum(loss)/loss.shape[0]
return loss
def train(self):
self.model.train()
train_loss, train_acc = self.iteration(self.train_data, 0, self.SeqClass)
return train_loss, train_acc
def valid(self):
self.model.eval()
valid_loss, valid_acc = self.iteration(self.valid_data, 1, self.SeqClass)
return valid_loss, valid_acc
def test(self):
self.model.eval()
test_loss, test_acc, all_output = self.iteration(self.test_data, 2, self.SeqClass)
return test_loss, test_acc, all_output
def iteration(self, training_data, mode, seq):
pbar = tqdm.tqdm(training_data, disable=False)
total_acc, total_cnt, total_loss, step_loss = 0, 0, 0, 0
count = 0
metric = load_metric("accuracy") if (self.task == "cola") else load_metric("glue", self.task)
total_metric = metric.compute(predictions=[0,1], references=[1,0])
for key in total_metric:
total_metric[key] = 0
#print (total_metric)
if mode == 2: # testing
all_output = torch.empty(self.testset_shape)
cnt = 0
for x, y in pbar: # (batch, 512, 768)
count+=1
batch = x.shape[0]
x, y = x.to(self.device), y.to(self.device) # seq: (batch, 512, 4), (batch) / token: , (batch, 512)
# avoid attend to pad word
if not seq:
attn = (y != 0).float().to(self.device) # (batch,512)
else:
attn = torch.ones((batch, self.max_seq_len)).to(self.device) # attend each of them
y_hat = self.model.forward(x, attn, self.layer) # seq: (batch, class_num) / token: (batch, 512, class_num)
# get the most likely choice with max
output = np.argmax(y_hat.cpu().detach().numpy(), axis=-1)
output = torch.from_numpy(output).to(self.device)
if mode == 2:
all_output[cnt : cnt+batch] = output
cnt += batch
# accuracy
if not seq:
acc = torch.sum((y == output).float() * attn)
total_acc += acc
total_cnt += torch.sum(attn).item()
else:
acc = torch.sum((y == output).float())
total_acc += acc
total_cnt += y.shape[0]
#print (output,y)
#print (metric.compute(predictions=output, references=y))
total_metric = Counter(total_metric) + Counter(metric.compute(predictions=output, references=y))
# calculate losses
if not seq:
y_hat = y_hat.permute(0,2,1)
loss = self.compute_loss(y_hat, y, attn, seq)
total_loss += loss.item()
step_loss += loss.item()
if count % 50 == 0:
print (" step %d: %.4f" % (count,round(step_loss/50,4)))
step_loss = 0
# udpate only in train
if mode == 0:
self.model.zero_grad()
loss.backward()
self.optim.step()
if mode == 2:
return round(total_loss/len(training_data),4), round(total_acc.item()/total_cnt,4), all_output
for key in total_metric:
total_metric[key] = round(total_metric[key]/count,4)
print (total_metric)
return round(total_loss/len(training_data),4), round(total_acc.item()/total_cnt,4)
def save_checkpoint(self, epoch, train_acc, valid_acc,
valid_loss, train_loss, is_best, filename):
state = {
'epoch': epoch + 1,
'state_dict': self.model.state_dict(),
'valid_acc': valid_acc,
'valid_loss': valid_loss,
'train_loss': train_loss,
'train_acc': train_acc,
'optimizer' : self.optim.state_dict()
}
torch.save(state, filename)
best_mdl = filename.split('.')[0]+'_best.ckpt'
if is_best:
shutil.copyfile(filename, best_mdl)