-
Notifications
You must be signed in to change notification settings - Fork 0
/
root_resnet.py
345 lines (292 loc) · 10.1 KB
/
root_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
import torch.nn as nn
from mmcv.cnn import xavier_init, constant_init, normal_init
import torch
def conv3x3(in_planes, out_planes, stride=1, dilation=1):
"3x3 convolutioin with padding"
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=3,
stride=stride,
padding=dilation,
dilation=dilation,
bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
with_cp=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride, dilation)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
assert not with_cp
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
with_cp=False):
"""Bottleneck block for resnet."""
super(Bottleneck, self).__init__()
self.inplanes = inplanes
self.planes = planes
self.conv1_stride = 1
self.conv2_stride = stride
# self.conv1 doesn't change the size(h, w) of images
self.conv1 = nn.Conv2d(
inplanes,
planes,
kernel_size=1,
stride=self.conv1_stride,
bias=False)
# self.conv2 will change the size(h, w) of images
# only if the self.conv2_stride != 1
self.conv2 = nn.Conv2d(
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.bn2 = nn.BatchNorm2d(planes)
# self.conv3 changes the channel of input,
self.conv3 = nn.Conv2d(
planes, planes * self.expansion, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
self.with_cp = with_cp
def forward(self, x):
def _inner_forward(x):
identity = 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:
identity = self.downsample(identity)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
def make_res_layer(block,
inplanes,
planes,
blocks,
stride=1,
dilation=1,
with_cp=False):
downsample = None
if stride != 1 or inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(
inplanes,
planes * block.expansion,
kernel_size=1,
stride=stride,
bias=False),
nn.BatchNorm2d(planes * block.expansion)
)
layers = []
layers.append(
block(
inplanes,
planes,
stride,
dilation,
downsample,
with_cp=with_cp))
inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(
block(inplanes, planes, 1, dilation, with_cp=with_cp))
return nn.Sequential(*layers)
class SSDRES512(nn.Module):
arch_setting = {
18: (BasicBlock, (2, 2, 2, 2)),
34: (BasicBlock, (3, 4, 6, 3, 1, 1, 1, 1)),
50: (Bottleneck, (3, 4, 6, 3)),
101: (Bottleneck, (3, 4, 23, 3)),
152: (Bottleneck, (3, 8, 36, 3))
}
def __init__(self,
input_size,
depth,
num_stages=8,
strides=(1, 2, 2, 2, 2, 2, 2, 2),
dilations=(1, 1, 1, 1, 1, 1, 1, 1),
out_indices=(2, 3, 4, 5, 6, 7),
with_cp=False):
super(SSDRES512, self).__init__()
self.depth = depth
self.num_stages = num_stages
self.strides = strides
self.dilations = dilations
self.out_indices = out_indices
self.with_cp = with_cp
# stage_blocks = (3, 4, 23, 3)
self.block, stage_blocks = self.arch_setting[depth]
self.stage_blocks = stage_blocks[:num_stages] # (3, 4, 23, 3)
self.inplanes = 64
self.input_size = input_size
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(64)
self.relu2 = nn.ReLU(inplace=True)
self.conv3 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn3 = nn.BatchNorm2d(64)
self.relu3 = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.res_layers = []
for i, num_blocks in enumerate(self.stage_blocks): # (3, 4, 23, 3)
stride = strides[i] # (1, 2, 2, 2)
dilation = dilations[i] # (1, 1, 1, 1)
if i <= 3:
planes = 64 * 2 ** i
else:
planes = 128
# Bottleneck: input_channels=in_plabnes, output_channels=palnes*4
res_layer = make_res_layer(
self.block,
self.inplanes,
planes,
num_blocks,
stride=stride,
dilation=dilation,
with_cp=with_cp)
self.inplanes = planes * self.block.expansion
layer_name = 'layer{}'.format(i + 1)
self.add_module(layer_name, res_layer)
self.res_layers.append(layer_name)
self.L2Norm1 = L2Norm(1024, 20)
self.L2Norm2 = L2Norm(2048, 20)
self.conv4 = nn.Conv2d(2048, 1024, kernel_size=3, stride=1, padding=1, bias=False)
self.bn4 = nn.BatchNorm2d(1024)
self.relu4 = nn.ReLU(inplace=True)
self.conv5 = nn.Conv2d(1024, 512, kernel_size=3, stride=2, padding=1, bias=False)
self.bn5 = nn.BatchNorm2d(512)
self.relu5 = nn.ReLU(inplace=True)
self.conv6 = nn.Conv2d(512, 256, kernel_size=3, stride=2, padding=1, bias=False)
self.bn6 = nn.BatchNorm2d(256)
self.relu6 = nn.ReLU(inplace=True)
self.conv7 = nn.Conv2d(256, 256, kernel_size=3, stride=1,bias=False)
self.bn7 = nn.BatchNorm2d(256)
self.relu7 = nn.ReLU(inplace=True)
self.conv8 = nn.Conv2d(256, 256, kernel_size=3, stride=1, bias=False)
self.bn8 = nn.BatchNorm2d(256)
self.relu8 = nn.ReLU(inplace=True)
def init_weight(self, pretraind=None):
if pretraind is None:
for m in self.modules():
if isinstance(m, nn.Conv2d):
xavier_init(m, distribution='uniform')
elif isinstance(m, nn.BatchNorm2d):
constant_init(m, 1)
elif isinstance(m, nn.Linear):
normal_init(m, std=0.01)
else:
raise TypeError('pertrained must be a str or NOne')
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu2(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.relu3(x)
x = self.maxpool(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i in self.out_indices:
outs.append(x)
outs[0] = self.L2Norm1(outs[0])
outs[1] = self.L2Norm2(outs[1])
x = self.conv4(x)
x = self.bn4(x)
x = self.relu4(x)
x = self.conv5(x)
x = self.bn5(x)
x = self.relu5(x)
outs.append(x)
x = self.conv6(x)
x = self.bn6(x)
x = self.relu6(x)
outs.append(x)
x = self.conv7(x)
x = self.bn7(x)
x = self.relu7(x)
outs.append(x)
x = self.conv8(x)
x = self.bn8(x)
x = self.relu8(x)
outs.append(x)
if len(outs) == 1:
return outs[0]
else:
return tuple(outs)
class L2Norm(nn.Module):
def __init__(self, in_channels, scale):
super(L2Norm, self).__init__()
self.in_channels = in_channels
self.gamma = scale or None
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.in_channels))
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.constant_(self.weight, self.gamma)
def forward(self, x):
norm = x.pow(2).sum(dim=1, keepdim=True).sqrt()+self.eps
x = torch.div(x, norm)
out = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3 ).expand_as(x) * x
return out
if __name__ == "__main__":
import torch
input = torch.randn(size=(1, 3, 512, 512))
net = SSDRES512(input_size=(512, 512), depth=101)
out = net(input)
x = out
for x in out:
print(x.shape)