-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathre_resnet.py
659 lines (562 loc) · 21.3 KB
/
re_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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
"""
Implementation of ReResNet V2.
@author: Jiaming Han
"""
import e2cnn.nn as enn
import math
import os
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from collections import OrderedDict
from e2cnn import gspaces
from mmcv.cnn import constant_init, kaiming_init
from torch.nn.modules.batchnorm import _BatchNorm
from ..builder import BACKBONES
from .base_backbone import BaseBackbone
def regular_feature_type(gspace: gspaces.GSpace, planes: int, fixparams: bool = False):
""" build a regular feature map with the specified number of channels"""
assert gspace.fibergroup.order() > 0
N = gspace.fibergroup.order()
if fixparams:
planes *= math.sqrt(N)
planes = planes / N
planes = int(planes)
return enn.FieldType(gspace, [gspace.regular_repr] * planes)
def trivial_feature_type(gspace: gspaces.GSpace, planes: int, fixparams: bool = False):
""" build a trivial feature map with the specified number of channels"""
if fixparams:
planes *= math.sqrt(gspace.fibergroup.order())
planes = int(planes)
return enn.FieldType(gspace, [gspace.trivial_repr] * planes)
FIELD_TYPE = {
"trivial": trivial_feature_type,
"regular": regular_feature_type,
}
def conv3x3(gspace, inplanes, out_planes, stride=1, padding=1, dilation=1, bias=False, fixparams=False):
"""3x3 convolution with padding"""
in_type = FIELD_TYPE['regular'](gspace, inplanes, fixparams=fixparams)
out_type = FIELD_TYPE['regular'](gspace, out_planes, fixparams=fixparams)
return enn.R2Conv(in_type, out_type, 3,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
sigma=None,
frequencies_cutoff=lambda r: 3 * r)
def conv1x1(gspace, inplanes, out_planes, stride=1, padding=0, dilation=1, bias=False, fixparams=False):
"""1x1 convolution"""
in_type = FIELD_TYPE['regular'](gspace, inplanes, fixparams=fixparams)
out_type = FIELD_TYPE['regular'](gspace, out_planes, fixparams=fixparams)
return enn.R2Conv(in_type, out_type, 1,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
sigma=None,
frequencies_cutoff=lambda r: 3 * r)
def build_norm_layer(cfg, gspace, num_features, postfix=''):
in_type = FIELD_TYPE['regular'](gspace, num_features)
return 'bn' + str(postfix), enn.InnerBatchNorm(in_type)
class BasicBlock(enn.EquivariantModule):
def __init__(self,
in_channels,
out_channels,
expansion=1,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
gspace=None,
fixparams=False):
super(BasicBlock, self).__init__()
self.in_type = FIELD_TYPE['regular'](
gspace, in_channels, fixparams=fixparams)
self.out_type = FIELD_TYPE['regular'](
gspace, out_channels, fixparams=fixparams)
self.in_channels = in_channels
self.out_channels = out_channels
self.expansion = expansion
assert self.expansion == 1
assert out_channels % expansion == 0
self.mid_channels = out_channels // expansion
self.stride = stride
self.dilation = dilation
self.style = style
self.with_cp = with_cp
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.norm1_name, norm1 = build_norm_layer(
norm_cfg, gspace, self.mid_channels, postfix=1)
self.norm2_name, norm2 = build_norm_layer(
norm_cfg, gspace, out_channels, postfix=2)
self.conv1 = conv3x3(
gspace,
in_channels,
self.mid_channels,
stride=stride,
padding=dilation,
dilation=dilation,
bias=False,
fixparams=fixparams)
self.add_module(self.norm1_name, norm1)
self.relu1 = enn.ReLU(self.conv1.out_type, inplace=True)
self.conv2 = conv3x3(
gspace,
self.mid_channels,
out_channels,
padding=1,
bias=False,
fixparams=fixparams)
self.add_module(self.norm2_name, norm2)
self.relu2 = enn.ReLU(self.conv1.out_type, inplace=True)
self.downsample = downsample
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu1(out)
out = self.conv2(out)
out = self.norm2(out)
if self.downsample is not None:
identity = self.downsample(x)
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.relu2(out)
return out
def evaluate_output_shape(self, input_shape):
assert len(input_shape) == 4
assert input_shape[1] == self.in_type.size
if self.downsample is not None:
return self.downsample.evaluate_output_shape(input_shape)
else:
return input_shape
def export(self):
self.eval()
submodules = []
# convert all the submodules if necessary
for name, module in self._modules.items():
if hasattr(module, 'export'):
module = module.export()
submodules.append((name, module))
return torch.nn.ModuleDict(OrderedDict(submodules))
class Bottleneck(enn.EquivariantModule):
def __init__(self,
in_channels,
out_channels,
expansion=4,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
gspace=None,
fixparams=False):
super(Bottleneck, self).__init__()
assert style in ['pytorch', 'caffe']
self.in_type = FIELD_TYPE['regular'](
gspace, in_channels, fixparams=fixparams)
self.out_type = FIELD_TYPE['regular'](
gspace, out_channels, fixparams=fixparams)
self.in_channels = in_channels
self.out_channels = out_channels
self.expansion = expansion
assert out_channels % expansion == 0
self.mid_channels = out_channels // expansion
self.stride = stride
self.dilation = dilation
self.style = style
self.with_cp = with_cp
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
if self.style == 'pytorch':
self.conv1_stride = 1
self.conv2_stride = stride
else:
self.conv1_stride = stride
self.conv2_stride = 1
self.norm1_name, norm1 = build_norm_layer(
norm_cfg, gspace, self.mid_channels, postfix=1)
self.norm2_name, norm2 = build_norm_layer(
norm_cfg, gspace, self.mid_channels, postfix=2)
self.norm3_name, norm3 = build_norm_layer(
norm_cfg, gspace, out_channels, postfix=3)
self.conv1 = conv1x1(
gspace,
in_channels,
self.mid_channels,
stride=self.conv1_stride,
bias=False,
fixparams=fixparams)
self.add_module(self.norm1_name, norm1)
self.relu1 = enn.ReLU(self.conv1.out_type, inplace=True)
self.conv2 = conv3x3(
gspace,
self.mid_channels,
self.mid_channels,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False,
fixparams=fixparams)
self.add_module(self.norm2_name, norm2)
self.relu2 = enn.ReLU(self.conv2.out_type, inplace=True)
self.conv3 = conv1x1(
gspace,
self.mid_channels,
out_channels,
bias=False,
fixparams=fixparams)
self.add_module(self.norm3_name, norm3)
self.relu3 = enn.ReLU(self.conv3.out_type, inplace=True)
self.downsample = downsample
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
@property
def norm3(self):
return getattr(self, self.norm3_name)
def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu1(out)
out = self.conv2(out)
out = self.norm2(out)
out = self.relu2(out)
out = self.conv3(out)
out = self.norm3(out)
if self.downsample is not None:
identity = self.downsample(x)
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.relu3(out)
return out
def evaluate_output_shape(self, input_shape):
assert len(input_shape) == 4
assert input_shape[1] == self.in_type.size
if self.downsample is not None:
return self.downsample.evaluate_output_shape(input_shape)
else:
return input_shape
def export(self):
self.eval()
submodules = []
# convert all the submodules if necessary
for name, module in self._modules.items():
if hasattr(module, 'export'):
module = module.export()
submodules.append((name, module))
return torch.nn.ModuleDict(OrderedDict(submodules))
def get_expansion(block, expansion=None):
if isinstance(expansion, int):
assert expansion > 0
elif expansion is None:
if hasattr(block, 'expansion'):
expansion = block.expansion
elif issubclass(block, BasicBlock):
expansion = 1
elif issubclass(block, Bottleneck):
expansion = 4
else:
raise TypeError(f'expansion is not specified for {block.__name__}')
else:
raise TypeError('expansion must be an integer or None')
return expansion
class ResLayer(nn.Sequential):
def __init__(self,
block,
num_blocks,
in_channels,
out_channels,
expansion=None,
stride=1,
avg_down=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
gspace=None,
fixparams=False,
**kwargs):
self.block = block
self.expansion = get_expansion(block, expansion)
downsample = None
if stride != 1 or in_channels != out_channels:
downsample = []
conv_stride = stride
if avg_down and stride != 1:
conv_stride = 1
in_type = FIELD_TYPE["regular"](
gspace, in_channels, fixparams=fixparams)
downsample.append(
enn.PointwiseAvgPool(
in_type,
kernel_size=stride,
stride=stride,
ceil_mode=True))
downsample.extend([
conv1x1(gspace, in_channels, out_channels,
stride=conv_stride, bias=False),
build_norm_layer(norm_cfg, gspace, out_channels)[1]
])
downsample = enn.SequentialModule(*downsample)
layers = []
layers.append(
block(
in_channels=in_channels,
out_channels=out_channels,
expansion=self.expansion,
stride=stride,
downsample=downsample,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
gspace=gspace,
fixparams=fixparams,
**kwargs))
in_channels = out_channels
for i in range(1, num_blocks):
layers.append(
block(
in_channels=in_channels,
out_channels=out_channels,
expansion=self.expansion,
stride=1,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
gspace=gspace,
fixparams=fixparams,
**kwargs))
super(ResLayer, self).__init__(*layers)
def export(self):
self.eval()
submodules = []
# convert all the submodules if necessary
for name, module in self._modules.items():
if hasattr(module, 'export'):
module = module.export()
submodules.append((name, module))
return torch.nn.ModuleDict(OrderedDict(submodules))
@BACKBONES.register_module()
class ReResNet(BaseBackbone):
arch_settings = {
18: (BasicBlock, (2, 2, 2, 2)),
34: (BasicBlock, (3, 4, 6, 3)),
50: (Bottleneck, (3, 4, 6, 3)),
101: (Bottleneck, (3, 4, 23, 3)),
152: (Bottleneck, (3, 8, 36, 3))
}
def __init__(self,
depth,
in_channels=3,
stem_channels=64,
base_channels=64,
expansion=None,
num_stages=4,
strides=(1, 2, 2, 2),
dilations=(1, 1, 1, 1),
out_indices=(3,),
style='pytorch',
deep_stem=False,
avg_down=False,
frozen_stages=-1,
conv_cfg=None,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=False,
with_cp=False,
zero_init_residual=True,
orientation=8,
fixparams=False,
with_geotensor=False):
super(ReResNet, self).__init__()
if depth not in self.arch_settings:
raise KeyError(f'invalid depth {depth} for resnet')
self.depth = depth
self.stem_channels = stem_channels
self.base_channels = base_channels
self.num_stages = num_stages
assert num_stages >= 1 and num_stages <= 4
self.strides = strides
self.dilations = dilations
assert len(strides) == len(dilations) == num_stages
self.out_indices = out_indices
assert max(out_indices) < num_stages
self.style = style
self.deep_stem = deep_stem
self.avg_down = avg_down
self.frozen_stages = frozen_stages
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.with_cp = with_cp
self.norm_eval = norm_eval
self.zero_init_residual = zero_init_residual
self.block, stage_blocks = self.arch_settings[depth]
self.stage_blocks = stage_blocks[:num_stages]
self.expansion = get_expansion(self.block, expansion)
self.orientation = orientation
self.fixparams = fixparams
self.with_geotensor = with_geotensor # just for testing equivariance
self.gspace = gspaces.Rot2dOnR2(orientation)
self.in_type = enn.FieldType(
self.gspace, [self.gspace.trivial_repr] * 3)
self._make_stem_layer(self.gspace, in_channels, stem_channels)
self.res_layers = []
_in_channels = stem_channels
_out_channels = base_channels * self.expansion
for i, num_blocks in enumerate(self.stage_blocks):
stride = strides[i]
dilation = dilations[i]
res_layer = self.make_res_layer(
block=self.block,
num_blocks=num_blocks,
in_channels=_in_channels,
out_channels=_out_channels,
expansion=self.expansion,
stride=stride,
dilation=dilation,
style=self.style,
avg_down=self.avg_down,
with_cp=with_cp,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
gspace=self.gspace,
fixparams=self.fixparams)
_in_channels = _out_channels
_out_channels *= 2
layer_name = f'layer{i + 1}'
self.add_module(layer_name, res_layer)
self.res_layers.append(layer_name)
self._freeze_stages()
self.feat_dim = res_layer[-1].out_channels
def make_res_layer(self, **kwargs):
return ResLayer(**kwargs)
@property
def norm1(self):
return getattr(self, self.norm1_name)
def _make_stem_layer(self, gspace, in_channels, stem_channels):
if not self.deep_stem:
in_type = enn.FieldType(
gspace, in_channels * [gspace.trivial_repr])
out_type = FIELD_TYPE['regular'](gspace, stem_channels)
self.conv1 = enn.R2Conv(in_type, out_type, 7,
stride=2,
padding=3,
bias=False,
sigma=None,
frequencies_cutoff=lambda r: 3 * r)
self.norm1_name, norm1 = build_norm_layer(
self.norm_cfg, gspace, stem_channels, postfix=1)
self.add_module(self.norm1_name, norm1)
self.relu = enn.ReLU(self.conv1.out_type, inplace=True)
self.maxpool = enn.PointwiseMaxPool(
self.conv1.out_type, kernel_size=3, stride=2, padding=1)
def _freeze_stages(self):
if self.frozen_stages >= 0:
if not self.deep_stem:
self.norm1.eval()
for m in [self.conv1, self.norm1]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False
def init_weights(self, pretrained=None):
super(ReResNet, self).init_weights(pretrained)
if pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv2d):
kaiming_init(m)
elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
constant_init(m, 1)
if self.zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
constant_init(m.norm3, 0)
elif isinstance(m, BasicBlock):
constant_init(m.norm2, 0)
def forward(self, x):
if not self.deep_stem:
x = enn.GeometricTensor(x, self.in_type)
x = self.conv1(x)
x = self.norm1(x)
x = self.relu(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.tensor if not self.with_geotensor else x)
if len(outs) == 1:
return outs[0]
else:
return tuple(outs)
def train(self, mode=True):
super(ReResNet, self).train(mode)
self._freeze_stages()
if mode and self.norm_eval:
for m in self.modules():
# trick: eval have effect on BatchNorm only
if isinstance(m, _BatchNorm):
m.eval()
def export(self):
self.eval()
submodules = []
# convert all the submodules if necessary
for name, module in self._modules.items():
if hasattr(module, 'export'):
module = module.export()
submodules.append((name, module))
return torch.nn.ModuleDict(OrderedDict(submodules))
if __name__ == "__main__":
class TestNet(nn.Module):
def __init__(self, gspace):
super().__init__()
out_type = FIELD_TYPE['regular'](gspace, 2048)
self.gpool = enn.GroupPooling(out_type)
self.linear = torch.nn.Linear(256, 1000)
def forward(self, out):
out = self.gpool(out)
out = out.tensor
gpool_out = out
b, c, w, h = out.shape
out = nn.functional.avg_pool2d(out, (w, h))
out = out.view(out.size(0), -1)
out = self.linear(out)
return out, gpool_out
m = ReResNet(depth=50, out_indices=(3, ), with_geotensor=True)
test_net = TestNet(m.gspace)
m.eval()
x = torch.randn(3, 3, 513, 801)
x90 = x.rot90(1, (2, 3))
y, gpool_out = test_net(m(x))
y90, gpool_out90 = test_net(m(x90))
print('G-POOL 90 degrees ROTATIONS EQUIVARIANCE:' +
('YES' if torch.allclose(gpool_out, gpool_out90.rot90(-1, (2, 3)), atol=1e-5) else 'NO'))
print('90 degrees ROTATIONS INVARIANCE:' +
('YES' if torch.allclose(y, y90, atol=1e-5) else 'NO'))