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 28 29 30 31 32 33 34 35 36 37
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

MODEL_URLS = {
              "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"
             }

__all__ = list(MODEL_URLS.keys())
W
WuHaobo 已提交
38 39


40
def channel_shuffle(x, groups):
41
    batch_size, num_channels, height, width = x.shape[0:4]
42 43 44
    channels_per_group = num_channels // groups

    # reshape
W
weishengyu 已提交
45 46
    x = reshape(
        x=x, shape=[batch_size, groups, channels_per_group, height, width])
47 48 49

    # transpose
    x = transpose(x=x, perm=[0, 2, 1, 3, 4])
50 51

    # flatten
52
    x = reshape(x=x, shape=[batch_size, num_channels, height, width])
53 54 55
    return x


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

79
        self._batch_norm = BatchNorm(
80
            out_channels,
81 82
            param_attr=ParamAttr(name=name + "_bn_scale"),
            bias_attr=ParamAttr(name=name + "_bn_offset"),
W
weishengyu 已提交
83
            act=act,
84
            moving_mean_name=name + "_bn_mean",
W
weishengyu 已提交
85
            moving_variance_name=name + "_bn_variance")
86

87
    def forward(self, inputs):
88 89 90 91 92
        y = self._conv(inputs)
        y = self._batch_norm(y)
        return y


93
class InvertedResidual(Layer):
W
weishengyu 已提交
94 95 96 97 98 99
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 act="relu",
                 name=None):
100 101 102 103 104 105 106 107 108
        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 已提交
109
            name='stage_' + name + '_conv1')
110 111 112 113 114 115 116 117
        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 已提交
118
            name='stage_' + name + '_conv2')
119 120 121 122 123 124 125 126
        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 已提交
127
            name='stage_' + name + '_conv3')
W
WuHaobo 已提交
128

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

    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)
205 206 207 208

        return channel_shuffle(out, 2)


209
class ShuffleNet(Layer):
W
weishengyu 已提交
210
    def __init__(self, class_dim=1000, scale=1.0, act="relu"):
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        super(ShuffleNet, self).__init__()
        self.scale = scale
        self.class_dim = class_dim
        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(
233 234 235
            in_channels=3,
            out_channels=stage_out_channels[1],
            kernel_size=3,
236 237 238
            stride=2,
            padding=1,
            act=act,
W
weishengyu 已提交
239
            name='stage1_conv')
240
        self._max_pool = MaxPool2D(kernel_size=3, stride=2, padding=1)
241 242 243

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

    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 已提交
291
        y = paddle.flatten(y, start_axis=1, stop_axis=-1)
292 293 294 295
        y = self._fc(y)
        return y


C
cuicheng01 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
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)
    _load_pretrained(pretrained, model, MODEL_URLS["ShuffleNetV2_x0_25"], use_ssld=use_ssld)
312
    return model
W
WuHaobo 已提交
313 314


C
cuicheng01 已提交
315 316 317
def ShuffleNetV2_x0_33(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=0.33, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["ShuffleNetV2_x0_33"], use_ssld=use_ssld)
W
WuHaobo 已提交
318 319 320
    return model


C
cuicheng01 已提交
321 322 323
def ShuffleNetV2_x0_5(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=0.5, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["ShuffleNetV2_x0_5"], use_ssld=use_ssld)
W
WuHaobo 已提交
324 325 326
    return model


C
cuicheng01 已提交
327 328 329
def ShuffleNetV2_x1_0(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=1.0, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["ShuffleNetV2_x1_0"], use_ssld=use_ssld)
W
WuHaobo 已提交
330 331 332
    return model


C
cuicheng01 已提交
333 334 335
def ShuffleNetV2_x1_5(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=1.5, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["ShuffleNetV2_x1_5"], use_ssld=use_ssld)
W
WuHaobo 已提交
336 337 338
    return model


C
cuicheng01 已提交
339 340 341
def ShuffleNetV2_x2_0(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=2.0, **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["ShuffleNetV2_x2_0"], use_ssld=use_ssld)
W
WuHaobo 已提交
342 343 344
    return model


C
cuicheng01 已提交
345 346 347
def ShuffleNetV2_swish(pretrained=False, use_ssld=False, **kwargs):
    model = ShuffleNet(scale=1.0, act="swish", **kwargs)
    _load_pretrained(pretrained, model, MODEL_URLS["ShuffleNetV2_swish"], use_ssld=use_ssld)
W
WuHaobo 已提交
348
    return model