shufflenet_v2.py 12.2 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

G
gaotingquan 已提交
15 16
# reference: https://arxiv.org/abs/1807.11164

W
WuHaobo 已提交
17 18 19 20
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

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

C
cuicheng01 已提交
27 28 29
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

MODEL_URLS = {
littletomatodonkey's avatar
littletomatodonkey 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    "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 已提交
45 46

__all__ = list(MODEL_URLS.keys())
W
WuHaobo 已提交
47 48


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

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

    # transpose
    x = transpose(x=x, perm=[0, 2, 1, 3, 4])
59 60

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


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

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

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


102
class InvertedResidual(Layer):
W
weishengyu 已提交
103 104 105 106 107 108
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 act="relu",
                 name=None):
109 110 111 112 113 114 115 116 117
        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 已提交
118
            name='stage_' + name + '_conv1')
119 120 121 122 123 124 125 126
        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 已提交
127
            name='stage_' + name + '_conv2')
128 129 130 131 132 133 134 135
        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 已提交
136
            name='stage_' + name + '_conv3')
W
WuHaobo 已提交
137

138
    def forward(self, inputs):
W
weishengyu 已提交
139 140 141 142
        x1, x2 = split(
            inputs,
            num_or_sections=[inputs.shape[1] // 2, inputs.shape[1] // 2],
            axis=1)
143 144 145 146 147 148 149 150
        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 已提交
151 152 153 154 155 156
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 act="relu",
                 name=None):
157 158 159 160 161 162 163 164 165 166 167
        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 已提交
168
            name='stage_' + name + '_conv4')
169 170 171 172 173 174 175 176
        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 已提交
177
            name='stage_' + name + '_conv5')
178 179 180 181 182 183 184 185 186
        # 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 已提交
187
            name='stage_' + name + '_conv1')
188 189 190 191 192 193 194 195
        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 已提交
196
            name='stage_' + name + '_conv2')
197 198 199 200 201 202 203 204
        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 已提交
205
            name='stage_' + name + '_conv3')
206 207 208 209 210 211 212 213

    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)
214 215 216 217

        return channel_shuffle(out, 2)


218
class ShuffleNet(Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
219
    def __init__(self, class_num=1000, scale=1.0, act="relu"):
220 221
        super(ShuffleNet, self).__init__()
        self.scale = scale
littletomatodonkey's avatar
littletomatodonkey 已提交
222
        self.class_num = class_num
223 224 225 226 227 228 229 230 231 232 233 234 235
        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:
236
            stage_out_channels = [-1, 24, 244, 488, 976, 2048]
237 238 239 240 241
        else:
            raise NotImplementedError("This scale size:[" + str(scale) +
                                      "] is not implemented!")
        # 1. conv1
        self._conv1 = ConvBNLayer(
242 243 244
            in_channels=3,
            out_channels=stage_out_channels[1],
            kernel_size=3,
245 246 247
            stride=2,
            padding=1,
            act=act,
W
weishengyu 已提交
248
            name='stage1_conv')
249
        self._max_pool = MaxPool2D(kernel_size=3, stride=2, padding=1)
250 251 252

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

    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 已提交
300
        y = paddle.flatten(y, start_axis=1, stop_axis=-1)
301 302 303 304
        y = self._fc(y)
        return y


C
cuicheng01 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
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 已提交
320 321
    _load_pretrained(
        pretrained, model, MODEL_URLS["ShuffleNetV2_x0_25"], use_ssld=use_ssld)
322
    return model
W
WuHaobo 已提交
323 324


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


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


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


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


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


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