-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbackbones.py
More file actions
110 lines (104 loc) · 4.59 KB
/
backbones.py
File metadata and controls
110 lines (104 loc) · 4.59 KB
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
import torch
import torch.nn as nn
import clip
import torch.nn.functional as F
import random
from torchvision import transforms
import numpy as np
from functools import partial
def linear(indim, outdim):
return nn.Linear(indim, outdim)
class BasicBlockRN12(nn.Module):
def __init__(self, in_planes, planes):
super(BasicBlockRN12, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes, kernel_size=3, padding=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes)
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, planes, kernel_size=1, bias=False),
nn.BatchNorm2d(planes)
)
def forward(self, x):
out = F.leaky_relu(self.bn1(self.conv1(x)), negative_slope = 0.1)
out = F.leaky_relu(self.bn2(self.conv2(out)), negative_slope = 0.1)
out = self.bn3(self.conv3(out))
out += self.shortcut(x)
return out
class ResNet12(nn.Module):
def __init__(self, feature_maps, input_shape, num_classes, few_shot, rotations):
super(ResNet12, self).__init__()
layers = []
layers.append(BasicBlockRN12(input_shape[0], feature_maps))
layers.append(BasicBlockRN12(feature_maps, int(2.5 * feature_maps)))
layers.append(BasicBlockRN12(int(2.5 * feature_maps), 5 * feature_maps))
layers.append(BasicBlockRN12(5 * feature_maps, 10 * feature_maps))
self.layers = nn.Sequential(*layers)
self.linear = linear(10 * feature_maps, num_classes)
self.rotations = rotations
self.linear_rot = linear(10 * feature_maps, 4)
self.mp = nn.MaxPool2d((2,2))
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def forward(self, x, index_mixup = None, lam = -1):
if lam != -1:
mixup_layer = random.randint(0, 3)
else:
mixup_layer = -1
out = x
if mixup_layer == 0:
out = lam * out + (1 - lam) * out[index_mixup]
for i in range(len(self.layers)):
out = self.layers[i](out)
if mixup_layer == i + 1:
out = lam * out + (1 - lam) * out[index_mixup]
out = self.mp(F.leaky_relu(out, negative_slope = 0.1))
out = F.avg_pool2d(out, out.shape[2])
features = out.view(out.size(0), -1)
return features
class Clip(nn.Module):
def __init__(self, name, device, return_tokens = False):
super(Clip, self).__init__()
self.backbone, self.process = clip.load(name, device='cpu')
self.backbone = self.backbone.to(device)
def forward(self, x):
return self.backbone.encode_image(x)
def default_transformations(img, image_size):
img = transforms.ToTensor()(img)
norm = transforms.Normalize(np.array([x / 255.0 for x in [125.3, 123.0, 113.9]]), np.array([x / 255.0 for x in [63.0, 62.1, 66.7]]))
all_transforms = torch.nn.Sequential(transforms.Resize(int(1.1*image_size)), transforms.CenterCrop(image_size), norm)
img = all_transforms(img)
return img
def load_model_weights(model, path, device):
pretrained_dict = torch.load(path, map_location=device)
model_dict = model.state_dict()
#pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
new_dict = {}
for k, v in pretrained_dict.items():
if k in model_dict:
if 'bn' in k:
new_dict[k] = v
else:
new_dict[k] = v.half()
model_dict.update(new_dict)
model.load_state_dict(model_dict)
print('Model loaded!')
# Get the model
def get_model(model_name, model_path, image_size, device):
if model_name == 'resnet12':
model = ResNet12(64, [3, 84, 84], 351, True, False).to(device)
load_model_weights(model, model_path, device)
transformations = partial(default_transformations, image_size=image_size)
elif 'clip' in model_name.lower():
clip_name = {'clip_b32':'ViT-B/32', 'clip_b16':'ViT-B/16', 'clip_l14':'ViT-L/14', 'clip_l14_336px':'ViT-L/14@336px'}[model_name.lower()]
model = Clip(clip_name, device)
transformations = model.process
else:
raise NotImplementedError
return model, transformations