shufflenet_v2.py 12.1 KB
Newer Older
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
9 10 11 12 13
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
W
WuHaobo 已提交
14 15 16 17 18

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

L
littletomatodonkey 已提交
19
import paddle
20
from paddle import ParamAttr, reshape, transpose, concat, split
21 22
from paddle.nn import Layer, Conv2D, MaxPool2D, AdaptiveAvgPool2D, BatchNorm, Linear
from paddle.nn.initializer import KaimingNormal
W
weishengyu 已提交
23
from paddle.nn.functional import swish
24

C
cuicheng01 已提交
25 26 27
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

MODEL_URLS = {
littletomatodonkey's avatar
littletomatodonkey 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    "ShuffleNetV2_x0_25":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ShuffleNetV2_x0_25_pretrained.pdparams",
    "ShuffleNetV2_x0_33":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ShuffleNetV2_x0_33_pretrained.pdparams",
    "ShuffleNetV2_x0_5":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ShuffleNetV2_x0_5_pretrained.pdparams",
    "ShuffleNetV2_x1_0":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ShuffleNetV2_x1_0_pretrained.pdparams",
    "ShuffleNetV2_x1_5":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ShuffleNetV2_x1_5_pretrained.pdparams",
    "ShuffleNetV2_x2_0":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ShuffleNetV2_x2_0_pretrained.pdparams",
    "ShuffleNetV2_swish":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ShuffleNetV2_swish_pretrained.pdparams"
}
C
cuicheng01 已提交
43 44

__all__ = list(MODEL_URLS.keys())
W
WuHaobo 已提交
45 46


47
def channel_shuffle(x, groups):
48
    batch_size, num_channels, height, width = x.shape[0:4]
49 50 51
    channels_per_group = num_channels // groups

    # reshape
W
weishengyu 已提交
52 53
    x = reshape(
        x=x, shape=[batch_size, groups, channels_per_group, height, width])
54 55 56

    # transpose
    x = transpose(x=x, perm=[0, 2, 1, 3, 4])
57 58

    # flatten
59
    x = reshape(x=x, shape=[batch_size, num_channels, height, width])
60 61 62
    return x


63 64 65 66 67 68 69 70 71
class ConvBNLayer(Layer):
    def __init__(
            self,
            in_channels,
            out_channels,
            kernel_size,
            stride,
            padding,
            groups=1,
W
weishengyu 已提交
72
            act=None,
W
weishengyu 已提交
73
            name=None, ):
74
        super(ConvBNLayer, self).__init__()
75
        self._conv = Conv2D(
76 77 78
            in_channels=in_channels,
            out_channels=out_channels,
            kernel_size=kernel_size,
W
WuHaobo 已提交
79 80
            stride=stride,
            padding=padding,
81
            groups=groups,
W
weishengyu 已提交
82
            weight_attr=ParamAttr(
83
                initializer=KaimingNormal(), name=name + "_weights"),
W
weishengyu 已提交
84
            bias_attr=False)
W
WuHaobo 已提交
85

86
        self._batch_norm = BatchNorm(
87
            out_channels,
88 89
            param_attr=ParamAttr(name=name + "_bn_scale"),
            bias_attr=ParamAttr(name=name + "_bn_offset"),
W
weishengyu 已提交
90
            act=act,
91
            moving_mean_name=name + "_bn_mean",
W
weishengyu 已提交
92
            moving_variance_name=name + "_bn_variance")
93

94
    def forward(self, inputs):
95 96 97 98 99
        y = self._conv(inputs)
        y = self._batch_norm(y)
        return y


100
class InvertedResidual(Layer):
W
weishengyu 已提交
101 102 103 104 105 106
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 act="relu",
                 name=None):
107 108 109 110 111 112 113 114 115
        super(InvertedResidual, self).__init__()
        self._conv_pw = ConvBNLayer(
            in_channels=in_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
116
            name='stage_' + name + '_conv1')
117 118 119 120 121 122 123 124
        self._conv_dw = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=3,
            stride=stride,
            padding=1,
            groups=out_channels // 2,
            act=None,
W
weishengyu 已提交
125
            name='stage_' + name + '_conv2')
126 127 128 129 130 131 132 133
        self._conv_linear = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
134
            name='stage_' + name + '_conv3')
W
WuHaobo 已提交
135

136
    def forward(self, inputs):
W
weishengyu 已提交
137 138 139 140
        x1, x2 = split(
            inputs,
            num_or_sections=[inputs.shape[1] // 2, inputs.shape[1] // 2],
            axis=1)
141 142 143 144 145 146 147 148
        x2 = self._conv_pw(x2)
        x2 = self._conv_dw(x2)
        x2 = self._conv_linear(x2)
        out = concat([x1, x2], axis=1)
        return channel_shuffle(out, 2)


class InvertedResidualDS(Layer):
W
weishengyu 已提交
149 150 151 152 153 154
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 act="relu",
                 name=None):
155 156 157 158 159 160 161 162 163 164 165
        super(InvertedResidualDS, self).__init__()

        # branch1
        self._conv_dw_1 = ConvBNLayer(
            in_channels=in_channels,
            out_channels=in_channels,
            kernel_size=3,
            stride=stride,
            padding=1,
            groups=in_channels,
            act=None,
W
weishengyu 已提交
166
            name='stage_' + name + '_conv4')
167 168 169 170 171 172 173 174
        self._conv_linear_1 = ConvBNLayer(
            in_channels=in_channels,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
175
            name='stage_' + name + '_conv5')
176 177 178 179 180 181 182 183 184
        # branch2
        self._conv_pw_2 = ConvBNLayer(
            in_channels=in_channels,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
185
            name='stage_' + name + '_conv1')
186 187 188 189 190 191 192 193
        self._conv_dw_2 = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=3,
            stride=stride,
            padding=1,
            groups=out_channels // 2,
            act=None,
W
weishengyu 已提交
194
            name='stage_' + name + '_conv2')
195 196 197 198 199 200 201 202
        self._conv_linear_2 = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
203
            name='stage_' + name + '_conv3')
204 205 206 207 208 209 210 211

    def forward(self, inputs):
        x1 = self._conv_dw_1(inputs)
        x1 = self._conv_linear_1(x1)
        x2 = self._conv_pw_2(inputs)
        x2 = self._conv_dw_2(x2)
        x2 = self._conv_linear_2(x2)
        out = concat([x1, x2], axis=1)
212 213 214 215

        return channel_shuffle(out, 2)


216
class ShuffleNet(Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
217
    def __init__(self, class_num=1000, scale=1.0, act="relu"):
218 219
        super(ShuffleNet, self).__init__()
        self.scale = scale
littletomatodonkey's avatar
littletomatodonkey 已提交
220
        self.class_num = class_num
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        stage_repeats = [4, 8, 4]

        if scale == 0.25:
            stage_out_channels = [-1, 24, 24, 48, 96, 512]
        elif scale == 0.33:
            stage_out_channels = [-1, 24, 32, 64, 128, 512]
        elif scale == 0.5:
            stage_out_channels = [-1, 24, 48, 96, 192, 1024]
        elif scale == 1.0:
            stage_out_channels = [-1, 24, 116, 232, 464, 1024]
        elif scale == 1.5:
            stage_out_channels = [-1, 24, 176, 352, 704, 1024]
        elif scale == 2.0:
            stage_out_channels = [-1, 24, 224, 488, 976, 2048]
        else:
            raise NotImplementedError("This scale size:[" + str(scale) +
                                      "] is not implemented!")
        # 1. conv1
        self._conv1 = ConvBNLayer(
240 241 242
            in_channels=3,
            out_channels=stage_out_channels[1],
            kernel_size=3,
243 244 245
            stride=2,
            padding=1,
            act=act,
W
weishengyu 已提交
246
            name='stage1_conv')
247
        self._max_pool = MaxPool2D(kernel_size=3, stride=2, padding=1)
248 249 250

        # 2. bottleneck sequences
        self._block_list = []
251 252
        for stage_id, num_repeat in enumerate(stage_repeats):
            for i in range(num_repeat):
253 254
                if i == 0:
                    block = self.add_sublayer(
255 256 257 258
                        name=str(stage_id + 2) + '_' + str(i + 1),
                        sublayer=InvertedResidualDS(
                            in_channels=stage_out_channels[stage_id + 1],
                            out_channels=stage_out_channels[stage_id + 2],
259 260
                            stride=2,
                            act=act,
W
weishengyu 已提交
261
                            name=str(stage_id + 2) + '_' + str(i + 1)))
262 263
                else:
                    block = self.add_sublayer(
264 265 266 267
                        name=str(stage_id + 2) + '_' + str(i + 1),
                        sublayer=InvertedResidual(
                            in_channels=stage_out_channels[stage_id + 2],
                            out_channels=stage_out_channels[stage_id + 2],
268 269
                            stride=1,
                            act=act,
W
weishengyu 已提交
270
                            name=str(stage_id + 2) + '_' + str(i + 1)))
271
                self._block_list.append(block)
272 273
        # 3. last_conv
        self._last_conv = ConvBNLayer(
274 275 276
            in_channels=stage_out_channels[-2],
            out_channels=stage_out_channels[-1],
            kernel_size=1,
277 278 279
            stride=1,
            padding=0,
            act=act,
W
weishengyu 已提交
280
            name='conv5')
281
        # 4. pool
282
        self._pool2d_avg = AdaptiveAvgPool2D(1)
283 284 285 286
        self._out_c = stage_out_channels[-1]
        # 5. fc
        self._fc = Linear(
            stage_out_channels[-1],
littletomatodonkey's avatar
littletomatodonkey 已提交
287
            class_num,
288
            weight_attr=ParamAttr(name='fc6_weights'),
W
weishengyu 已提交
289
            bias_attr=ParamAttr(name='fc6_offset'))
290 291 292 293 294 295 296 297

    def forward(self, inputs):
        y = self._conv1(inputs)
        y = self._max_pool(y)
        for inv in self._block_list:
            y = inv(y)
        y = self._last_conv(y)
        y = self._pool2d_avg(y)
L
littletomatodonkey 已提交
298
        y = paddle.flatten(y, start_axis=1, stop_axis=-1)
299 300 301 302
        y = self._fc(y)
        return y


C
cuicheng01 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
def _load_pretrained(pretrained, model, model_url, use_ssld=False):
    if pretrained is False:
        pass
    elif pretrained is True:
        load_dygraph_pretrain_from_url(model, model_url, use_ssld=use_ssld)
    elif isinstance(pretrained, str):
        load_dygraph_pretrain(model, pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type."
        )


def ShuffleNetV2_x0_25(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=0.25, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
318 319
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_x0_25"], use_ssld=use_ssld)
320
    return model
W
WuHaobo 已提交
321 322


C
cuicheng01 已提交
323 324
def ShuffleNetV2_x0_33(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=0.33, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
325 326
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_x0_33"], use_ssld=use_ssld)
W
WuHaobo 已提交
327 328 329
    return model


C
cuicheng01 已提交
330 331
def ShuffleNetV2_x0_5(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=0.5, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
332 333
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_x0_5"], use_ssld=use_ssld)
W
WuHaobo 已提交
334 335 336
    return model


C
cuicheng01 已提交
337 338
def ShuffleNetV2_x1_0(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=1.0, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
339 340
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_x1_0"], use_ssld=use_ssld)
W
WuHaobo 已提交
341 342 343
    return model


C
cuicheng01 已提交
344 345
def ShuffleNetV2_x1_5(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=1.5, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
346 347
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_x1_5"], use_ssld=use_ssld)
W
WuHaobo 已提交
348 349 350
    return model


C
cuicheng01 已提交
351 352
def ShuffleNetV2_x2_0(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=2.0, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
353 354
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_x2_0"], use_ssld=use_ssld)
W
WuHaobo 已提交
355 356 357
    return model


C
cuicheng01 已提交
358 359
def ShuffleNetV2_swish(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=1.0, act="swish", **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
360 361
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_swish"], use_ssld=use_ssld)
W
WuHaobo 已提交
362
    return model