-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathtraining.py
202 lines (152 loc) · 7.95 KB
/
training.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
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved
Author: Dejiao Zhang ([email protected])
Date: 02/26/2021
"""
import os
import time
import numpy as np
from sklearn import cluster
from utils.logger import statistics_log
from utils.metric import Confusion
from dataloader.dataloader import unshuffle_loader
import torch
import torch.nn as nn
from torch.nn import functional as F
from learner.cluster_utils import target_distribution
from learner.contrastive_utils import PairConLoss
class SCCLvTrainer(nn.Module):
def __init__(self, model, tokenizer, optimizer, train_loader, args):
super(SCCLvTrainer, self).__init__()
self.model = model
self.tokenizer = tokenizer
self.optimizer = optimizer
self.train_loader = train_loader
self.args = args
self.eta = self.args.eta
self.cluster_loss = nn.KLDivLoss(size_average=False)
self.contrast_loss = PairConLoss(temperature=self.args.temperature)
self.gstep = 0
print(f"*****Intialize SCCLv, temp:{self.args.temperature}, eta:{self.args.eta}\n")
def get_batch_token(self, text):
token_feat = self.tokenizer.batch_encode_plus(
text,
max_length=self.args.max_length,
return_tensors='pt',
padding='max_length',
truncation=True
)
return token_feat
def prepare_transformer_input(self, batch):
if len(batch) == 4:
text1, text2, text3 = batch['text'], batch['augmentation_1'], batch['augmentation_2']
feat1 = self.get_batch_token(text1)
feat2 = self.get_batch_token(text2)
feat3 = self.get_batch_token(text3)
input_ids = torch.cat([feat1['input_ids'].unsqueeze(1), feat2['input_ids'].unsqueeze(1), feat3['input_ids'].unsqueeze(1)], dim=1)
attention_mask = torch.cat([feat1['attention_mask'].unsqueeze(1), feat2['attention_mask'].unsqueeze(1), feat3['attention_mask'].unsqueeze(1)], dim=1)
elif len(batch) == 2:
text = batch['text']
feat1 = self.get_batch_token(text)
feat2 = self.get_batch_token(text)
input_ids = torch.cat([feat1['input_ids'].unsqueeze(1), feat2['input_ids'].unsqueeze(1)], dim=1)
attention_mask = torch.cat([feat1['attention_mask'].unsqueeze(1), feat2['attention_mask'].unsqueeze(1)], dim=1)
return input_ids.cuda(), attention_mask.cuda()
def train_step_virtual(self, input_ids, attention_mask):
embd1, embd2 = self.model(input_ids, attention_mask, task_type="virtual")
# Instance-CL loss
feat1, feat2 = self.model.contrast_logits(embd1, embd2)
losses = self.contrast_loss(feat1, feat2)
loss = self.eta * losses["loss"]
# Clustering loss
if self.args.objective == "SCCL":
output = self.model.get_cluster_prob(embd1)
target = target_distribution(output).detach()
cluster_loss = self.cluster_loss((output+1e-08).log(), target)/output.shape[0]
loss += 0.5*cluster_loss
losses["cluster_loss"] = cluster_loss.item()
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
return losses
def train_step_explicit(self, input_ids, attention_mask):
embd1, embd2, embd3 = self.model(input_ids, attention_mask, task_type="explicit")
# Instance-CL loss
feat1, feat2 = self.model.contrast_logits(embd2, embd3)
losses = self.contrast_loss(feat1, feat2)
loss = self.eta * losses["loss"]
# Clustering loss
if self.args.objective == "SCCL":
output = self.model.get_cluster_prob(embd1)
target = target_distribution(output).detach()
cluster_loss = self.cluster_loss((output+1e-08).log(), target)/output.shape[0]
loss += cluster_loss
losses["cluster_loss"] = cluster_loss.item()
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
return losses
def train(self):
print('\n={}/{}=Iterations/Batches'.format(self.args.max_iter, len(self.train_loader)))
self.model.train()
for i in np.arange(self.args.max_iter+1):
try:
batch = next(train_loader_iter)
except:
train_loader_iter = iter(self.train_loader)
batch = next(train_loader_iter)
input_ids, attention_mask = self.prepare_transformer_input(batch)
losses = self.train_step_virtual(input_ids, attention_mask) if self.args.augtype == "virtual" else self.train_step_explicit(input_ids, attention_mask)
if (self.args.print_freq>0) and ((i%self.args.print_freq==0) or (i==self.args.max_iter)):
statistics_log(self.args.tensorboard, losses=losses, global_step=i)
self.evaluate_embedding(i)
self.model.train()
return None
def evaluate_embedding(self, step):
dataloader = unshuffle_loader(self.args)
print('---- {} evaluation batches ----'.format(len(dataloader)))
self.model.eval()
for i, batch in enumerate(dataloader):
with torch.no_grad():
text, label = batch['text'], batch['label']
feat = self.get_batch_token(text)
embeddings = self.model(feat['input_ids'].cuda(), feat['attention_mask'].cuda(), task_type="evaluate")
model_prob = self.model.get_cluster_prob(embeddings)
if i == 0:
all_labels = label
all_embeddings = embeddings.detach()
all_prob = model_prob
else:
all_labels = torch.cat((all_labels, label), dim=0)
all_embeddings = torch.cat((all_embeddings, embeddings.detach()), dim=0)
all_prob = torch.cat((all_prob, model_prob), dim=0)
# Initialize confusion matrices
confusion, confusion_model = Confusion(self.args.num_classes), Confusion(self.args.num_classes)
all_pred = all_prob.max(1)[1]
confusion_model.add(all_pred, all_labels)
confusion_model.optimal_assignment(self.args.num_classes)
acc_model = confusion_model.acc()
kmeans = cluster.KMeans(n_clusters=self.args.num_classes, random_state=self.args.seed)
embeddings = all_embeddings.cpu().numpy()
kmeans.fit(embeddings)
pred_labels = torch.tensor(kmeans.labels_.astype(np.int))
# clustering accuracy
confusion.add(pred_labels, all_labels)
confusion.optimal_assignment(self.args.num_classes)
acc = confusion.acc()
ressave = {"acc":acc, "acc_model":acc_model}
ressave.update(confusion.clusterscores())
for key, val in ressave.items():
self.args.tensorboard.add_scalar('Test/{}'.format(key), val, step)
np.save(self.args.resPath + 'acc_{}.npy'.format(step), ressave)
np.save(self.args.resPath + 'scores_{}.npy'.format(step), confusion.clusterscores())
np.save(self.args.resPath + 'mscores_{}.npy'.format(step), confusion_model.clusterscores())
# np.save(self.args.resPath + 'mpredlabels_{}.npy'.format(step), all_pred.cpu().numpy())
# np.save(self.args.resPath + 'predlabels_{}.npy'.format(step), pred_labels.cpu().numpy())
# np.save(self.args.resPath + 'embeddings_{}.npy'.format(step), embeddings)
# np.save(self.args.resPath + 'labels_{}.npy'.format(step), all_labels.cpu())
print('[Representation] Clustering scores:',confusion.clusterscores())
print('[Representation] ACC: {:.3f}'.format(acc))
print('[Model] Clustering scores:',confusion_model.clusterscores())
print('[Model] ACC: {:.3f}'.format(acc_model))
return None