File size: 24,619 Bytes
c310e19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
# # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# """
# Variant of the resnet module that takes cfg as an argument.
# Example usage. Strings may be specified in the config file.
#     model = ResNet(
#         "StemWithFixedBatchNorm",
#         "BottleneckWithFixedBatchNorm",
#         "ResNet50StagesTo4",
#     )
# Custom implementations may be written in user code and hooked in via the
# `register_*` functions.
# """
# from collections import namedtuple

# import torch
# import torch.nn.functional as F
# from torch import nn

# from maskrcnn_benchmark.layers import FrozenBatchNorm2d
# from maskrcnn_benchmark.layers import Conv2d


# # ResNet stage specification
# StageSpec = namedtuple(
#     "StageSpec",
#     [
#         "index",  # Index of the stage, eg 1, 2, ..,. 5
#         "block_count",  # Numer of residual blocks in the stage
#         "return_features",  # True => return the last feature map from this stage
#     ],
# )

# # -----------------------------------------------------------------------------
# # Standard ResNet models
# # -----------------------------------------------------------------------------
# # ResNet-50 (including all stages)
# ResNet50StagesTo5 = (
#     StageSpec(index=i, block_count=c, return_features=r)
#     for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, False), (4, 3, True))
# )
# # ResNet-50 up to stage 4 (excludes stage 5)
# ResNet50StagesTo4 = (
#     StageSpec(index=i, block_count=c, return_features=r)
#     for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, True))
# )
# # ResNet-50-FPN (including all stages)
# ResNet50FPNStagesTo5 = (
#     StageSpec(index=i, block_count=c, return_features=r)
#     for (i, c, r) in ((1, 3, True), (2, 4, True), (3, 6, True), (4, 3, True))
# )
# # ResNet-101-FPN (including all stages)
# ResNet101FPNStagesTo5 = (
#     StageSpec(index=i, block_count=c, return_features=r)
#     for (i, c, r) in ((1, 3, True), (2, 4, True), (3, 23, True), (4, 3, True))
# )


# class ResNet(nn.Module):
#     def __init__(self, cfg):
#         super(ResNet, self).__init__()

#         # If we want to use the cfg in forward(), then we should make a copy
#         # of it and store it for later use:
#         # self.cfg = cfg.clone()

#         # Translate string names to implementations
#         stem_module = _STEM_MODULES[cfg.MODEL.RESNETS.STEM_FUNC]
#         stage_specs = _STAGE_SPECS[cfg.MODEL.BACKBONE.CONV_BODY]
#         transformation_module = _TRANSFORMATION_MODULES[cfg.MODEL.RESNETS.TRANS_FUNC]

#         # Construct the stem module
#         self.stem = stem_module(cfg)

#         # Constuct the specified ResNet stages
#         num_groups = cfg.MODEL.RESNETS.NUM_GROUPS
#         width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP
#         in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS
#         stage2_bottleneck_channels = num_groups * width_per_group
#         stage2_out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS
#         self.stages = []
#         self.return_features = {}
#         for stage_spec in stage_specs:
#             name = "layer" + str(stage_spec.index)
#             stage2_relative_factor = 2 ** (stage_spec.index - 1)
#             bottleneck_channels = stage2_bottleneck_channels * stage2_relative_factor
#             out_channels = stage2_out_channels * stage2_relative_factor
#             module = _make_stage(
#                 transformation_module,
#                 in_channels,
#                 bottleneck_channels,
#                 out_channels,
#                 stage_spec.block_count,
#                 num_groups,
#                 cfg.MODEL.RESNETS.STRIDE_IN_1X1,
#                 first_stride=int(stage_spec.index > 1) + 1,
#             )
#             in_channels = out_channels
#             self.add_module(name, module)
#             self.stages.append(name)
#             self.return_features[name] = stage_spec.return_features

#         # Optionally freeze (requires_grad=False) parts of the backbone
#         self._freeze_backbone(cfg.MODEL.BACKBONE.FREEZE_CONV_BODY_AT)

#     def _freeze_backbone(self, freeze_at):
#         for stage_index in range(freeze_at):
#             if stage_index == 0:
#                 m = self.stem  # stage 0 is the stem
#             else:
#                 m = getattr(self, "layer" + str(stage_index))
#             for p in m.parameters():
#                 p.requires_grad = False

#     def forward(self, x):
#         outputs = []
#         x = self.stem(x)
#         for stage_name in self.stages:
#             x = getattr(self, stage_name)(x)
#             if self.return_features[stage_name]:
#                 outputs.append(x)
#         return outputs


# class ResNetHead(nn.Module):
#     def __init__(
#         self,
#         block_module,
#         stages,
#         num_groups=1,
#         width_per_group=64,
#         stride_in_1x1=True,
#         stride_init=None,
#         res2_out_channels=256,
#     ):
#         super(ResNetHead, self).__init__()

#         stage2_relative_factor = 2 ** (stages[0].index - 1)
#         stage2_bottleneck_channels = num_groups * width_per_group
#         out_channels = res2_out_channels * stage2_relative_factor
#         in_channels = out_channels // 2
#         bottleneck_channels = stage2_bottleneck_channels * stage2_relative_factor

#         block_module = _TRANSFORMATION_MODULES[block_module]

#         self.stages = []
#         stride = stride_init
#         for stage in stages:
#             name = "layer" + str(stage.index)
#             if not stride:
#                 stride = int(stage.index > 1) + 1
#             module = _make_stage(
#                 block_module,
#                 in_channels,
#                 bottleneck_channels,
#                 out_channels,
#                 stage.block_count,
#                 num_groups,
#                 stride_in_1x1,
#                 first_stride=stride,
#             )
#             stride = None
#             self.add_module(name, module)
#             self.stages.append(name)

#     def forward(self, x):
#         for stage in self.stages:
#             x = getattr(self, stage)(x)
#         return x


# def _make_stage(
#     transformation_module,
#     in_channels,
#     bottleneck_channels,
#     out_channels,
#     block_count,
#     num_groups,
#     stride_in_1x1,
#     first_stride,
# ):
#     blocks = []
#     stride = first_stride
#     for _ in range(block_count):
#         blocks.append(
#             transformation_module(
#                 in_channels,
#                 bottleneck_channels,
#                 out_channels,
#                 num_groups,
#                 stride_in_1x1,
#                 stride,
#             )
#         )
#         stride = 1
#         in_channels = out_channels
#     return nn.Sequential(*blocks)


# class BottleneckWithFixedBatchNorm(nn.Module):
#     def __init__(
#         self,
#         in_channels,
#         bottleneck_channels,
#         out_channels,
#         num_groups=1,
#         stride_in_1x1=True,
#         stride=1,
#     ):
#         super(BottleneckWithFixedBatchNorm, self).__init__()

#         self.downsample = None
#         if in_channels != out_channels:
#             self.downsample = nn.Sequential(
#                 Conv2d(
#                     in_channels, out_channels, kernel_size=1, stride=stride, bias=False
#                 ),
#                 FrozenBatchNorm2d(out_channels),
#             )

#         # The original MSRA ResNet models have stride in the first 1x1 conv
#         # The subsequent fb.torch.resnet and Caffe2 ResNe[X]t implementations have
#         # stride in the 3x3 conv
#         stride_1x1, stride_3x3 = (stride, 1) if stride_in_1x1 else (1, stride)

#         self.conv1 = Conv2d(
#             in_channels,
#             bottleneck_channels,
#             kernel_size=1,
#             stride=stride_1x1,
#             bias=False,
#         )
#         self.bn1 = FrozenBatchNorm2d(bottleneck_channels)
#         # TODO: specify init for the above

#         self.conv2 = Conv2d(
#             bottleneck_channels,
#             bottleneck_channels,
#             kernel_size=3,
#             stride=stride_3x3,
#             padding=1,
#             bias=False,
#             groups=num_groups,
#         )
#         self.bn2 = FrozenBatchNorm2d(bottleneck_channels)

#         self.conv3 = Conv2d(
#             bottleneck_channels, out_channels, kernel_size=1, bias=False
#         )
#         self.bn3 = FrozenBatchNorm2d(out_channels)

#     def forward(self, x):
#         residual = x

#         out = self.conv1(x)
#         out = self.bn1(out)
#         out = F.relu_(out)

#         out = self.conv2(out)
#         out = self.bn2(out)
#         out = F.relu_(out)

#         out0 = self.conv3(out)
#         out = self.bn3(out0)

#         if self.downsample is not None:
#             residual = self.downsample(x)

#         out += residual
#         out = F.relu_(out)

#         return out


# class StemWithFixedBatchNorm(nn.Module):
#     def __init__(self, cfg):
#         super(StemWithFixedBatchNorm, self).__init__()

#         out_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS

#         self.conv1 = Conv2d(
#             3, out_channels, kernel_size=7, stride=2, padding=3, bias=False
#         )
#         self.bn1 = FrozenBatchNorm2d(out_channels)

#     def forward(self, x):
#         x = self.conv1(x)
#         x = self.bn1(x)
#         x = F.relu_(x)
#         x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
#         return x


# _TRANSFORMATION_MODULES = {"BottleneckWithFixedBatchNorm": BottleneckWithFixedBatchNorm}

# _STEM_MODULES = {"StemWithFixedBatchNorm": StemWithFixedBatchNorm}

# _STAGE_SPECS = {
#     "R-50-C4": ResNet50StagesTo4,
#     "R-50-C5": ResNet50StagesTo5,
#     "R-50-FPN": ResNet50FPNStagesTo5,
#     "R-101-FPN": ResNet101FPNStagesTo5,
# }


# def register_transformation_module(module_name, module):
#     _register_generic(_TRANSFORMATION_MODULES, module_name, module)


# def register_stem_module(module_name, module):
#     _register_generic(_STEM_MODULES, module_name, module)


# def register_stage_spec(stage_spec_name, stage_spec):
#     _register_generic(_STAGE_SPECS, stage_spec_name, stage_spec)


# def _register_generic(module_dict, module_name, module):
#     assert module_name not in module_dict
#     module_dict[module_name] = module



# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Variant of the resnet module that takes cfg as an argument.
Example usage. Strings may be specified in the config file.
    model = ResNet(
        "StemWithFixedBatchNorm",
        "BottleneckWithFixedBatchNorm",
        "ResNet50StagesTo4",
    )
OR:
    model = ResNet(
        "StemWithGN",
        "BottleneckWithGN",
        "ResNet50StagesTo4",
    )
Custom implementations may be written in user code and hooked in via the
`register_*` functions.
"""
from collections import namedtuple

import torch
import torch.nn.functional as F
from torch import nn

from maskrcnn_benchmark.layers import FrozenBatchNorm2d
from maskrcnn_benchmark.layers import Conv2d
from maskrcnn_benchmark.layers import DFConv2d
from maskrcnn_benchmark.modeling.make_layers import group_norm
from maskrcnn_benchmark.utils.registry import Registry


# ResNet stage specification
StageSpec = namedtuple(
    "StageSpec",
    [
        "index",  # Index of the stage, eg 1, 2, ..,. 5
        "block_count",  # Number of residual blocks in the stage
        "return_features",  # True => return the last feature map from this stage
    ],
)

# -----------------------------------------------------------------------------
# Standard ResNet models
# -----------------------------------------------------------------------------
# ResNet-50 (including all stages)
ResNet50StagesTo5 = tuple(
    StageSpec(index=i, block_count=c, return_features=r)
    for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, False), (4, 3, True))
)
# ResNet-50 up to stage 4 (excludes stage 5)
ResNet50StagesTo4 = tuple(
    StageSpec(index=i, block_count=c, return_features=r)
    for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 6, True))
)
# ResNet-101 (including all stages)
ResNet101StagesTo5 = tuple(
    StageSpec(index=i, block_count=c, return_features=r)
    for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 23, False), (4, 3, True))
)
# ResNet-101 up to stage 4 (excludes stage 5)
ResNet101StagesTo4 = tuple(
    StageSpec(index=i, block_count=c, return_features=r)
    for (i, c, r) in ((1, 3, False), (2, 4, False), (3, 23, True))
)
# ResNet-50-FPN (including all stages)
ResNet50FPNStagesTo5 = tuple(
    StageSpec(index=i, block_count=c, return_features=r)
    for (i, c, r) in ((1, 3, True), (2, 4, True), (3, 6, True), (4, 3, True))
)
# ResNet-101-FPN (including all stages)
ResNet101FPNStagesTo5 = tuple(
    StageSpec(index=i, block_count=c, return_features=r)
    for (i, c, r) in ((1, 3, True), (2, 4, True), (3, 23, True), (4, 3, True))
)
# ResNet-152-FPN (including all stages)
ResNet152FPNStagesTo5 = tuple(
    StageSpec(index=i, block_count=c, return_features=r)
    for (i, c, r) in ((1, 3, True), (2, 8, True), (3, 36, True), (4, 3, True))
)

class ResNet(nn.Module):
    def __init__(self, cfg):
        super(ResNet, self).__init__()

        # If we want to use the cfg in forward(), then we should make a copy
        # of it and store it for later use:
        # self.cfg = cfg.clone()

        # Translate string names to implementations
        stem_module = _STEM_MODULES[cfg.MODEL.RESNETS.STEM_FUNC]
        stage_specs = _STAGE_SPECS[cfg.MODEL.BACKBONE.CONV_BODY]
        transformation_module = _TRANSFORMATION_MODULES[cfg.MODEL.RESNETS.TRANS_FUNC]

        # Construct the stem module
        self.stem = stem_module(cfg)

        # Constuct the specified ResNet stages
        num_groups = cfg.MODEL.RESNETS.NUM_GROUPS
        width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP
        in_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS
        stage2_bottleneck_channels = num_groups * width_per_group
        stage2_out_channels = cfg.MODEL.RESNETS.RES2_OUT_CHANNELS
        self.stages = []
        self.return_features = {}
        for stage_spec in stage_specs:
            name = "layer" + str(stage_spec.index)
            stage2_relative_factor = 2 ** (stage_spec.index - 1)
            bottleneck_channels = stage2_bottleneck_channels * stage2_relative_factor
            out_channels = stage2_out_channels * stage2_relative_factor
            stage_with_dcn = cfg.MODEL.RESNETS.STAGE_WITH_DCN[stage_spec.index -1]
            module = _make_stage(
                transformation_module,
                in_channels,
                bottleneck_channels,
                out_channels,
                stage_spec.block_count,
                num_groups,
                cfg.MODEL.RESNETS.STRIDE_IN_1X1,
                first_stride=int(stage_spec.index > 1) + 1,
                dcn_config={
                    "stage_with_dcn": stage_with_dcn,
                    "with_modulated_dcn": cfg.MODEL.RESNETS.WITH_MODULATED_DCN,
                    "deformable_groups": cfg.MODEL.RESNETS.DEFORMABLE_GROUPS,
                }
            )
            in_channels = out_channels
            self.add_module(name, module)
            self.stages.append(name)
            self.return_features[name] = stage_spec.return_features

        # Optionally freeze (requires_grad=False) parts of the backbone
        self._freeze_backbone(cfg.MODEL.BACKBONE.FREEZE_CONV_BODY_AT)

    def _freeze_backbone(self, freeze_at):
        if freeze_at < 0:
            return
        for stage_index in range(freeze_at):
            if stage_index == 0:
                m = self.stem  # stage 0 is the stem
            else:
                m = getattr(self, "layer" + str(stage_index))
            for p in m.parameters():
                p.requires_grad = False

    def forward(self, x):
        outputs = []
        x = self.stem(x)
        for stage_name in self.stages:
            x = getattr(self, stage_name)(x)
            if self.return_features[stage_name]:
                outputs.append(x)
        return outputs


class ResNetHead(nn.Module):
    def __init__(
        self,
        block_module,
        stages,
        num_groups=1,
        width_per_group=64,
        stride_in_1x1=True,
        stride_init=None,
        res2_out_channels=256,
        dilation=1,
        dcn_config={}
    ):
        super(ResNetHead, self).__init__()

        stage2_relative_factor = 2 ** (stages[0].index - 1)
        stage2_bottleneck_channels = num_groups * width_per_group
        out_channels = res2_out_channels * stage2_relative_factor
        in_channels = out_channels // 2
        bottleneck_channels = stage2_bottleneck_channels * stage2_relative_factor

        block_module = _TRANSFORMATION_MODULES[block_module]

        self.stages = []
        stride = stride_init
        for stage in stages:
            name = "layer" + str(stage.index)
            if not stride:
                stride = int(stage.index > 1) + 1
            module = _make_stage(
                block_module,
                in_channels,
                bottleneck_channels,
                out_channels,
                stage.block_count,
                num_groups,
                stride_in_1x1,
                first_stride=stride,
                dilation=dilation,
                dcn_config=dcn_config
            )
            stride = None
            self.add_module(name, module)
            self.stages.append(name)
        self.out_channels = out_channels

    def forward(self, x):
        for stage in self.stages:
            x = getattr(self, stage)(x)
        return x


def _make_stage(
    transformation_module,
    in_channels,
    bottleneck_channels,
    out_channels,
    block_count,
    num_groups,
    stride_in_1x1,
    first_stride,
    dilation=1,
    dcn_config={}
):
    blocks = []
    stride = first_stride
    for _ in range(block_count):
        blocks.append(
            transformation_module(
                in_channels,
                bottleneck_channels,
                out_channels,
                num_groups,
                stride_in_1x1,
                stride,
                dilation=dilation,
                dcn_config=dcn_config
            )
        )
        stride = 1
        in_channels = out_channels
    return nn.Sequential(*blocks)


class Bottleneck(nn.Module):
    def __init__(
        self,
        in_channels,
        bottleneck_channels,
        out_channels,
        num_groups,
        stride_in_1x1,
        stride,
        dilation,
        norm_func,
        dcn_config
    ):
        super(Bottleneck, self).__init__()

        self.downsample = None
        if in_channels != out_channels:
            down_stride = stride if dilation == 1 else 1
            self.downsample = nn.Sequential(
                Conv2d(
                    in_channels, out_channels,
                    kernel_size=1, stride=down_stride, bias=False
                ),
                norm_func(out_channels),
            )
            for modules in [self.downsample,]:
                for l in modules.modules():
                    if isinstance(l, Conv2d):
                        nn.init.kaiming_uniform_(l.weight, a=1)

        if dilation > 1:
            stride = 1 # reset to be 1

        # The original MSRA ResNet models have stride in the first 1x1 conv
        # The subsequent fb.torch.resnet and Caffe2 ResNe[X]t implementations have
        # stride in the 3x3 conv
        stride_1x1, stride_3x3 = (stride, 1) if stride_in_1x1 else (1, stride)

        self.conv1 = Conv2d(
            in_channels,
            bottleneck_channels,
            kernel_size=1,
            stride=stride_1x1,
            bias=False,
        )
        self.bn1 = norm_func(bottleneck_channels)
        # TODO: specify init for the above
        with_dcn = dcn_config.get("stage_with_dcn", False)
        if with_dcn:
            deformable_groups = dcn_config.get("deformable_groups", 1)
            with_modulated_dcn = dcn_config.get("with_modulated_dcn", False)
            self.conv2 = DFConv2d(
                bottleneck_channels,
                bottleneck_channels,
                with_modulated_dcn=with_modulated_dcn,
                kernel_size=3,
                stride=stride_3x3,
                groups=num_groups,
                dilation=dilation,
                deformable_groups=deformable_groups,
                bias=False
            )
        else:
            self.conv2 = Conv2d(
                bottleneck_channels,
                bottleneck_channels,
                kernel_size=3,
                stride=stride_3x3,
                padding=dilation,
                bias=False,
                groups=num_groups,
                dilation=dilation
            )
            nn.init.kaiming_uniform_(self.conv2.weight, a=1)

        self.bn2 = norm_func(bottleneck_channels)

        self.conv3 = Conv2d(
            bottleneck_channels, out_channels, kernel_size=1, bias=False
        )
        self.bn3 = norm_func(out_channels)

        for l in [self.conv1, self.conv3,]:
            nn.init.kaiming_uniform_(l.weight, a=1)

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = F.relu_(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = F.relu_(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = F.relu_(out)

        return out


class BaseStem(nn.Module):
    def __init__(self, cfg, norm_func):
        super(BaseStem, self).__init__()

        out_channels = cfg.MODEL.RESNETS.STEM_OUT_CHANNELS

        self.conv1 = Conv2d(
            3, out_channels, kernel_size=7, stride=2, padding=3, bias=False
        )
        self.bn1 = norm_func(out_channels)

        for l in [self.conv1,]:
            nn.init.kaiming_uniform_(l.weight, a=1)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = F.relu_(x)
        x = F.max_pool2d(x, kernel_size=3, stride=2, padding=1)
        return x


class BottleneckWithFixedBatchNorm(Bottleneck):
    def __init__(
        self,
        in_channels,
        bottleneck_channels,
        out_channels,
        num_groups=1,
        stride_in_1x1=True,
        stride=1,
        dilation=1,
        dcn_config={}
    ):
        super(BottleneckWithFixedBatchNorm, self).__init__(
            in_channels=in_channels,
            bottleneck_channels=bottleneck_channels,
            out_channels=out_channels,
            num_groups=num_groups,
            stride_in_1x1=stride_in_1x1,
            stride=stride,
            dilation=dilation,
            norm_func=FrozenBatchNorm2d,
            dcn_config=dcn_config
        )


class StemWithFixedBatchNorm(BaseStem):
    def __init__(self, cfg):
        super(StemWithFixedBatchNorm, self).__init__(
            cfg, norm_func=FrozenBatchNorm2d
        )


class BottleneckWithGN(Bottleneck):
    def __init__(
        self,
        in_channels,
        bottleneck_channels,
        out_channels,
        num_groups=1,
        stride_in_1x1=True,
        stride=1,
        dilation=1,
        dcn_config={}
    ):
        super(BottleneckWithGN, self).__init__(
            in_channels=in_channels,
            bottleneck_channels=bottleneck_channels,
            out_channels=out_channels,
            num_groups=num_groups,
            stride_in_1x1=stride_in_1x1,
            stride=stride,
            dilation=dilation,
            norm_func=group_norm,
            dcn_config=dcn_config
        )


class StemWithGN(BaseStem):
    def __init__(self, cfg):
        super(StemWithGN, self).__init__(cfg, norm_func=group_norm)


_TRANSFORMATION_MODULES = Registry({
    "BottleneckWithFixedBatchNorm": BottleneckWithFixedBatchNorm,
    "BottleneckWithGN": BottleneckWithGN,
})

_STEM_MODULES = Registry({
    "StemWithFixedBatchNorm": StemWithFixedBatchNorm,
    "StemWithGN": StemWithGN,
})

_STAGE_SPECS = Registry({
    "R-50-C4": ResNet50StagesTo4,
    "R-50-C5": ResNet50StagesTo5,
    "R-101-C4": ResNet101StagesTo4,
    "R-101-C5": ResNet101StagesTo5,
    "R-50-FPN": ResNet50FPNStagesTo5,
    "R-50-FPN-RETINANET": ResNet50FPNStagesTo5,
    "R-101-FPN": ResNet101FPNStagesTo5,
    "R-101-FPN-RETINANET": ResNet101FPNStagesTo5,
    "R-152-FPN": ResNet152FPNStagesTo5,
})