This repository was archived by the owner on Jan 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 542
/
Copy pathResNet.py
398 lines (309 loc) · 14.1 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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
from __future__ import division
import os
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from core.config import cfg
import nn as mynn
import utils.net as net_utils
from utils.resnet_weights_helper import convert_state_dict
# ---------------------------------------------------------------------------- #
# Bits for specific architectures (ResNet50, ResNet101, ...)
# ---------------------------------------------------------------------------- #
def ResNet50_conv4_body():
return ResNet_convX_body((3, 4, 6))
def ResNet50_conv5_body():
return ResNet_convX_body((3, 4, 6, 3))
def ResNet101_conv4_body():
return ResNet_convX_body((3, 4, 23))
def ResNet101_conv5_body():
return ResNet_convX_body((3, 4, 23, 3))
def ResNet152_conv5_body():
return ResNet_convX_body((3, 8, 36, 3))
# ---------------------------------------------------------------------------- #
# Generic ResNet components
# ---------------------------------------------------------------------------- #
class ResNet_convX_body(nn.Module):
def __init__(self, block_counts):
super(ResNet_convX_body, self).__init__()
self.block_counts = block_counts
self.convX = len(block_counts) + 1
self.num_layers = (sum(block_counts) + 3 * (self.convX == 4)) * 3 + 2
self.res1 = globals()[cfg.RESNETS.STEM_FUNC]()
dim_in = 64
dim_bottleneck = cfg.RESNETS.NUM_GROUPS * cfg.RESNETS.WIDTH_PER_GROUP
self.res2, dim_in = add_stage(dim_in, 256, dim_bottleneck, block_counts[0],
dilation=1, stride_init=1)
self.res3, dim_in = add_stage(dim_in, 512, dim_bottleneck * 2, block_counts[1],
dilation=1, stride_init=2)
self.res4, dim_in = add_stage(dim_in, 1024, dim_bottleneck * 4, block_counts[2],
dilation=1, stride_init=2)
if len(block_counts) == 4:
stride_init = 2 if cfg.RESNETS.RES5_DILATION == 1 else 1
self.res5, dim_in = add_stage(dim_in, 2048, dim_bottleneck * 8, block_counts[3],
cfg.RESNETS.RES5_DILATION, stride_init)
self.spatial_scale = 1 / 32 * cfg.RESNETS.RES5_DILATION
else:
self.spatial_scale = 1 / 16 # final feature scale wrt. original image scale
self.dim_out = dim_in
self._init_modules()
def _init_modules(self):
assert cfg.RESNETS.FREEZE_AT in [0, 2, 3, 4, 5]
assert cfg.RESNETS.FREEZE_AT <= self.convX
for i in range(1, cfg.RESNETS.FREEZE_AT + 1):
freeze_params(getattr(self, 'res%d' % i))
# Freeze all bn (affine) layers !!!
self.apply(lambda m: freeze_params(m) if isinstance(m, mynn.AffineChannel2d) else None)
def detectron_weight_mapping(self):
if cfg.RESNETS.USE_GN:
mapping_to_detectron = {
'res1.conv1.weight': 'conv1_w',
'res1.gn1.weight': 'conv1_gn_s',
'res1.gn1.bias': 'conv1_gn_b',
}
orphan_in_detectron = ['pred_w', 'pred_b']
else:
mapping_to_detectron = {
'res1.conv1.weight': 'conv1_w',
'res1.bn1.weight': 'res_conv1_bn_s',
'res1.bn1.bias': 'res_conv1_bn_b',
}
orphan_in_detectron = ['conv1_b', 'fc1000_w', 'fc1000_b']
for res_id in range(2, self.convX + 1):
stage_name = 'res%d' % res_id
mapping, orphans = residual_stage_detectron_mapping(
getattr(self, stage_name), stage_name,
self.block_counts[res_id - 2], res_id)
mapping_to_detectron.update(mapping)
orphan_in_detectron.extend(orphans)
return mapping_to_detectron, orphan_in_detectron
def train(self, mode=True):
# Override
self.training = mode
for i in range(cfg.RESNETS.FREEZE_AT + 1, self.convX + 1):
getattr(self, 'res%d' % i).train(mode)
def forward(self, x):
for i in range(self.convX):
x = getattr(self, 'res%d' % (i + 1))(x)
return x
class ResNet_roi_conv5_head(nn.Module):
def __init__(self, dim_in, roi_xform_func, spatial_scale):
super(ResNet_roi_conv5_head, self).__init__()
self.roi_xform = roi_xform_func
self.spatial_scale = spatial_scale
dim_bottleneck = cfg.RESNETS.NUM_GROUPS * cfg.RESNETS.WIDTH_PER_GROUP
stride_init = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION // 7
self.res5, self.dim_out = add_stage(dim_in, 2048, dim_bottleneck * 8, 3,
dilation=1, stride_init=stride_init)
self.avgpool = nn.AvgPool2d(7)
self._init_modules()
def _init_modules(self):
# Freeze all bn (affine) layers !!!
self.apply(lambda m: freeze_params(m) if isinstance(m, mynn.AffineChannel2d) else None)
def detectron_weight_mapping(self):
mapping_to_detectron, orphan_in_detectron = \
residual_stage_detectron_mapping(self.res5, 'res5', 3, 5)
return mapping_to_detectron, orphan_in_detectron
def forward(self, x, rpn_ret):
x = self.roi_xform(
x, rpn_ret,
blob_rois='rois',
method=cfg.FAST_RCNN.ROI_XFORM_METHOD,
resolution=cfg.FAST_RCNN.ROI_XFORM_RESOLUTION,
spatial_scale=self.spatial_scale,
sampling_ratio=cfg.FAST_RCNN.ROI_XFORM_SAMPLING_RATIO
)
res5_feat = self.res5(x)
x = self.avgpool(res5_feat)
if cfg.MODEL.SHARE_RES5 and self.training:
return x, res5_feat
else:
return x
def add_stage(inplanes, outplanes, innerplanes, nblocks, dilation=1, stride_init=2):
"""Make a stage consist of `nblocks` residual blocks.
Returns:
- stage module: an nn.Sequentail module of residual blocks
- final output dimension
"""
res_blocks = []
stride = stride_init
for _ in range(nblocks):
res_blocks.append(add_residual_block(
inplanes, outplanes, innerplanes, dilation, stride
))
inplanes = outplanes
stride = 1
return nn.Sequential(*res_blocks), outplanes
def add_residual_block(inplanes, outplanes, innerplanes, dilation, stride):
"""Return a residual block module, including residual connection, """
if stride != 1 or inplanes != outplanes:
shortcut_func = globals()[cfg.RESNETS.SHORTCUT_FUNC]
downsample = shortcut_func(inplanes, outplanes, stride)
else:
downsample = None
trans_func = globals()[cfg.RESNETS.TRANS_FUNC]
res_block = trans_func(
inplanes, outplanes, innerplanes, stride,
dilation=dilation, group=cfg.RESNETS.NUM_GROUPS,
downsample=downsample)
return res_block
# ------------------------------------------------------------------------------
# various downsample shortcuts (may expand and may consider a new helper)
# ------------------------------------------------------------------------------
def basic_bn_shortcut(inplanes, outplanes, stride):
return nn.Sequential(
nn.Conv2d(inplanes,
outplanes,
kernel_size=1,
stride=stride,
bias=False),
mynn.AffineChannel2d(outplanes),
)
def basic_gn_shortcut(inplanes, outplanes, stride):
return nn.Sequential(
nn.Conv2d(inplanes,
outplanes,
kernel_size=1,
stride=stride,
bias=False),
nn.GroupNorm(net_utils.get_group_gn(outplanes), outplanes,
eps=cfg.GROUP_NORM.EPSILON)
)
# ------------------------------------------------------------------------------
# various stems (may expand and may consider a new helper)
# ------------------------------------------------------------------------------
def basic_bn_stem():
return nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)),
('bn1', mynn.AffineChannel2d(64)),
('relu', nn.ReLU(inplace=True)),
# ('maxpool', nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True))]))
('maxpool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))]))
def basic_gn_stem():
return nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)),
('gn1', nn.GroupNorm(net_utils.get_group_gn(64), 64,
eps=cfg.GROUP_NORM.EPSILON)),
('relu', nn.ReLU(inplace=True)),
('maxpool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))]))
# ------------------------------------------------------------------------------
# various transformations (may expand and may consider a new helper)
# ------------------------------------------------------------------------------
class bottleneck_transformation(nn.Module):
""" Bottleneck Residual Block """
def __init__(self, inplanes, outplanes, innerplanes, stride=1, dilation=1, group=1,
downsample=None):
super(bottleneck_transformation, self).__init__()
# In original resnet, stride=2 is on 1x1.
# In fb.torch resnet, stride=2 is on 3x3.
(str1x1, str3x3) = (stride, 1) if cfg.RESNETS.STRIDE_1X1 else (1, stride)
self.stride = stride
self.conv1 = nn.Conv2d(
inplanes, innerplanes, kernel_size=1, stride=str1x1, bias=False)
self.bn1 = mynn.AffineChannel2d(innerplanes)
self.conv2 = nn.Conv2d(
innerplanes, innerplanes, kernel_size=3, stride=str3x3, bias=False,
padding=1 * dilation, dilation=dilation, groups=group)
self.bn2 = mynn.AffineChannel2d(innerplanes)
self.conv3 = nn.Conv2d(
innerplanes, outplanes, kernel_size=1, stride=1, bias=False)
self.bn3 = mynn.AffineChannel2d(outplanes)
self.downsample = downsample
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class bottleneck_gn_transformation(nn.Module):
expansion = 4
def __init__(self, inplanes, outplanes, innerplanes, stride=1, dilation=1, group=1,
downsample=None):
super(bottleneck_gn_transformation, self).__init__()
# In original resnet, stride=2 is on 1x1.
# In fb.torch resnet, stride=2 is on 3x3.
(str1x1, str3x3) = (stride, 1) if cfg.RESNETS.STRIDE_1X1 else (1, stride)
self.stride = stride
self.conv1 = nn.Conv2d(
inplanes, innerplanes, kernel_size=1, stride=str1x1, bias=False)
self.gn1 = nn.GroupNorm(net_utils.get_group_gn(innerplanes), innerplanes,
eps=cfg.GROUP_NORM.EPSILON)
self.conv2 = nn.Conv2d(
innerplanes, innerplanes, kernel_size=3, stride=str3x3, bias=False,
padding=1 * dilation, dilation=dilation, groups=group)
self.gn2 = nn.GroupNorm(net_utils.get_group_gn(innerplanes), innerplanes,
eps=cfg.GROUP_NORM.EPSILON)
self.conv3 = nn.Conv2d(
innerplanes, outplanes, kernel_size=1, stride=1, bias=False)
self.gn3 = nn.GroupNorm(net_utils.get_group_gn(outplanes), outplanes,
eps=cfg.GROUP_NORM.EPSILON)
self.downsample = downsample
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.gn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.gn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.gn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
# ---------------------------------------------------------------------------- #
# Helper functions
# ---------------------------------------------------------------------------- #
def residual_stage_detectron_mapping(module_ref, module_name, num_blocks, res_id):
"""Construct weight mapping relation for a residual stage with `num_blocks` of
residual blocks given the stage id: `res_id`
"""
if cfg.RESNETS.USE_GN:
norm_suffix = '_gn'
else:
norm_suffix = '_bn'
mapping_to_detectron = {}
orphan_in_detectron = []
for blk_id in range(num_blocks):
detectron_prefix = 'res%d_%d' % (res_id, blk_id)
my_prefix = '%s.%d' % (module_name, blk_id)
# residual branch (if downsample is not None)
if getattr(module_ref[blk_id], 'downsample'):
dtt_bp = detectron_prefix + '_branch1' # short for "detectron_branch_prefix"
mapping_to_detectron[my_prefix
+ '.downsample.0.weight'] = dtt_bp + '_w'
orphan_in_detectron.append(dtt_bp + '_b')
mapping_to_detectron[my_prefix
+ '.downsample.1.weight'] = dtt_bp + norm_suffix + '_s'
mapping_to_detectron[my_prefix
+ '.downsample.1.bias'] = dtt_bp + norm_suffix + '_b'
# conv branch
for i, c in zip([1, 2, 3], ['a', 'b', 'c']):
dtt_bp = detectron_prefix + '_branch2' + c
mapping_to_detectron[my_prefix
+ '.conv%d.weight' % i] = dtt_bp + '_w'
orphan_in_detectron.append(dtt_bp + '_b')
mapping_to_detectron[my_prefix
+ '.' + norm_suffix[1:] + '%d.weight' % i] = dtt_bp + norm_suffix + '_s'
mapping_to_detectron[my_prefix
+ '.' + norm_suffix[1:] + '%d.bias' % i] = dtt_bp + norm_suffix + '_b'
return mapping_to_detectron, orphan_in_detectron
def freeze_params(m):
"""Freeze all the weights by setting requires_grad to False
"""
for p in m.parameters():
p.requires_grad = False