shufflenetv2.py 7.43 KB
Newer Older
Bar's avatar
Bar committed
1
2
import torch
import torch.nn as nn
ekka's avatar
ekka committed
3
from .utils import load_state_dict_from_url
Bar's avatar
Bar committed
4

5
6
7
8
9

__all__ = [
    'ShuffleNetV2', 'shufflenet_v2_x0_5', 'shufflenet_v2_x1_0',
    'shufflenet_v2_x1_5', 'shufflenet_v2_x2_0'
]
Bar's avatar
Bar committed
10
11

model_urls = {
12
13
    'shufflenetv2_x0.5': 'https://download.pytorch.org/models/shufflenetv2_x0.5-f707e7126e.pth',
    'shufflenetv2_x1.0': 'https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth',
Bar's avatar
Bar committed
14
15
16
17
18
19
    'shufflenetv2_x1.5': None,
    'shufflenetv2_x2.0': None,
}


def channel_shuffle(x, groups):
20
    # type: (torch.Tensor, int) -> torch.Tensor
Bar's avatar
Bar committed
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
    batchsize, num_channels, height, width = x.data.size()
    channels_per_group = num_channels // groups

    # reshape
    x = x.view(batchsize, groups,
               channels_per_group, height, width)

    x = torch.transpose(x, 1, 2).contiguous()

    # flatten
    x = x.view(batchsize, -1, height, width)

    return x


class InvertedResidual(nn.Module):
    def __init__(self, inp, oup, stride):
        super(InvertedResidual, self).__init__()

        if not (1 <= stride <= 3):
            raise ValueError('illegal stride value')
        self.stride = stride

        branch_features = oup // 2
        assert (self.stride != 1) or (inp == branch_features << 1)

        if self.stride > 1:
            self.branch1 = nn.Sequential(
49
                self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1),
Bar's avatar
Bar committed
50
                nn.BatchNorm2d(inp),
51
                nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
Bar's avatar
Bar committed
52
53
54
                nn.BatchNorm2d(branch_features),
                nn.ReLU(inplace=True),
            )
55
56
        else:
            self.branch1 = nn.Sequential()
Bar's avatar
Bar committed
57
58

        self.branch2 = nn.Sequential(
59
60
            nn.Conv2d(inp if (self.stride > 1) else branch_features,
                      branch_features, kernel_size=1, stride=1, padding=0, bias=False),
Bar's avatar
Bar committed
61
62
            nn.BatchNorm2d(branch_features),
            nn.ReLU(inplace=True),
63
            self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),
Bar's avatar
Bar committed
64
            nn.BatchNorm2d(branch_features),
65
            nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
Bar's avatar
Bar committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
            nn.BatchNorm2d(branch_features),
            nn.ReLU(inplace=True),
        )

    @staticmethod
    def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False):
        return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)

    def forward(self, x):
        if self.stride == 1:
            x1, x2 = x.chunk(2, dim=1)
            out = torch.cat((x1, self.branch2(x2)), dim=1)
        else:
            out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)

        out = channel_shuffle(out, 2)

        return out


class ShuffleNetV2(nn.Module):
87
    def __init__(self, stages_repeats, stages_out_channels, num_classes=1000, inverted_residual=InvertedResidual):
Bar's avatar
Bar committed
88
89
        super(ShuffleNetV2, self).__init__()

Bar's avatar
Bar committed
90
91
92
93
94
        if len(stages_repeats) != 3:
            raise ValueError('expected stages_repeats as list of 3 positive ints')
        if len(stages_out_channels) != 5:
            raise ValueError('expected stages_out_channels as list of 5 positive ints')
        self._stage_out_channels = stages_out_channels
ekka's avatar
ekka committed
95

Bar's avatar
Bar committed
96
97
        input_channels = 3
        output_channels = self._stage_out_channels[0]
Bar's avatar
Bar committed
98
99
100
101
102
103
104
105
106
107
108
        self.conv1 = nn.Sequential(
            nn.Conv2d(input_channels, output_channels, 3, 2, 1, bias=False),
            nn.BatchNorm2d(output_channels),
            nn.ReLU(inplace=True),
        )
        input_channels = output_channels

        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        stage_names = ['stage{}'.format(i) for i in [2, 3, 4]]
        for name, repeats, output_channels in zip(
Bar's avatar
Bar committed
109
                stage_names, stages_repeats, self._stage_out_channels[1:]):
110
            seq = [inverted_residual(input_channels, output_channels, 2)]
Bar's avatar
Bar committed
111
            for i in range(repeats - 1):
112
                seq.append(inverted_residual(output_channels, output_channels, 1))
Bar's avatar
Bar committed
113
114
115
            setattr(self, name, nn.Sequential(*seq))
            input_channels = output_channels

Bar's avatar
Bar committed
116
        output_channels = self._stage_out_channels[-1]
Bar's avatar
Bar committed
117
118
119
120
121
122
123
124
        self.conv5 = nn.Sequential(
            nn.Conv2d(input_channels, output_channels, 1, 1, 0, bias=False),
            nn.BatchNorm2d(output_channels),
            nn.ReLU(inplace=True),
        )

        self.fc = nn.Linear(output_channels, num_classes)

125
    def _forward(self, x):
Bar's avatar
Bar committed
126
127
128
129
130
131
132
133
134
135
        x = self.conv1(x)
        x = self.maxpool(x)
        x = self.stage2(x)
        x = self.stage3(x)
        x = self.stage4(x)
        x = self.conv5(x)
        x = x.mean([2, 3])  # globalpool
        x = self.fc(x)
        return x

136
137
    forward = _forward

Bar's avatar
Bar committed
138

Bar's avatar
Bar committed
139
140
def _shufflenetv2(arch, pretrained, progress, *args, **kwargs):
    model = ShuffleNetV2(*args, **kwargs)
Bar's avatar
Bar committed
141
142

    if pretrained:
ekka's avatar
ekka committed
143
        model_url = model_urls[arch]
Bar's avatar
Bar committed
144
        if model_url is None:
ekka's avatar
ekka committed
145
146
            raise NotImplementedError('pretrained {} is not supported as of now'.format(arch))
        else:
147
            state_dict = load_state_dict_from_url(model_url, progress=progress)
ekka's avatar
ekka committed
148
            model.load_state_dict(state_dict)
Bar's avatar
Bar committed
149
150
151
152

    return model


153
def shufflenet_v2_x0_5(pretrained=False, progress=True, **kwargs):
154
155
156
157
158
159
160
161
162
    """
    Constructs a ShuffleNetV2 with 0.5x output channels, as described in
    `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design"
    <https://arxiv.org/abs/1807.11164>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
Bar's avatar
Bar committed
163
164
    return _shufflenetv2('shufflenetv2_x0.5', pretrained, progress,
                         [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs)
Bar's avatar
Bar committed
165
166


167
def shufflenet_v2_x1_0(pretrained=False, progress=True, **kwargs):
168
169
170
171
172
173
174
175
176
    """
    Constructs a ShuffleNetV2 with 1.0x output channels, as described in
    `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design"
    <https://arxiv.org/abs/1807.11164>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
Bar's avatar
Bar committed
177
178
    return _shufflenetv2('shufflenetv2_x1.0', pretrained, progress,
                         [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs)
Bar's avatar
Bar committed
179
180


181
def shufflenet_v2_x1_5(pretrained=False, progress=True, **kwargs):
182
183
184
185
186
187
188
189
190
    """
    Constructs a ShuffleNetV2 with 1.5x output channels, as described in
    `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design"
    <https://arxiv.org/abs/1807.11164>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
Bar's avatar
Bar committed
191
192
    return _shufflenetv2('shufflenetv2_x1.5', pretrained, progress,
                         [4, 8, 4], [24, 176, 352, 704, 1024], **kwargs)
Bar's avatar
Bar committed
193
194


195
def shufflenet_v2_x2_0(pretrained=False, progress=True, **kwargs):
196
197
198
199
200
201
202
203
204
    """
    Constructs a ShuffleNetV2 with 2.0x output channels, as described in
    `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design"
    <https://arxiv.org/abs/1807.11164>`_.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
Bar's avatar
Bar committed
205
206
    return _shufflenetv2('shufflenetv2_x2.0', pretrained, progress,
                         [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs)