inception.py 15.7 KB
Newer Older
1
2
from __future__ import division

3
from collections import namedtuple
4
import warnings
5
6
7
import torch
import torch.nn as nn
import torch.nn.functional as F
8
from torch.jit.annotations import Optional
9
from torch import Tensor
10
from .utils import load_state_dict_from_url
11
12


13
__all__ = ['Inception3', 'inception_v3', 'InceptionOutputs', '_InceptionOutputs']
14
15
16
17
18
19
20


model_urls = {
    # Inception v3 ported from TensorFlow
    'inception_v3_google': 'https://download.pytorch.org/models/inception_v3_google-1a9a5a14.pth',
}

21
22
23
24
25
26
InceptionOutputs = namedtuple('InceptionOutputs', ['logits', 'aux_logits'])
InceptionOutputs.__annotations__ = {'logits': torch.Tensor, 'aux_logits': Optional[torch.Tensor]}

# Script annotations failed with _GoogleNetOutputs = namedtuple ...
# _InceptionOutputs set here for backwards compat
_InceptionOutputs = InceptionOutputs
27

28

29
def inception_v3(pretrained=False, progress=True, **kwargs):
30
31
32
    r"""Inception v3 model architecture from
    `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_.

33
34
    .. note::
        **Important**: In contrast to the other models the inception_v3 expects tensors with a size of
35
        N x 3 x 299 x 299, so ensure your images are sized accordingly.
36

37
38
    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
39
        progress (bool): If True, displays a progress bar of the download to stderr
40
41
        aux_logits (bool): If True, add an auxiliary branch that can improve training.
            Default: *True*
42
        transform_input (bool): If True, preprocesses the input according to the method with which it
43
            was trained on ImageNet. Default: *False*
44
45
46
47
    """
    if pretrained:
        if 'transform_input' not in kwargs:
            kwargs['transform_input'] = True
48
49
50
51
52
        if 'aux_logits' in kwargs:
            original_aux_logits = kwargs['aux_logits']
            kwargs['aux_logits'] = True
        else:
            original_aux_logits = True
53
        model = Inception3(**kwargs)
54
55
56
        state_dict = load_state_dict_from_url(model_urls['inception_v3_google'],
                                              progress=progress)
        model.load_state_dict(state_dict)
57
58
59
        if not original_aux_logits:
            model.aux_logits = False
            del model.AuxLogits
60
61
62
63
64
65
        return model

    return Inception3(**kwargs)


class Inception3(nn.Module):
soumith's avatar
soumith committed
66

67
    def __init__(self, num_classes=1000, aux_logits=True, transform_input=False,
68
                 inception_blocks=None, init_weights=True):
69
        super(Inception3, self).__init__()
70
71
72
73
74
75
76
77
78
79
80
81
82
83
        if inception_blocks is None:
            inception_blocks = [
                BasicConv2d, InceptionA, InceptionB, InceptionC,
                InceptionD, InceptionE, InceptionAux
            ]
        assert len(inception_blocks) == 7
        conv_block = inception_blocks[0]
        inception_a = inception_blocks[1]
        inception_b = inception_blocks[2]
        inception_c = inception_blocks[3]
        inception_d = inception_blocks[4]
        inception_e = inception_blocks[5]
        inception_aux = inception_blocks[6]

84
85
        self.aux_logits = aux_logits
        self.transform_input = transform_input
86
87
88
89
90
91
92
93
94
95
96
97
98
        self.Conv2d_1a_3x3 = conv_block(3, 32, kernel_size=3, stride=2)
        self.Conv2d_2a_3x3 = conv_block(32, 32, kernel_size=3)
        self.Conv2d_2b_3x3 = conv_block(32, 64, kernel_size=3, padding=1)
        self.Conv2d_3b_1x1 = conv_block(64, 80, kernel_size=1)
        self.Conv2d_4a_3x3 = conv_block(80, 192, kernel_size=3)
        self.Mixed_5b = inception_a(192, pool_features=32)
        self.Mixed_5c = inception_a(256, pool_features=64)
        self.Mixed_5d = inception_a(288, pool_features=64)
        self.Mixed_6a = inception_b(288)
        self.Mixed_6b = inception_c(768, channels_7x7=128)
        self.Mixed_6c = inception_c(768, channels_7x7=160)
        self.Mixed_6d = inception_c(768, channels_7x7=160)
        self.Mixed_6e = inception_c(768, channels_7x7=192)
99
        if aux_logits:
100
101
102
103
            self.AuxLogits = inception_aux(768, num_classes)
        self.Mixed_7a = inception_d(768)
        self.Mixed_7b = inception_e(1280)
        self.Mixed_7c = inception_e(2048)
104
        self.fc = nn.Linear(2048, num_classes)
105
106
107
108
109
110
111
112
113
114
115
116
117
        if init_weights:
            for m in self.modules():
                if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
                    import scipy.stats as stats
                    stddev = m.stddev if hasattr(m, 'stddev') else 0.1
                    X = stats.truncnorm(-2, 2, scale=stddev)
                    values = torch.as_tensor(X.rvs(m.weight.numel()), dtype=m.weight.dtype)
                    values = values.view(m.weight.size())
                    with torch.no_grad():
                        m.weight.copy_(values)
                elif isinstance(m, nn.BatchNorm2d):
                    nn.init.constant_(m.weight, 1)
                    nn.init.constant_(m.bias, 0)
118

119
    def _transform_input(self, x):
120
        if self.transform_input:
121
122
123
124
            x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5
            x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5
            x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5
            x = torch.cat((x_ch0, x_ch1, x_ch2), 1)
125
126
127
        return x

    def _forward(self, x):
128
        # N x 3 x 299 x 299
129
        x = self.Conv2d_1a_3x3(x)
130
        # N x 32 x 149 x 149
131
        x = self.Conv2d_2a_3x3(x)
132
        # N x 32 x 147 x 147
133
        x = self.Conv2d_2b_3x3(x)
134
        # N x 64 x 147 x 147
135
        x = F.max_pool2d(x, kernel_size=3, stride=2)
136
        # N x 64 x 73 x 73
137
        x = self.Conv2d_3b_1x1(x)
138
        # N x 80 x 73 x 73
139
        x = self.Conv2d_4a_3x3(x)
140
        # N x 192 x 71 x 71
141
        x = F.max_pool2d(x, kernel_size=3, stride=2)
142
        # N x 192 x 35 x 35
143
        x = self.Mixed_5b(x)
144
        # N x 256 x 35 x 35
145
        x = self.Mixed_5c(x)
surgan12's avatar
surgan12 committed
146
        # N x 288 x 35 x 35
147
        x = self.Mixed_5d(x)
148
        # N x 288 x 35 x 35
149
        x = self.Mixed_6a(x)
150
        # N x 768 x 17 x 17
151
        x = self.Mixed_6b(x)
152
        # N x 768 x 17 x 17
153
        x = self.Mixed_6c(x)
154
        # N x 768 x 17 x 17
155
        x = self.Mixed_6d(x)
156
        # N x 768 x 17 x 17
157
        x = self.Mixed_6e(x)
158
        # N x 768 x 17 x 17
159
160
        aux_defined = self.training and self.aux_logits
        if aux_defined:
161
            aux = self.AuxLogits(x)
162
163
        else:
            aux = None
164
        # N x 768 x 17 x 17
165
        x = self.Mixed_7a(x)
166
        # N x 1280 x 8 x 8
167
        x = self.Mixed_7b(x)
168
        # N x 2048 x 8 x 8
169
        x = self.Mixed_7c(x)
170
        # N x 2048 x 8 x 8
171
172
        # Adaptive average pooling
        x = F.adaptive_avg_pool2d(x, (1, 1))
173
        # N x 2048 x 1 x 1
174
        x = F.dropout(x, training=self.training)
175
        # N x 2048 x 1 x 1
176
        x = torch.flatten(x, 1)
177
        # N x 2048
178
        x = self.fc(x)
179
        # N x 1000 (num_classes)
180
        return x, aux
181
182
183

    @torch.jit.unused
    def eager_outputs(self, x, aux):
184
        # type: (Tensor, Optional[Tensor]) -> InceptionOutputs
185
        if self.training and self.aux_logits:
186
            return InceptionOutputs(x, aux)
187
188
189
190
191
192
193
194
195
196
197
198
199
        else:
            return x

    def forward(self, x):
        x = self._transform_input(x)
        x, aux = self._forward(x)
        aux_defined = self.training and self.aux_logits
        if torch.jit.is_scripting():
            if not aux_defined:
                warnings.warn("Scripted Inception3 always returns Inception3 Tuple")
            return InceptionOutputs(x, aux)
        else:
            return self.eager_outputs(x, aux)
200
201
202


class InceptionA(nn.Module):
soumith's avatar
soumith committed
203

204
    def __init__(self, in_channels, pool_features, conv_block=None):
205
        super(InceptionA, self).__init__()
206
207
208
        if conv_block is None:
            conv_block = BasicConv2d
        self.branch1x1 = conv_block(in_channels, 64, kernel_size=1)
209

210
211
        self.branch5x5_1 = conv_block(in_channels, 48, kernel_size=1)
        self.branch5x5_2 = conv_block(48, 64, kernel_size=5, padding=2)
212

213
214
215
        self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1)
        self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1)
        self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, padding=1)
216

217
        self.branch_pool = conv_block(in_channels, pool_features, kernel_size=1)
218

219
    def _forward(self, x):
220
221
222
223
224
225
226
227
228
229
230
231
232
        branch1x1 = self.branch1x1(x)

        branch5x5 = self.branch5x5_1(x)
        branch5x5 = self.branch5x5_2(branch5x5)

        branch3x3dbl = self.branch3x3dbl_1(x)
        branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
        branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)

        branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool = self.branch_pool(branch_pool)

        outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
233
234
235
236
        return outputs

    def forward(self, x):
        outputs = self._forward(x)
237
238
239
240
        return torch.cat(outputs, 1)


class InceptionB(nn.Module):
soumith's avatar
soumith committed
241

242
    def __init__(self, in_channels, conv_block=None):
243
        super(InceptionB, self).__init__()
244
245
246
        if conv_block is None:
            conv_block = BasicConv2d
        self.branch3x3 = conv_block(in_channels, 384, kernel_size=3, stride=2)
247

248
249
250
        self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1)
        self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1)
        self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, stride=2)
251

252
    def _forward(self, x):
253
254
255
256
257
258
259
260
261
        branch3x3 = self.branch3x3(x)

        branch3x3dbl = self.branch3x3dbl_1(x)
        branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
        branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)

        branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)

        outputs = [branch3x3, branch3x3dbl, branch_pool]
262
263
264
265
        return outputs

    def forward(self, x):
        outputs = self._forward(x)
266
267
268
269
        return torch.cat(outputs, 1)


class InceptionC(nn.Module):
soumith's avatar
soumith committed
270

271
    def __init__(self, in_channels, channels_7x7, conv_block=None):
272
        super(InceptionC, self).__init__()
273
274
275
        if conv_block is None:
            conv_block = BasicConv2d
        self.branch1x1 = conv_block(in_channels, 192, kernel_size=1)
276
277

        c7 = channels_7x7
278
279
280
        self.branch7x7_1 = conv_block(in_channels, c7, kernel_size=1)
        self.branch7x7_2 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3))
        self.branch7x7_3 = conv_block(c7, 192, kernel_size=(7, 1), padding=(3, 0))
281

282
283
284
285
286
        self.branch7x7dbl_1 = conv_block(in_channels, c7, kernel_size=1)
        self.branch7x7dbl_2 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0))
        self.branch7x7dbl_3 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3))
        self.branch7x7dbl_4 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0))
        self.branch7x7dbl_5 = conv_block(c7, 192, kernel_size=(1, 7), padding=(0, 3))
287

288
        self.branch_pool = conv_block(in_channels, 192, kernel_size=1)
289

290
    def _forward(self, x):
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
        branch1x1 = self.branch1x1(x)

        branch7x7 = self.branch7x7_1(x)
        branch7x7 = self.branch7x7_2(branch7x7)
        branch7x7 = self.branch7x7_3(branch7x7)

        branch7x7dbl = self.branch7x7dbl_1(x)
        branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
        branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
        branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
        branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)

        branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool = self.branch_pool(branch_pool)

        outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
307
308
309
310
        return outputs

    def forward(self, x):
        outputs = self._forward(x)
311
312
313
314
        return torch.cat(outputs, 1)


class InceptionD(nn.Module):
soumith's avatar
soumith committed
315

316
    def __init__(self, in_channels, conv_block=None):
317
        super(InceptionD, self).__init__()
318
319
320
321
        if conv_block is None:
            conv_block = BasicConv2d
        self.branch3x3_1 = conv_block(in_channels, 192, kernel_size=1)
        self.branch3x3_2 = conv_block(192, 320, kernel_size=3, stride=2)
322

323
324
325
326
        self.branch7x7x3_1 = conv_block(in_channels, 192, kernel_size=1)
        self.branch7x7x3_2 = conv_block(192, 192, kernel_size=(1, 7), padding=(0, 3))
        self.branch7x7x3_3 = conv_block(192, 192, kernel_size=(7, 1), padding=(3, 0))
        self.branch7x7x3_4 = conv_block(192, 192, kernel_size=3, stride=2)
327

328
    def _forward(self, x):
329
330
331
332
333
334
335
336
337
338
        branch3x3 = self.branch3x3_1(x)
        branch3x3 = self.branch3x3_2(branch3x3)

        branch7x7x3 = self.branch7x7x3_1(x)
        branch7x7x3 = self.branch7x7x3_2(branch7x7x3)
        branch7x7x3 = self.branch7x7x3_3(branch7x7x3)
        branch7x7x3 = self.branch7x7x3_4(branch7x7x3)

        branch_pool = F.max_pool2d(x, kernel_size=3, stride=2)
        outputs = [branch3x3, branch7x7x3, branch_pool]
339
340
341
342
        return outputs

    def forward(self, x):
        outputs = self._forward(x)
343
344
345
346
        return torch.cat(outputs, 1)


class InceptionE(nn.Module):
soumith's avatar
soumith committed
347

348
    def __init__(self, in_channels, conv_block=None):
349
        super(InceptionE, self).__init__()
350
351
352
        if conv_block is None:
            conv_block = BasicConv2d
        self.branch1x1 = conv_block(in_channels, 320, kernel_size=1)
353

354
355
356
        self.branch3x3_1 = conv_block(in_channels, 384, kernel_size=1)
        self.branch3x3_2a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1))
        self.branch3x3_2b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0))
357

358
359
360
361
        self.branch3x3dbl_1 = conv_block(in_channels, 448, kernel_size=1)
        self.branch3x3dbl_2 = conv_block(448, 384, kernel_size=3, padding=1)
        self.branch3x3dbl_3a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1))
        self.branch3x3dbl_3b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0))
362

363
        self.branch_pool = conv_block(in_channels, 192, kernel_size=1)
364

365
    def _forward(self, x):
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
        branch1x1 = self.branch1x1(x)

        branch3x3 = self.branch3x3_1(x)
        branch3x3 = [
            self.branch3x3_2a(branch3x3),
            self.branch3x3_2b(branch3x3),
        ]
        branch3x3 = torch.cat(branch3x3, 1)

        branch3x3dbl = self.branch3x3dbl_1(x)
        branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
        branch3x3dbl = [
            self.branch3x3dbl_3a(branch3x3dbl),
            self.branch3x3dbl_3b(branch3x3dbl),
        ]
        branch3x3dbl = torch.cat(branch3x3dbl, 1)

        branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1)
        branch_pool = self.branch_pool(branch_pool)

        outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
387
388
389
390
        return outputs

    def forward(self, x):
        outputs = self._forward(x)
391
392
393
394
        return torch.cat(outputs, 1)


class InceptionAux(nn.Module):
soumith's avatar
soumith committed
395

396
    def __init__(self, in_channels, num_classes, conv_block=None):
397
        super(InceptionAux, self).__init__()
398
399
400
401
        if conv_block is None:
            conv_block = BasicConv2d
        self.conv0 = conv_block(in_channels, 128, kernel_size=1)
        self.conv1 = conv_block(128, 768, kernel_size=5)
402
403
404
405
406
        self.conv1.stddev = 0.01
        self.fc = nn.Linear(768, num_classes)
        self.fc.stddev = 0.001

    def forward(self, x):
407
        # N x 768 x 17 x 17
408
        x = F.avg_pool2d(x, kernel_size=5, stride=3)
409
        # N x 768 x 5 x 5
410
        x = self.conv0(x)
411
        # N x 128 x 5 x 5
412
        x = self.conv1(x)
413
        # N x 768 x 1 x 1
414
415
        # Adaptive average pooling
        x = F.adaptive_avg_pool2d(x, (1, 1))
416
        # N x 768 x 1 x 1
417
        x = torch.flatten(x, 1)
418
        # N x 768
419
        x = self.fc(x)
420
        # N x 1000
421
422
423
424
        return x


class BasicConv2d(nn.Module):
soumith's avatar
soumith committed
425

426
427
428
429
430
431
432
433
434
    def __init__(self, in_channels, out_channels, **kwargs):
        super(BasicConv2d, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)
        self.bn = nn.BatchNorm2d(out_channels, eps=0.001)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        return F.relu(x, inplace=True)