-
Notifications
You must be signed in to change notification settings - Fork 0
/
misc.py
194 lines (149 loc) · 5.99 KB
/
misc.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
import torch
from torch import nn
import torchvision
from torchvision import transforms
from torchvision import models
from utils import build_backbone_infomin as bbi
import numpy as np
import os
class Identity(nn.Module):
"""
Identity layer
"""
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
class AugmentOnTest:
"""
wrapper to assess test samples
"""
def __init__(self, dataset, n):
"""
Args:
dataset: a instance of torch.utils.data.Dataset class.
n: number of copies to be created for each sample.
"""
self.dataset = dataset
self.n = n
def __len__(self):
return self.n * len(self.dataset)
def __getitem__(self, i):
return self.dataset[i // self.n]
def get_model(method, ft_from_featuremap):
"""
function to get the pre-trained network given the method as input
Args:
method: which method to return the pre-trained network
ft_from_featuremap: indicates if fine-tuning from feature map
or latent representation
"""
print(30*"**")
print(f"Loading pre-trained weights from {method}...")
resnet = None
msg = "Empty message"
if method == 'simclr':
print("Loading SimCLR...")
#weights from https://github.com/google-research/simclr
cpt = torch.load('/experimentos/pesos/simclr/simclr_r50_800.pth')
resnet = models.resnet50(pretrained=False)
msg = resnet.load_state_dict(cpt)
resnet.fc = Identity()
elif method == 'swav':
#weights from https://github.com/facebookresearch/swav
resnet = torch.hub.load('facebookresearch/swav:main', 'resnet50')
resnet.fc = Identity()
elif method == 'baseline':
resnet = models.resnet50(pretrained=True)
resnet.fc = Identity()
elif method == 'byol':
#weights from https://github.com/deepmind/deepmind-research/tree/master/byol
cpt = torch.load('/experimentos/pesos/byol/byol_res50x1.pth.tar')
resnet = models.resnet50(pretrained=False)
msg = resnet.load_state_dict(cpt)
resnet.fc = Identity()
elif method == 'infomin':
model, _ = bbi.build_model()
model, msg = bbi.load_encoder_weights(model)
resnet = model.encoder
elif method == 'moco':
#weights from https://github.com/facebookresearch/moco
path = '/experimentos/pesos/mocov2/moco_v2_800ep_pretrain.pth.tar'
resnet, msg = load_moco(path)
resnet.fc = Identity()
else:
raise NotImplementedError()
print(30*"**")
print("Loading Weights with message: ",msg)
print(30*"**")
assert resnet is not None, "Encoder Network is None. Fix this issue."
#adjust the last layer if necessary
resnet = adjust_last_layers(method, ft_from_featuremap, resnet)
return resnet
def adjust_last_layers(method, ft_from_featuremap, model):
"""
Adjust the last layer from the network. This is only required
when fine-tuning from feature map instead from the latent representation.
"""
if method in ['simclr', 'swav', 'byol'] and ft_from_featuremap:
model.avgpool = Identity()
return model
def get_data_transforms(method):
"""
Get proper data augmentation for the method given as parameter
"""
#mean and std for imagenet
mean = [0.485, 0.456, 0.406]
std = [0.228, 0.224, 0.225]
normalize = transforms.Normalize(mean=mean, std=std)
train_trans = [transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.RandomResizedCrop(299, scale=(0.75, 1.0)),
transforms.RandomRotation(45),
transforms.ColorJitter(hue=0.2),
transforms.ToTensor()]
val_trans = [transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.RandomResizedCrop(299, scale=(0.75, 1.0)),
transforms.RandomRotation(45),
transforms.ColorJitter(hue=0.2),
transforms.ToTensor()]
test_trans = [transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.RandomResizedCrop(299, scale=(0.75, 1.0)),
transforms.RandomRotation(45),
transforms.ColorJitter(hue=0.2),
transforms.ToTensor()]
#simclr is the only one which was trained without imagenet normalization
if method not in ['simclr']:
train_trans.append(normalize)
val_trans.append(normalize)
test_trans.append(normalize)
#dict to store the transformations for each step
data_transforms = {
'train': transforms.Compose(train_trans),
'val': transforms.Compose(val_trans),
'test': transforms.Compose(test_trans)
}
return data_transforms
def load_moco(path):
#piece of code adapted from https://github.com/facebookresearch/moco/blob/master/main_lincls.py#L155-L177
model = models.resnet50(pretrained=False)
if os.path.isfile(path):
print("=> loading checkpoint '{}'".format(path))
checkpoint = torch.load(path, map_location="cpu")
# rename moco pre-trained keys
state_dict = checkpoint['state_dict']
for k in list(state_dict.keys()):
# retain only encoder_q up to before the embedding layer
if k.startswith('module.encoder_q') and not k.startswith('module.encoder_q.fc'):
# remove prefix
state_dict[k[len("module.encoder_q."):]] = state_dict[k]
# delete renamed or unused k
del state_dict[k]
msg = model.load_state_dict(state_dict, strict=False)
assert set(msg.missing_keys) == {"fc.weight", "fc.bias"}
msg = f"=> loaded pre-trained model '{path}'"
else:
msg = f"=> no checkpoint found at '{path}'"
return model, msg