-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainAugcomp.py
409 lines (304 loc) · 17.1 KB
/
trainAugcomp.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import argparse
import math
import numpy as np
import torch
import torch.nn as nn
from torch.optim import SGD, lr_scheduler
from torch.utils.data import DataLoader
from tqdm import tqdm
from PIL import Image
from data.augmentations import get_transform
from FER import RafDataset,get_RAFDB_datasets
from util.general_utils import AverageMeter, init_experiment
from util.cluster_and_log_utils import log_accs_from_preds
from config import exp_root
from model import DINOHead, info_nce_logits, SupConLoss, DistillLoss, ContrastiveLearningViewGenerator, get_params_groups
from model import DynamicLSR
from model import DINOHeadExtended,WorstCaseEstimationLoss,TotalClusteringLoss
def train(student, train_loader, test_loader, unlabelled_train_loader, args):
params_groups = get_params_groups(student)
optimizer = SGD(params_groups, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)
fp16_scaler = None
if args.fp16:
fp16_scaler = torch.cuda.amp.GradScaler()
total_norm = 0
exp_lr_scheduler = lr_scheduler.CosineAnnealingLR(
optimizer,
T_max=args.epochs,
eta_min=args.lr * 1e-3,
)
cluster_criterion = DistillLoss(
args.warmup_teacher_temp_epochs,
args.epochs,
args.n_views,
args.warmup_teacher_temp,
args.teacher_temp,
)
total_loss_func = TotalClusteringLoss(
num_classes=args.num_labeled_classes
feat_dim=args.feat_dim,
device=device,
wb_weight=1.0,
max_min_weight=0.1
).to(device)
worst_case_criterion = WorstCaseEstimationLoss(eta_prime=args.eta_prime)
# worst_case_criterion = WorstCaseEstimationLoss_v2(eta_prime=args.eta_prime)
# inductive
best_test_acc_lab = 0
# transductive
best_train_acc_lab = 0
best_train_acc_ubl = 0
best_train_acc_all = 0
for epoch in range(args.epochs):
loss_record = AverageMeter()
student.train()
for batch_idx, batch in enumerate(train_loader):
images, class_labels, uq_idxs, mask_lab = batch
mask_lab = mask_lab[:, 0]
class_labels, mask_lab = class_labels.cuda(non_blocking=True), mask_lab.cuda(non_blocking=True).bool()
images = torch.cat(images, dim=0).cuda(non_blocking=True)
with torch.cuda.amp.autocast(fp16_scaler is not None):
student_proj, student_out, aux_logits = student(images)
teacher_out = student_out.detach()
# clustering, sup
sup_logits = torch.cat([f[mask_lab] for f in (student_out / 0.1).chunk(2)], dim=0)
sup_labels = torch.cat([class_labels[mask_lab] for _ in range(2)], dim=0)
cls_loss = nn.CrossEntropyLoss()(sup_logits, sup_labels)#cls_loss
total_steps = len(train_loader) * (epoch+1)
initial_e = 0.1
dynamic_lsr = DynamicLSR(initial_e=0.1, total_steps=total_steps)
LSR_loss = dynamic_lsr(sup_logits, sup_labels)
# clustering, unsup
cluster_loss = cluster_criterion(student_out, teacher_out, epoch)
avg_probs = (student_out / 0.1).softmax(dim=1).mean(dim=0)
me_max_loss = - torch.sum(torch.log(avg_probs**(-avg_probs))) + math.log(float(len(avg_probs)))
cluster_loss += args.memax_weight * me_max_loss
# represent learning, unsup
contrastive_logits, contrastive_labels = info_nce_logits(features=student_proj)
# print(contrastive_labels)
contrastive_loss = torch.nn.CrossEntropyLoss()(contrastive_logits, contrastive_labels)
# representation learning, sup
student_proj = torch.cat([f[mask_lab].unsqueeze(1) for f in student_proj.chunk(2)], dim=1)
student_proj = torch.nn.functional.normalize(student_proj, dim=-1)
sup_con_labels = class_labels[mask_lab]
sup_con_loss = SupConLoss()(student_proj, labels=sup_con_labels)
if epoch >= args.cluster_epochs:
total_loss = total_loss_func(student_proj , sup_con_labels)
else:
total_loss = torch.tensor(0.0).cuda()
# if epoch >= args.cluster_epochs:
# total_loss = total_loss_func(sup_con_logits ,sup_con_labels)
# else:
# total_loss = torch.tensor(0.0).cuda()
'''
aughead
'''
# if epoch >= args.worst_epochs:
# student_out_views = student_out.chunk(2)
# aux_logits_views = aux_logits.chunk(2)
# y_l = student_out_views[0][mask_lab]
# y_l_adv = aux_logits_views[0][mask_lab]
# y_u = student_out_views[0][~mask_lab]
# y_u_adv = aux_logits_views[0][~mask_lab]
# worst_case_loss = args.trade_off_worst * worst_case_criterion(y_l, y_l_adv, y_u, y_u_adv)
# else:
# worst_case_loss = torch.tensor(0.0).cuda()
student_out_views = student_out.chunk(2)
aux_logits_views = aux_logits.chunk(2)
y_l = student_out_views[0][mask_lab]
y_l_adv = aux_logits_views[0][mask_lab]
y_u = student_out_views[0][~mask_lab]
y_u_adv = aux_logits_views[0][~mask_lab]
worst_case_loss = args.worst_weight * worst_case_criterion(y_l, y_l_adv, y_u, y_u_adv)
pstr = ''
pstr += f'cls_loss: {cls_loss.item():.4f} '
pstr += f'cluster_loss: {cluster_loss.item():.4f} '
pstr += f'sup_con_loss: {sup_con_loss.item():.4f} '
pstr += f'contrastive_loss: {contrastive_loss.item():.4f} '
pstr += f'LSR_loss: {LSR_loss.item():.4f} '
pstr += f'worst_case_loss: {worst_case_loss.item():.4f} '
pstr += f'clustering_loss: {total_loss.item():.4f} '
#
loss = 0
loss += (1 - args.sup_weight) * cluster_loss + args.sup_weight * cls_loss
loss += (1 - args.sup_weight) * contrastive_loss + args.sup_weight * sup_con_loss
loss += args.LSR_weight * LSR_loss
loss += worst_case_loss
loss += args.cluster *total_loss
# Train acc
loss_record.update(loss.item(), class_labels.size(0))
optimizer.zero_grad()
if fp16_scaler is None:
loss.backward()
torch.nn.utils.clip_grad_norm_(student.parameters(), max_norm=100.0)
optimizer.step()
else:
fp16_scaler.scale(loss).backward()
fp16_scaler.step(optimizer)
fp16_scaler.update()
if batch_idx % args.print_freq == 0:
args.logger.info('Epoch: [{}][{}/{}]\t loss {:.5f}\t {}'
.format(epoch, batch_idx, len(train_loader), loss.item(), pstr))
args.logger.info('Train Epoch: {} Avg Loss: {:.4f} '.format(epoch, loss_record.avg))
args.logger.info('Testing on unlabelled examples in the training data...')
all_acc, old_acc, new_acc = test(student, unlabelled_train_loader, epoch=epoch, save_name='Train ACC Unlabelled', args=args)
original_data = np.loadtxt(f"./Results/clusterfinal.txt", delimiter=',')
new_data = np.append(original_data, [all_acc, old_acc, new_acc])
np.savetxt(f"./Results/clusterfinal.txt", new_data, fmt='%f', delimiter=',')
args.logger.info('Train Accuracies: All {:.4f} | Old {:.4f} | New {:.4f}'.format(all_acc, old_acc, new_acc))
exp_lr_scheduler.step()
save_dict = {
'model': student.state_dict(),
'optimizer': optimizer.state_dict(),
'epoch': epoch + 1,
}
if old_acc_test > best_test_acc_lab:
args.logger.info(f'Best ACC on old Classes on disjoint test set: {old_acc_test:.4f}...')
args.logger.info('Best Train Accuracies: All {:.4f} | Old {:.4f} | New {:.4f}'.format(all_acc, old_acc, new_acc))
torch.save(save_dict, args.model_path[:-3] + f'_best.pt')
args.logger.info("model saved to {}.".format(args.model_path[:-3] + f'_best.pt'))
# inductive
best_test_acc_lab = old_acc_test
# transductive
best_train_acc_lab = old_acc
best_train_acc_ubl = new_acc
best_train_acc_all = all_acc
args.logger.info(f'Exp Name: {args.exp_name}')
args.logger.info(f'Metrics with best model on test set: All: {best_train_acc_all:.4f} Old: {best_train_acc_lab:.4f} New: {best_train_acc_ubl:.4f}')
def test(model, test_loader, epoch, save_name, args):
model.eval()
preds, targets = [], []
mask = np.array([])
for batch_idx, (images, label, _) in enumerate(tqdm(test_loader)):
images = images.cuda(non_blocking=True)
with torch.no_grad():
embedding, logits,_ = model(images)
preds.append(logits.argmax(1).cpu().numpy())
targets.append(label.cpu().numpy())
mask = np.append(mask,
np.array([True if x.item() in args.train_classes else False for x in label]))
data_embed_npy=torch.cat(data_emb_collect,axis=0).cpu().numpy()
label_npy=torch.cat(label_collect,axis=0).cpu().numpy()
preds = np.concatenate(preds)
targets = np.concatenate(targets)
all_acc, old_acc, new_acc = log_accs_from_preds(y_true=targets, y_pred=preds, mask=mask,
T=epoch, eval_funcs=args.eval_funcs, save_name=save_name,
args=args)
return all_acc, old_acc, new_acc
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='cluster', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--batch_size', default=128, type=int)
parser.add_argument('--num_workers', default=8, type=int)
parser.add_argument('--eval_funcs', nargs='+', help='Which eval functions to use', default=['v2', 'v2p'])
parser.add_argument('--warmup_model_dir', type=str, default=None)
parser.add_argument('--dataset_name', type=str, default='rafdb', help='options: cifar10, cifar100, imagenet_100, cub, scars, fgvc_aricraft, herbarium_19')
parser.add_argument('--prop_train_labels', type=float, default=0.5)
parser.add_argument('--use_ssb_splits', action='store_true', default=True)
parser.add_argument('--grad_from_block', type=int, default=11)
parser.add_argument('--lr', type=float, default=0.1)
parser.add_argument('--gamma', type=float, default=0.1)
parser.add_argument('--momentum', type=float, default=0.9)
parser.add_argument('--weight_decay', type=float, default=5e-5)
parser.add_argument('--epochs', default=200, type=int)
parser.add_argument('--exp_root', type=str, default=exp_root)
parser.add_argument('--transform', type=str, default='imagenet')
parser.add_argument('--sup_weight', type=float, default=0.35)
parser.add_argument('--n_views', default=2, type=int)
parser.add_argument('--memax_weight', type=float, default=2)
parser.add_argument('--warmup_teacher_temp', default=0.07, type=float, help='Initial value for the teacher temperature.')
parser.add_argument('--teacher_temp', default=0.04, type=float, help='Final value (after linear warmup)of the teacher temperature.')
parser.add_argument('--warmup_teacher_temp_epochs', default=30, type=int, help='Number of warmup epochs for the teacher temperature.')
parser.add_argument('--fp16', action='store_true', default=False)
parser.add_argument('--print_freq', default=10, type=int)
parser.add_argument('--exp_name', default=None, type=str)
#------------------------
#Aughead
parser.add_argument('--eta-prime', default=2, type=float,
help='weight of adversarial loss on labeled data (default: 2)')
parser.add_argument('--worst_weight', default=0.2, type=float,
help='weight of worst-case estimation loss on unlabeled data (default: 0.2)')
parser.add_argument('--cluster_epochs', default=50, type=int, help='Number of warmup epochs for the clustering.')
parser.add_argument('--cluster', default=0.2, type=int, help='weight for the clustering.')
parser.add_argument('--LSR_weight', default=0.3, type=int, help='weight for the Dynamic LSR.')
# ----------------------
# INIT
# ----------------------
args = parser.parse_args([])
device = torch.device('cuda:0')
args.dataset_name = "ferplus"
args.train_classes = (0,1,2,3)
args.unlabeled_classes = (4,5,6,7)
args.exp_name = "ferplus0123"
# args.memax_weight = 1
args.eval_funcs = 'v2'
args.num_labeled_classes = len(args.train_classes)
args.num_unlabeled_classes = len(args.unlabeled_classes)
init_experiment(args, runner_name=['simgcd'])
args.logger.info(f'Using evaluation function {args.eval_funcs[0]} to print results')
torch.backends.cudnn.benchmark = True
# ----------------------
# BASE MODEL
# ----------------------
args.interpolation = 3
args.crop_pct = 0.875
backbone = torch.hub.load('facebookresearch/dino:main', 'dino_vitb16')
if args.warmup_model_dir is not None:
args.logger.info(f'Loading weights from {args.warmup_model_dir}')
backbone.load_state_dict(torch.load(args.warmup_model_dir, map_location='cpu'))
# NOTE: Hardcoded image size as we do not finetune the entire ViT model
args.image_size = 224
args.feat_dim = 768
args.num_mlp_layers = 3
args.mlp_out_dim = args.num_labeled_classes + args.num_unlabeled_classes
# ----------------------
# HOW MUCH OF BASE MODEL TO FINETUNE
# ----------------------
for m in backbone.parameters():
m.requires_grad = False
# Only finetune layers from block 'args.grad_from_block' onwards
for name, m in backbone.named_parameters():
if 'block' in name:
block_num = int(name.split('.')[1])
if block_num >= args.grad_from_block:
m.requires_grad = True
args.logger.info('model build')
# --------------------
# CONTRASTIVE TRANSFORM
# --------------------
train_transform, test_transform = get_transform(args.transform, image_size=args.image_size, args=args)
train_transform = ContrastiveLearningViewGenerator(base_transform=train_transform, n_views=args.n_views)
# --------------------
# DATASETS
# --------------------
train_dataset, test_dataset, unlabelled_train_examples_test, datasets = get_RAFDB_datasets(args.dataset_name,
train_transform,
test_transform,
args)
# --------------------
# SAMPLER
# Sampler which balances labelled and unlabelled examples in each batch
# --------------------
label_len = len(train_dataset.labelled_dataset)
unlabelled_len = len(train_dataset.unlabelled_dataset)
sample_weights = [1 if i < label_len else label_len / unlabelled_len for i in range(len(train_dataset))]
sample_weights = torch.DoubleTensor(sample_weights)
sampler = torch.utils.data.WeightedRandomSampler(sample_weights, num_samples=len(train_dataset))
# --------------------
# DATALOADERS
# --------------------
train_loader = DataLoader(train_dataset, num_workers=args.num_workers, batch_size=args.batch_size, shuffle=False,
sampler=sampler, drop_last=True, pin_memory=True)
test_loader_unlabelled = DataLoader(unlabelled_train_examples_test, num_workers=args.num_workers,
batch_size=256, shuffle=False, pin_memory=False)
test_loader_labelled = DataLoader(test_dataset, num_workers=args.num_workers,
batch_size=256, shuffle=False, pin_memory=False)
# ----------------------
# PROJECTION HEAD
# ----------------------
projector = DINOHeadExtended(in_dim=args.feat_dim, out_dim=args.mlp_out_dim, nlayers=args.num_mlp_layers)
model = nn.Sequential(backbone, projector).to(device)
# ----------------------
# TRAIN
# ----------------------
train(model, train_loader, test_loader_labelled, test_loader_unlabelled, args)
# train(model, train_loader, None, test_loader_unlabelled, args)