This repository has been archived by the owner on May 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
resnet.py
182 lines (150 loc) · 6.83 KB
/
resnet.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
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_NORM_EPSILON = 1e-5
BATCH_NORM_DECAY = 0.9 # == pytorch's default value as well
class BatchNormRelu(nn.Sequential):
def __init__(self, num_channels, relu=True):
super().__init__(nn.BatchNorm2d(num_channels, eps=BATCH_NORM_EPSILON), nn.ReLU() if relu else nn.Identity())
def conv(in_channels, out_channels, kernel_size=3, stride=1, bias=False):
return nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size,
stride=stride, padding=(kernel_size - 1) // 2, bias=bias)
class SelectiveKernel(nn.Module):
def __init__(self, in_channels, out_channels, stride, sk_ratio, min_dim=32):
super().__init__()
assert sk_ratio > 0.0
self.main_conv = nn.Sequential(conv(in_channels, 2 * out_channels, stride=stride),
BatchNormRelu(2 * out_channels))
mid_dim = max(int(out_channels * sk_ratio), min_dim)
self.mixing_conv = nn.Sequential(conv(out_channels, mid_dim, kernel_size=1), BatchNormRelu(mid_dim),
conv(mid_dim, 2 * out_channels, kernel_size=1))
def forward(self, x):
x = self.main_conv(x)
x = torch.stack(torch.chunk(x, 2, dim=1), dim=0) # 2, B, C, H, W
g = x.sum(dim=0).mean(dim=[2, 3], keepdim=True)
m = self.mixing_conv(g)
m = torch.stack(torch.chunk(m, 2, dim=1), dim=0) # 2, B, C, 1, 1
return (x * F.softmax(m, dim=0)).sum(dim=0)
class Projection(nn.Module):
def __init__(self, in_channels, out_channels, stride, sk_ratio=0):
super().__init__()
if sk_ratio > 0:
self.shortcut = nn.Sequential(nn.ZeroPad2d((0, 1, 0, 1)),
# kernel_size = 2 => padding = 1
nn.AvgPool2d(kernel_size=2, stride=stride, padding=0),
conv(in_channels, out_channels, kernel_size=1))
else:
self.shortcut = conv(in_channels, out_channels, kernel_size=1, stride=stride)
self.bn = BatchNormRelu(out_channels, relu=False)
def forward(self, x):
return self.bn(self.shortcut(x))
class BottleneckBlock(nn.Module):
expansion = 4
def __init__(self, in_channels, out_channels, stride, sk_ratio=0, use_projection=False):
super().__init__()
if use_projection:
self.projection = Projection(in_channels, out_channels * 4, stride, sk_ratio)
else:
self.projection = nn.Identity()
ops = [conv(in_channels, out_channels, kernel_size=1), BatchNormRelu(out_channels)]
if sk_ratio > 0:
ops.append(SelectiveKernel(out_channels, out_channels, stride, sk_ratio))
else:
ops.append(conv(out_channels, out_channels, stride=stride))
ops.append(BatchNormRelu(out_channels))
ops.append(conv(out_channels, out_channels * 4, kernel_size=1))
ops.append(BatchNormRelu(out_channels * 4, relu=False))
self.net = nn.Sequential(*ops)
def forward(self, x):
shortcut = self.projection(x)
return F.relu(shortcut + self.net(x))
class Blocks(nn.Module):
def __init__(self, num_blocks, in_channels, out_channels, stride, sk_ratio=0):
super().__init__()
self.blocks = nn.ModuleList([BottleneckBlock(in_channels, out_channels, stride, sk_ratio, True)])
self.channels_out = out_channels * BottleneckBlock.expansion
for _ in range(num_blocks - 1):
self.blocks.append(BottleneckBlock(self.channels_out, out_channels, 1, sk_ratio))
def forward(self, x):
for b in self.blocks:
x = b(x)
return x
class Stem(nn.Sequential):
def __init__(self, sk_ratio, width_multiplier):
ops = []
channels = 64 * width_multiplier // 2
if sk_ratio > 0:
ops.append(conv(3, channels, stride=2))
ops.append(BatchNormRelu(channels))
ops.append(conv(channels, channels))
ops.append(BatchNormRelu(channels))
ops.append(conv(channels, channels * 2))
else:
ops.append(conv(3, channels * 2, kernel_size=7, stride=2))
ops.append(BatchNormRelu(channels * 2))
ops.append(nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
super().__init__(*ops)
class ResNet(nn.Module):
def __init__(self, layers, width_multiplier, sk_ratio):
super().__init__()
ops = [Stem(sk_ratio, width_multiplier)]
channels_in = 64 * width_multiplier
ops.append(Blocks(layers[0], channels_in, 64 * width_multiplier, 1, sk_ratio))
channels_in = ops[-1].channels_out
ops.append(Blocks(layers[1], channels_in, 128 * width_multiplier, 2, sk_ratio))
channels_in = ops[-1].channels_out
ops.append(Blocks(layers[2], channels_in, 256 * width_multiplier, 2, sk_ratio))
channels_in = ops[-1].channels_out
ops.append(Blocks(layers[3], channels_in, 512 * width_multiplier, 2, sk_ratio))
channels_in = ops[-1].channels_out
self.channels_out = channels_in
self.net = nn.Sequential(*ops)
self.fc = nn.Linear(channels_in, 1000)
def forward(self, x, apply_fc=False):
h = self.net(x).mean(dim=[2, 3])
if apply_fc:
h = self.fc(h)
return h
class ContrastiveHead(nn.Module):
def __init__(self, channels_in, out_dim=128, num_layers=3):
super().__init__()
self.layers = nn.ModuleList()
for i in range(num_layers):
if i != num_layers - 1:
dim, relu = channels_in, True
else:
dim, relu = out_dim, False
self.layers.append(nn.Linear(channels_in, dim, bias=False))
bn = nn.BatchNorm1d(dim, eps=BATCH_NORM_EPSILON, affine=True)
if i == num_layers - 1:
nn.init.zeros_(bn.bias)
self.layers.append(bn)
if relu:
self.layers.append(nn.ReLU())
def forward(self, x):
for b in self.layers:
x = b(x)
return x
def get_resnet(depth=50, width_multiplier=1, sk_ratio=0): # sk_ratio=0.0625 is recommended
layers = {50: [3, 4, 6, 3], 101: [3, 4, 23, 3], 152: [3, 8, 36, 3], 200: [3, 24, 36, 3]}[depth]
resnet = ResNet(layers, width_multiplier, sk_ratio)
return resnet, ContrastiveHead(resnet.channels_out)
def name_to_params(checkpoint):
sk_ratio = 0.0625 if '_sk1' in checkpoint else 0
if 'r50_' in checkpoint:
depth = 50
elif 'r101_' in checkpoint:
depth = 101
elif 'r152_' in checkpoint:
depth = 152
else:
raise NotImplementedError
if '_1x_' in checkpoint:
width = 1
elif '_2x_' in checkpoint:
width = 2
elif '_3x_' in checkpoint:
width = 3
else:
raise NotImplementedError
return depth, width, sk_ratio