"vscode:/vscode.git/clone" did not exist on "4b12118014056b3ede06b7a5d41ea173dc55a548"
shufflenetv2.py 8.1 KB
Newer Older
1
2
from typing import Callable, Any, List

Bar's avatar
Bar committed
3
4
import torch
import torch.nn as nn
5
6
from torch import Tensor

7
from .._internally_replaced_utils import load_state_dict_from_url
Bar's avatar
Bar committed
8

9

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

model_urls = {
13
14
15
16
    "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",
    "shufflenetv2_x1.5": None,
    "shufflenetv2_x2.0": None,
Bar's avatar
Bar committed
17
18
19
}


20
def channel_shuffle(x: Tensor, groups: int) -> Tensor:
21
    batchsize, num_channels, height, width = x.size()
Bar's avatar
Bar committed
22
23
24
    channels_per_group = num_channels // groups

    # reshape
25
    x = x.view(batchsize, groups, channels_per_group, height, width)
Bar's avatar
Bar committed
26
27
28
29
30
31
32
33
34
35

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

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

    return x


class InvertedResidual(nn.Module):
36
    def __init__(self, inp: int, oup: int, stride: int) -> None:
Bar's avatar
Bar committed
37
38
39
        super(InvertedResidual, self).__init__()

        if not (1 <= stride <= 3):
40
            raise ValueError("illegal stride value")
Bar's avatar
Bar committed
41
42
43
44
45
46
47
        self.stride = stride

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

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

        self.branch2 = nn.Sequential(
58
59
60
61
62
63
64
65
            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
66
67
            nn.BatchNorm2d(branch_features),
            nn.ReLU(inplace=True),
68
            self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1),
Bar's avatar
Bar committed
69
            nn.BatchNorm2d(branch_features),
70
            nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False),
Bar's avatar
Bar committed
71
72
73
74
75
            nn.BatchNorm2d(branch_features),
            nn.ReLU(inplace=True),
        )

    @staticmethod
76
    def depthwise_conv(
77
        i: int, o: int, kernel_size: int, stride: int = 1, padding: int = 0, bias: bool = False
78
    ) -> nn.Conv2d:
Bar's avatar
Bar committed
79
80
        return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i)

81
    def forward(self, x: Tensor) -> Tensor:
Bar's avatar
Bar committed
82
83
84
85
86
87
88
89
90
91
92
93
        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):
94
95
96
97
98
    def __init__(
        self,
        stages_repeats: List[int],
        stages_out_channels: List[int],
        num_classes: int = 1000,
99
        inverted_residual: Callable[..., nn.Module] = InvertedResidual,
100
    ) -> None:
Bar's avatar
Bar committed
101
102
        super(ShuffleNetV2, self).__init__()

Bar's avatar
Bar committed
103
        if len(stages_repeats) != 3:
104
            raise ValueError("expected stages_repeats as list of 3 positive ints")
Bar's avatar
Bar committed
105
        if len(stages_out_channels) != 5:
106
            raise ValueError("expected stages_out_channels as list of 5 positive ints")
Bar's avatar
Bar committed
107
        self._stage_out_channels = stages_out_channels
ekka's avatar
ekka committed
108

Bar's avatar
Bar committed
109
110
        input_channels = 3
        output_channels = self._stage_out_channels[0]
Bar's avatar
Bar committed
111
112
113
114
115
116
117
118
119
        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)

120
121
122
123
        # Static annotations for mypy
        self.stage2: nn.Sequential
        self.stage3: nn.Sequential
        self.stage4: nn.Sequential
124
125
        stage_names = ["stage{}".format(i) for i in [2, 3, 4]]
        for name, repeats, output_channels in zip(stage_names, stages_repeats, self._stage_out_channels[1:]):
126
            seq = [inverted_residual(input_channels, output_channels, 2)]
Bar's avatar
Bar committed
127
            for i in range(repeats - 1):
128
                seq.append(inverted_residual(output_channels, output_channels, 1))
Bar's avatar
Bar committed
129
130
131
            setattr(self, name, nn.Sequential(*seq))
            input_channels = output_channels

Bar's avatar
Bar committed
132
        output_channels = self._stage_out_channels[-1]
Bar's avatar
Bar committed
133
134
135
136
137
138
139
140
        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)

141
    def _forward_impl(self, x: Tensor) -> Tensor:
142
        # See note [TorchScript super()]
Bar's avatar
Bar committed
143
144
145
146
147
148
149
150
151
152
        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

153
    def forward(self, x: Tensor) -> Tensor:
154
        return self._forward_impl(x)
155

Bar's avatar
Bar committed
156

157
def _shufflenetv2(arch: str, pretrained: bool, progress: bool, *args: Any, **kwargs: Any) -> ShuffleNetV2:
Bar's avatar
Bar committed
158
    model = ShuffleNetV2(*args, **kwargs)
Bar's avatar
Bar committed
159
160

    if pretrained:
ekka's avatar
ekka committed
161
        model_url = model_urls[arch]
Bar's avatar
Bar committed
162
        if model_url is None:
163
            raise NotImplementedError("pretrained {} is not supported as of now".format(arch))
ekka's avatar
ekka committed
164
        else:
165
            state_dict = load_state_dict_from_url(model_url, progress=progress)
ekka's avatar
ekka committed
166
            model.load_state_dict(state_dict)
Bar's avatar
Bar committed
167
168
169
170

    return model


171
def shufflenet_v2_x0_5(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ShuffleNetV2:
172
173
174
175
176
177
178
179
180
    """
    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
    """
181
    return _shufflenetv2("shufflenetv2_x0.5", pretrained, progress, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs)
Bar's avatar
Bar committed
182
183


184
def shufflenet_v2_x1_0(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ShuffleNetV2:
185
186
187
188
189
190
191
192
193
    """
    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
    """
194
    return _shufflenetv2("shufflenetv2_x1.0", pretrained, progress, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs)
Bar's avatar
Bar committed
195
196


197
def shufflenet_v2_x1_5(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ShuffleNetV2:
198
199
200
201
202
203
204
205
206
    """
    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
    """
207
    return _shufflenetv2("shufflenetv2_x1.5", pretrained, progress, [4, 8, 4], [24, 176, 352, 704, 1024], **kwargs)
Bar's avatar
Bar committed
208
209


210
def shufflenet_v2_x2_0(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ShuffleNetV2:
211
212
213
214
215
216
217
218
219
    """
    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
    """
220
    return _shufflenetv2("shufflenetv2_x2.0", pretrained, progress, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs)