resnext.py 5.58 KB
Newer Older
pangjm's avatar
pangjm committed
1
2
3
4
5
import math

import torch.nn as nn

from .resnet import ResNet
pangjm's avatar
pangjm committed
6
from .resnet import Bottleneck as _Bottleneck
ThangVu's avatar
ThangVu committed
7
from ..utils import build_norm_layer
pangjm's avatar
pangjm committed
8
9


pangjm's avatar
pangjm committed
10
class Bottleneck(_Bottleneck):
pangjm's avatar
pangjm committed
11

pangjm's avatar
pangjm committed
12
    def __init__(self, *args, groups=1, base_width=4, **kwargs):
pangjm's avatar
pangjm committed
13
        """Bottleneck block for ResNeXt.
pangjm's avatar
pangjm committed
14
15
16
        If style is "pytorch", the stride-two layer is the 3x3 conv layer,
        if it is "caffe", the stride-two layer is the first 1x1 conv layer.
        """
pangjm's avatar
pangjm committed
17
        super(Bottleneck, self).__init__(*args, **kwargs)
pangjm's avatar
pangjm committed
18

pangjm's avatar
pangjm committed
19
        if groups == 1:
pangjm's avatar
pangjm committed
20
            width = self.planes
pangjm's avatar
pangjm committed
21
        else:
pangjm's avatar
pangjm committed
22
            width = math.floor(self.planes * (base_width / 64)) * groups
pangjm's avatar
pangjm committed
23

ThangVu's avatar
ThangVu committed
24
25
26
27
28
29
30
31
32
33
34
35
36
        self.norm1_name, norm1 = build_norm_layer(self.normalize,
                                                  width,
                                                  postfix=1)
        self.norm2_name, norm2 = build_norm_layer(self.normalize,
                                                  width,
                                                  postfix=2)
        self.norm3_name, norm3 = build_norm_layer(self.normalize,
                                                  self.planes * self.expansion,
                                                  postfix=3)
        self.add_module(self.norm1_name, norm1)
        self.add_module(self.norm2_name, norm2)
        self.add_module(self.norm3_name, norm3)

pangjm's avatar
pangjm committed
37
        self.conv1 = nn.Conv2d(
pangjm's avatar
pangjm committed
38
39
40
41
42
            self.inplanes,
            width,
            kernel_size=1,
            stride=self.conv1_stride,
            bias=False)
pangjm's avatar
pangjm committed
43
44
45
46
        self.conv2 = nn.Conv2d(
            width,
            width,
            kernel_size=3,
pangjm's avatar
pangjm committed
47
48
49
            stride=self.conv2_stride,
            padding=self.dilation,
            dilation=self.dilation,
pangjm's avatar
pangjm committed
50
51
52
            groups=groups,
            bias=False)
        self.conv3 = nn.Conv2d(
pangjm's avatar
pangjm committed
53
            width, self.planes * self.expansion, kernel_size=1, bias=False)
pangjm's avatar
pangjm committed
54
55
56
57
58
59
60
61
62
63
64


def make_res_layer(block,
                   inplanes,
                   planes,
                   blocks,
                   stride=1,
                   dilation=1,
                   groups=1,
                   base_width=4,
                   style='pytorch',
ThangVu's avatar
ThangVu committed
65
66
                   with_cp=False,
                   normalize=dict(type='BN')):
pangjm's avatar
pangjm committed
67
68
69
70
71
72
73
74
75
    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),
ThangVu's avatar
ThangVu committed
76
            build_norm_layer(normalize, planes * block.expansion)[1],
pangjm's avatar
pangjm committed
77
78
79
80
81
82
83
        )

    layers = []
    layers.append(
        block(
            inplanes,
            planes,
pangjm's avatar
pangjm committed
84
85
86
            stride=stride,
            dilation=dilation,
            downsample=downsample,
pangjm's avatar
pangjm committed
87
88
89
            groups=groups,
            base_width=base_width,
            style=style,
ThangVu's avatar
ThangVu committed
90
91
            with_cp=with_cp,
            normalize=normalize))
pangjm's avatar
pangjm committed
92
93
94
95
96
97
    inplanes = planes * block.expansion
    for i in range(1, blocks):
        layers.append(
            block(
                inplanes,
                planes,
pangjm's avatar
pangjm committed
98
99
                stride=1,
                dilation=dilation,
pangjm's avatar
pangjm committed
100
101
102
                groups=groups,
                base_width=base_width,
                style=style,
ThangVu's avatar
ThangVu committed
103
104
                with_cp=with_cp,
                normalize=normalize))
pangjm's avatar
pangjm committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124

    return nn.Sequential(*layers)


class ResNeXt(ResNet):
    """ResNeXt backbone.

    Args:
        depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.
        num_stages (int): Resnet stages, normally 4.
        groups (int): Group of resnext.
        base_width (int): Base width of resnext.
        strides (Sequence[int]): Strides of the first block of each stage.
        dilations (Sequence[int]): Dilation of each stage.
        out_indices (Sequence[int]): Output from which stages.
        style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
            layer is the 3x3 conv layer, otherwise the stride-two layer is
            the first 1x1 conv layer.
        frozen_stages (int): Stages to be frozen (all param fixed). -1 means
            not freezing any parameters.
ThangVu's avatar
ThangVu committed
125
126
127
        normalize (dict): dictionary to construct norm layer. Additionally,
            eval mode and gradent freezing are controlled by
            eval (bool) and frozen (bool) respectively.
pangjm's avatar
pangjm committed
128
129
130
131
132
133
134
135
136
137
        with_cp (bool): Use checkpoint or not. Using checkpoint will save some
            memory while slowing down the training speed.
    """

    arch_settings = {
        50: (Bottleneck, (3, 4, 6, 3)),
        101: (Bottleneck, (3, 4, 23, 3)),
        152: (Bottleneck, (3, 8, 36, 3))
    }

pangjm's avatar
pangjm committed
138
139
    def __init__(self, groups=1, base_width=4, **kwargs):
        super(ResNeXt, self).__init__(**kwargs)
pangjm's avatar
pangjm committed
140
141
142
143
144
145
        self.groups = groups
        self.base_width = base_width

        self.inplanes = 64
        self.res_layers = []
        for i, num_blocks in enumerate(self.stage_blocks):
pangjm's avatar
pangjm committed
146
147
            stride = self.strides[i]
            dilation = self.dilations[i]
pangjm's avatar
pangjm committed
148
149
150
151
152
153
154
155
156
157
158
            planes = 64 * 2**i
            res_layer = make_res_layer(
                self.block,
                self.inplanes,
                planes,
                num_blocks,
                stride=stride,
                dilation=dilation,
                groups=self.groups,
                base_width=self.base_width,
                style=self.style,
ThangVu's avatar
ThangVu committed
159
160
                with_cp=self.with_cp,
                normalize=self.normalize)
pangjm's avatar
pangjm committed
161
162
163
164
            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)
ThangVu's avatar
ThangVu committed
165
166

        self._freeze_stages()