-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathres2net.py
315 lines (249 loc) · 11.6 KB
/
res2net.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
import torch
import torch.nn as nn
__all__ = ['ImageNetRes2Net', 'res2net50', 'res2net101',
'res2net152', 'res2next50_32x4d', 'se_res2net50',
'CifarRes2Net', 'res2next29_6cx24wx4scale',
'res2next29_8cx25wx4scale', 'res2next29_6cx24wx6scale',
'res2next29_6cx24wx4scale_se', 'res2next29_8cx25wx4scale_se',
'res2next29_6cx24wx6scale_se']
def conv3x3(in_planes, out_planes, stride=1, groups=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, groups=groups, bias=False)
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
class SEModule(nn.Module):
def __init__(self, channels, reduction=16):
super(SEModule, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1, padding=0)
self.relu = nn.ReLU(inplace=True)
self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1, padding=0)
self.sigmoid = nn.Sigmoid()
def forward(self, input):
x = self.avg_pool(input)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
x = self.sigmoid(x)
return input * x
class Res2NetBottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, downsample=None, stride=1, scales=4, groups=1, se=False, norm_layer=None):
super(Res2NetBottleneck, self).__init__()
if planes % scales != 0:
raise ValueError('Planes must be divisible by scales')
if norm_layer is None:
norm_layer = nn.BatchNorm2d
bottleneck_planes = groups * planes
self.conv1 = conv1x1(inplanes, bottleneck_planes, stride)
self.bn1 = norm_layer(bottleneck_planes)
self.conv2 = nn.ModuleList([conv3x3(bottleneck_planes // scales, bottleneck_planes // scales, groups=groups) for _ in range(scales-1)])
self.bn2 = nn.ModuleList([norm_layer(bottleneck_planes // scales) for _ in range(scales-1)])
self.conv3 = conv1x1(bottleneck_planes, planes * self.expansion)
self.bn3 = norm_layer(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.se = SEModule(planes * self.expansion) if se else None
self.downsample = downsample
self.stride = stride
self.scales = scales
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
xs = torch.chunk(out, self.scales, 1)
ys = []
for s in range(self.scales):
if s == 0:
ys.append(xs[s])
elif s == 1:
ys.append(self.relu(self.bn2[s-1](self.conv2[s-1](xs[s]))))
else:
ys.append(self.relu(self.bn2[s-1](self.conv2[s-1](xs[s] + ys[-1]))))
out = torch.cat(ys, 1)
out = self.conv3(out)
out = self.bn3(out)
if self.se is not None:
out = self.se(out)
if self.downsample is not None:
identity = self.downsample(identity)
out += identity
out = self.relu(out)
return out
class ImageNetRes2Net(nn.Module):
def __init__(self, layers, num_classes=1000, zero_init_residual=False,
groups=1, width=16, scales=4, se=False, norm_layer=None):
super(ImageNetRes2Net, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
planes = [int(width * scales * 2 ** i) for i in range(4)]
self.inplanes = planes[0]
self.conv1 = nn.Conv2d(3, planes[0], kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = norm_layer(planes[0])
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(Res2NetBottleneck, planes[0], layers[0], scales=scales, groups=groups, se=se, norm_layer=norm_layer)
self.layer2 = self._make_layer(Res2NetBottleneck, planes[1], layers[1], stride=2, scales=scales, groups=groups, se=se, norm_layer=norm_layer)
self.layer3 = self._make_layer(Res2NetBottleneck, planes[2], layers[2], stride=2, scales=scales, groups=groups, se=se, norm_layer=norm_layer)
self.layer4 = self._make_layer(Res2NetBottleneck, planes[3], layers[3], stride=2, scales=scales, groups=groups, se=se, norm_layer=norm_layer)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(planes[3] * Res2NetBottleneck.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Res2NetBottleneck):
nn.init.constant_(m.bn3.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, scales=4, groups=1, se=False, norm_layer=None):
if norm_layer is None:
norm_layer = nn.BatchNorm2d
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, downsample, stride=stride, scales=scales, groups=groups, se=se, norm_layer=norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, scales=scales, groups=groups, se=se, norm_layer=norm_layer))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
class CifarRes2Net(nn.Module):
def __init__(self, layers, num_classes=100, zero_init_residual=False,
groups=1, width=64, scales=4, se=False, norm_layer=None):
super(CifarRes2Net, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
planes = [int(width * scales * 2 ** i) for i in range(3)]
self.inplanes = planes[0]
self.conv1 = conv3x3(3, planes[0])
self.bn1 = norm_layer(planes[0])
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(Res2NetBottleneck, planes[0], layers[0], scales=scales, groups=groups, se=se, norm_layer=norm_layer)
self.layer2 = self._make_layer(Res2NetBottleneck, planes[1], layers[1], stride=2, scales=scales, groups=groups, se=se, norm_layer=norm_layer)
self.layer3 = self._make_layer(Res2NetBottleneck, planes[2], layers[2], stride=2, scales=scales, groups=groups, se=se, norm_layer=norm_layer)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(planes[2] * Res2NetBottleneck.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
# Zero-initialize the last BN in each residual branch,
# so that the residual branch starts with zeros, and each residual block behaves like an identity.
# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
if zero_init_residual:
for m in self.modules():
if isinstance(m, Res2NetBottleneck):
nn.init.constant_(m.bn3.weight, 0)
def _make_layer(self, block, planes, blocks, stride=1, scales=4, groups=1, se=False, norm_layer=None):
if norm_layer is None:
norm_layer = nn.BatchNorm2d
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(self.inplanes, planes * block.expansion, stride),
norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, downsample, stride=stride, scales=scales, groups=groups, se=se, norm_layer=norm_layer))
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.append(block(self.inplanes, planes, scales=scales, groups=groups, se=se, norm_layer=norm_layer))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def res2net50(**kwargs):
"""Constructs a Res2Net-50 model.
"""
model = ImageNetRes2Net([3, 4, 6, 3], **kwargs)
return model
def res2net101(**kwargs):
"""Constructs a ResNet-101 model.
"""
model = ImageNetRes2Net([3, 4, 23, 3], **kwargs)
return model
def res2net152(**kwargs):
"""Constructs a ResNet-152 model.
"""
model = ImageNetRes2Net([3, 8, 36, 3], **kwargs)
return model
def res2next50_32x4d(**kwargs):
"""Constructs a Res2NeXt-50_32x4d model.
"""
model = ImageNetRes2Net([3, 4, 6, 3], groups=32, width=4, **kwargs)
return model
def res2next101_32x8d(**kwargs):
"""Constructs a Res2NeXt-101_32x8d model.
"""
model = ImageNetRes2Net([3, 4, 23, 3], groups=32, width=8, **kwargs)
return model
def se_res2net50(**kwargs):
"""Constructs a SE-Res2Net-50 model.
"""
model = ImageNetRes2Net([3, 4, 6, 3], se=True, **kwargs)
return model
def res2next29_6cx24wx4scale(**kwargs):
"""Constructs a Res2NeXt-29, 6cx24wx4scale model.
"""
model = CifarRes2Net([3, 3, 3], groups=6, width=24, scales=4, **kwargs)
return model
def res2next29_8cx25wx4scale(**kwargs):
"""Constructs a Res2NeXt-29, 8cx25wx4scale model.
"""
model = CifarRes2Net([3, 3, 3], groups=8, width=25, scales=4, **kwargs)
return model
def res2next29_6cx24wx6scale(**kwargs):
"""Constructs a Res2NeXt-29, 6cx24wx6scale model.
"""
model = CifarRes2Net([3, 3, 3], groups=6, width=24, scales=6, **kwargs)
return model
def res2next29_6cx24wx4scale_se(**kwargs):
"""Constructs a Res2NeXt-29, 6cx24wx4scale-SE model.
"""
model = CifarRes2Net([3, 3, 3], groups=6, width=24, scales=4, se=True, **kwargs)
return model
def res2next29_8cx25wx4scale_se(**kwargs):
"""Constructs a Res2NeXt-29, 8cx25wx4scale-SE model.
"""
model = CifarRes2Net([3, 3, 3], groups=8, width=25, scales=4, se=True, **kwargs)
return model
def res2next29_6cx24wx6scale_se(**kwargs):
"""Constructs a Res2NeXt-29, 6cx24wx6scale-SE model.
"""
model = CifarRes2Net([3, 3, 3], groups=6, width=24, scales=6, se=True, **kwargs)
return model