-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_globloc_contrastive.py
237 lines (191 loc) · 9.97 KB
/
main_globloc_contrastive.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 13:42:16 2021
@author: user1
"""
import torch, sys
import os, csv
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
import pandas as pd
from utils import (AverageMeter, Logger, Memory, ModelCheckpoint,
NoiseContrastiveEstimator, LocalTripletLoss, Progbar)
from datasets.GLCDataset import GLContrastLoader
from network import Network
device = torch.device('cuda:0')
# train_data_dir = '/home/user1/PhD_CAPSULEAI/Project2021/DATA/train_contrast/dummy/'
# val_data_dir = '/home/user1/PhD_CAPSULEAI/Project2021/DATA/train_down/dummy/'
train_data_dir = '/home/user1/PhD_CAPSULEAI/Project2021/DATA/train_contrast/train/'
train_knn = '/home/user1/PhD_CAPSULEAI/Project2021/DATA/train_downCD/train/'
val_data_dir = '/home/user1/PhD_CAPSULEAI/Project2021/DATA/train_downCD/test/'
negative_nb = 200 # number of negative examples in NCE
lr = 0.012 #.003 loss; 0.0271 # 253 .008 0.0312 #327 0.006 0.0233
checkpoint_dir = 'GLCT_models'
log_filename = 'logs/GLCT/glct_log'
dataparallel = True
resume_epoch = 0
max_epochs = 700
only_test = False
augmentation = 'aggr'
results = {'test_acc@1': {}}
color_space = 'RGB' # can be 'RGB' OR 'LAB'
alpha, beta, gamma = 0.2, 0.6, 0.2
dataset = GLContrastLoader(train_data_dir, aug=augmentation)
train_loader = torch.utils.data.DataLoader(dataset, shuffle=True, batch_size=128, num_workers=16)
# mem_path = 'repr/GLCT_representations.pt'
mem_path = 'GLC_AA_representations.pt'
tb_dir ='./tbx/GLCT/'
# test using KNN monitor:
train_knn_dataset = GLContrastLoader(root_dir=train_knn, if_test=True)
train_knn_loader = torch.utils.data.DataLoader(train_knn_dataset,shuffle=True,batch_size=64, num_workers=16)
val_dataset = GLContrastLoader(root_dir=val_data_dir, if_test=True)
val_loader = torch.utils.data.DataLoader(val_dataset,shuffle=True,batch_size=64, num_workers=16)
checkpoint = ModelCheckpoint(mode='min', directory=checkpoint_dir)
net = Network()
if not dataparallel:
net = net.to(device)
else:
net = torch.nn.DataParallel(net, device_ids=list(range(torch.cuda.device_count()))).cuda()
optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0.9, weight_decay=1e-4)
scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=50, T_mult=2, eta_min=12e-5)
if resume_epoch!= 0:
resume_epoch = checkpoint.retreive_model(net, optimizer, resume_epoch)
memory = Memory(size=len(dataset), weight=0.5, device=device, path= mem_path)
memory.initialize(net, train_loader, epoch=resume_epoch)
noise_contrastive_estimator = NoiseContrastiveEstimator(device)
# local_contrastive_estimator = LocalContrastiveEstimator(device)
local_triplet_loss = LocalTripletLoss(device)
logger = Logger(log_filename, tb_dir)
loss_weight = 0.5
# test using a knn monitor
def test(train_knn_loader, val_loader):
net.eval()
classes = len(train_knn_loader.dataset.classes) # get classes during test
total_top1, total_num, feature_bank, clases = 0.0, 0, [], []
with torch.no_grad():
# generate feature representations
for imgs, target in tqdm(train_knn_loader): #TODO
images = imgs.to(device)
feature = net(images=images, patches=None, mode=0)
feature = F.normalize(feature, dim=1)
feature_bank.append(feature)
clases.append(target)
# [D, N]
feature_bank = torch.cat(feature_bank).t().contiguous()
# [N]
feature_labels = torch.cat(clases).to(device)
# loop test data to predict the label by weighted knn search
test_bar = tqdm(val_loader)
targets, features = [], []
for data, target in test_bar:
data, target = data.to(device), target.to(device)
feature = net(images=data, patches=None, mode=0)
feature = F.normalize(feature, dim=1)
pred_labels = knn_predict(feature, feature_bank, feature_labels, classes, knn_k=290, knn_t=0.1)
total_num += data.size(0)
total_top1 += (pred_labels[:, 0] == target).float().sum().item()
targets.append(target)
features.append(feature)
test_acc_1 = total_top1 / total_num * 100
# results['test_acc@1'][epoch] = test_acc_1
print('\n Unsupervised Accuracy : {}'.format(round(test_acc_1)))
if only_test:
sys.exit()
print( 'ADDING EMBEDDING FOR TEST DATA' )
logger.embedding(torch.cat(features), torch.cat(targets), epoch)
sys.exit()
# save statistics:
if os.path.isfile('./logs/GLCV/GLCV_AA_N512KNN_log.csv'):
with open(r'./logs/GLCV/GLCV_AA_N512KNN_log.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow([epoch, round(test_acc_1)])
else:
with open('./logs/GLCV/GLCV_AA_N512KNN_log.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow([epoch, round(test_acc_1)])
return
# knn monitor as in InstDisc https://arxiv.org/abs/1805.01978
# implementation follows http://github.com/zhirongw/lemniscate.pytorch and https://github.com/leftthomas/SimCLR
def knn_predict(feature, feature_bank, feature_labels, classes, knn_k, knn_t):
# compute cos similarity between each feature vector and feature bank ---> [B, N]
sim_matrix = torch.mm(feature, feature_bank)
# [B, K]
sim_weight, sim_indices = sim_matrix.topk(k=knn_k, dim=-1)
# [B, K]
sim_labels = torch.gather(feature_labels.expand(feature.size(0), -1), dim=-1, index=sim_indices)
sim_weight = (sim_weight / knn_t).exp()
# counts for each class
one_hot_label = torch.zeros(feature.size(0) * knn_k, classes, device=sim_labels.device)
# [B*K, C]
one_hot_label = one_hot_label.scatter(dim=-1, index=sim_labels.view(-1, 1), value=1.0)
# weighted score ---> [B, C]
pred_scores = torch.sum(one_hot_label.view(feature.size(0), -1, classes) * sim_weight.unsqueeze(dim=-1), dim=1)
pred_labels = pred_scores.argsort(dim=-1, descending=True)
return pred_labels
for epoch in range(int(resume_epoch)+1, max_epochs):
if only_test is True or (epoch%10 == 0 and epoch>0):
torch.cuda.empty_cache()
test(train_knn_loader, val_loader)
else:
iters=len(train_loader)
net = net.train()
memory.update_weighted_count(epoch)
train_loss = AverageMeter('train_loss')
local_loss_3 = AverageMeter('local_negative_loss')
global_loss_2 = AverageMeter('global_negative_loss')
alternate_view_loss_1 = AverageMeter('jigsaw_loss')
bar = Progbar(len(train_loader), stateful_metrics=['train_loss', 'valid_loss'])
# lr = optimizer.param_groups[0]['lr']
lr= scheduler.get_lr()
print('\nEpoch: {}\t lr:{:.3f}'.format(epoch, lr[0]))
for step, batch in enumerate(train_loader):
# prepare batch
images = batch['original'].to(device) #TODO
local_negatives = batch['local_negative'].to(device)
patches = [element.to(device) for element in batch['patches']]
index = batch['index']
representations = memory.return_representations(index).to(device).detach()
# zero grad
optimizer.zero_grad()
#forward, loss, backward, step
output = net(images=images, patches=patches, mode=1)
output_local_negatives = net(images=local_negatives, mode=0)
loss_1 = noise_contrastive_estimator(output[0], output[1], index, memory, negative_nb=negative_nb) # patches
loss_2 = noise_contrastive_estimator(output[0], representations, index, memory, negative_nb=negative_nb) # original
loss_3 = local_triplet_loss(output[0],representations, output_local_negatives) # Local Negative
loss = alpha* loss_1 + beta * loss_2 + gamma * loss_3
loss.mean().backward()
optimizer.step()
scheduler.step(epoch + step / iters)
# update representation memory
memory.update(index, output[0].detach().cpu().numpy())
# update metric and bar
train_loss.update(loss.item(), images.shape[0])
local_loss_3.update(loss_3.item(), images.shape[0])
global_loss_2.update(loss_2.item(), images.shape[0])
alternate_view_loss_1.update(loss_1.item(), images.shape[0])
bar.update(step, values=[('train_loss', train_loss.return_avg())])
lr = scheduler.get_lr()[0]
# update annealed lr before warm restart :
.update(epoch=epoch, loss=train_loss.return_avg(), lr=lr, name='_full_')
# sending all losses to tbx logging:
logger.update(epoch=epoch, loss=local_loss_3.return_avg(), lr=lr, name='_LN_')
logger.update(epoch=epoch, loss=global_loss_2.return_avg(), lr=lr, name='_GN_')
logger.update(epoch=epoch, loss=alternate_view_loss_1.return_avg(), lr=lr, name='_inter_view_')
# embedding to check where LN, GN and Positives are in embedding space
LN_feat = output_local_negatives.to(device).detach() # 64,128
Prior_feat = output[0].to(device).detach() # 64,128
Jigsaw_feat = output[1].to(device).detach() # 64,128
GN_feat = memory.return_random(size = negative_nb, index = index) # 200,128
GN_feat = torch.Tensor(GN_feat).to(device).detach()
concat_feat = torch.cat((LN_feat, Prior_feat, GN_feat, Jigsaw_feat), 0)logger
concat_labels = ['LN']*LN_feat.shape[0] + ['V_p']*Prior_feat.shape[0] + ['GN']*GN_feat.shape[0] + ['V_d']*Jigsaw_feat.shape[0]
logger.embedding(concat_feat ,label_imgs=None, meta=concat_labels, epoch=epoch)
# Reset LR for annealing
# print('Reset scheduler after each epoch')
# scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, len(train_loader))
# save model if improved
checkpoint.save_model(net, optimizer, train_loss.return_avg(), epoch, memory)