resnet.py 10.2 KB
Newer Older
1
import torch.nn as nn
2
from .utils import load_state_dict_from_url
3
4
5


__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
6
           'resnet152', 'resnext50_32x4d', 'resnext101_32x8d']
7
8
9


model_urls = {
10
11
12
13
14
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
15
16
17
}


18
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
19
    """3x3 convolution with padding"""
20
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
21
                     padding=dilation, groups=groups, bias=False, dilation=dilation)
22
23


24
25
26
27
28
def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)


Soumith Chintala's avatar
Soumith Chintala committed
29
class BasicBlock(nn.Module):
30
31
    expansion = 1

32
    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
33
                 base_width=64, dilation=1, norm_layer=None):
34
        super(BasicBlock, self).__init__()
35
36
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
37
38
        if groups != 1 or base_width != 64:
            raise ValueError('BasicBlock only supports groups=1 and base_width=64')
39
40
        if dilation > 1:
            raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
41
        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
42
        self.conv1 = conv3x3(inplanes, planes, stride)
43
        self.bn1 = norm_layer(planes)
44
45
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
46
        self.bn2 = norm_layer(planes)
47
48
49
50
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
51
        identity = x
52
53
54
55
56
57
58
59
60

        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:
61
            identity = self.downsample(x)
62

63
        out += identity
64
65
66
67
68
        out = self.relu(out)

        return out


Soumith Chintala's avatar
Soumith Chintala committed
69
class Bottleneck(nn.Module):
70
71
    expansion = 4

72
    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
73
                 base_width=64, dilation=1, norm_layer=None):
74
        super(Bottleneck, self).__init__()
75
76
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
77
        width = int(planes * (base_width / 64.)) * groups
78
        # Both self.conv2 and self.downsample layers downsample the input when stride != 1
79
80
        self.conv1 = conv1x1(inplanes, width)
        self.bn1 = norm_layer(width)
81
        self.conv2 = conv3x3(width, width, stride, groups, dilation)
82
83
        self.bn2 = norm_layer(width)
        self.conv3 = conv1x1(width, planes * self.expansion)
84
        self.bn3 = norm_layer(planes * self.expansion)
85
86
87
88
89
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
90
        identity = x
91
92
93
94
95
96
97
98
99
100
101
102
103

        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:
104
            identity = self.downsample(x)
105

106
        out += identity
107
108
109
110
111
        out = self.relu(out)

        return out


Soumith Chintala's avatar
Soumith Chintala committed
112
class ResNet(nn.Module):
113

114
    def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
115
116
                 groups=1, width_per_group=64, replace_stride_with_dilation=None,
                 norm_layer=None):
117
        super(ResNet, self).__init__()
118
119
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
120
        self._norm_layer = norm_layer
121
122

        self.inplanes = 64
123
124
125
126
127
128
129
130
        self.dilation = 1
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None "
                             "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
131
132
133
        self.groups = groups
        self.base_width = width_per_group
        self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
134
                               bias=False)
135
        self.bn1 = norm_layer(self.inplanes)
136
137
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
138
139
140
141
142
143
144
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])
145
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
146
        self.fc = nn.Linear(512 * block.expansion, num_classes)
147
148
149

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
150
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
151
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
152
153
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
154

155
156
157
158
159
160
161
162
163
164
        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)
                elif isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)

165
166
    def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
        norm_layer = self._norm_layer
167
        downsample = None
168
169
170
171
        previous_dilation = self.dilation
        if dilate:
            self.dilation *= stride
            stride = 1
172
173
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
174
                conv1x1(self.inplanes, planes * block.expansion, stride),
175
                norm_layer(planes * block.expansion),
176
177
178
            )

        layers = []
179
        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
180
                            self.base_width, previous_dilation, norm_layer))
181
        self.inplanes = planes * block.expansion
182
        for _ in range(1, blocks):
183
            layers.append(block(self.inplanes, planes, groups=self.groups,
184
185
                                base_width=self.base_width, dilation=self.dilation,
                                norm_layer=norm_layer))
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return x


207
208
209
210
211
212
213
214
215
216
def _resnet(arch, inplanes, planes, pretrained, progress, **kwargs):
    model = ResNet(inplanes, planes, **kwargs)
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model


def resnet18(pretrained=False, progress=True, **kwargs):
217
218
219
220
    """Constructs a ResNet-18 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
221
        progress (bool): If True, displays a progress bar of the download to stderr
222
    """
223
224
    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
                   **kwargs)
225
226


227
def resnet34(pretrained=False, progress=True, **kwargs):
228
229
230
231
    """Constructs a ResNet-34 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
232
        progress (bool): If True, displays a progress bar of the download to stderr
233
    """
234
235
    return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
                   **kwargs)
236
237


238
def resnet50(pretrained=False, progress=True, **kwargs):
239
240
241
242
    """Constructs a ResNet-50 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
243
        progress (bool): If True, displays a progress bar of the download to stderr
244
    """
245
246
    return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
                   **kwargs)
247
248


249
def resnet101(pretrained=False, progress=True, **kwargs):
250
251
252
253
    """Constructs a ResNet-101 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
254
        progress (bool): If True, displays a progress bar of the download to stderr
255
    """
256
257
    return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
                   **kwargs)
258
259


260
def resnet152(pretrained=False, progress=True, **kwargs):
261
262
263
264
    """Constructs a ResNet-152 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
265
        progress (bool): If True, displays a progress bar of the download to stderr
266
    """
267
268
    return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
                   **kwargs)
269
270


271
272
273
274
275
def resnext50_32x4d(**kwargs):
    kwargs['groups'] = 32
    kwargs['width_per_group'] = 4
    return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
                   pretrained=False, progress=True, **kwargs)
276
277


278
279
280
281
282
def resnext101_32x8d(**kwargs):
    kwargs['groups'] = 32
    kwargs['width_per_group'] = 8
    return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
                   pretrained=False, progress=True, **kwargs)