shufflenetv2.py 20.8 KB
Newer Older
N
Nyakku Shigure 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

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

import paddle
import paddle.nn as nn
21
from paddle.nn import AdaptiveAvgPool2D, Linear, MaxPool2D
N
Nyakku Shigure 已提交
22 23
from paddle.utils.download import get_weights_path_from_url

24 25
from ..ops import ConvNormActivation

N
Nyakku Shigure 已提交
26 27 28 29
__all__ = []

model_urls = {
    "shufflenet_v2_x0_25": (
30
        "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x0_25.pdparams",
31 32
        "1e509b4c140eeb096bb16e214796d03b",
    ),
N
Nyakku Shigure 已提交
33
    "shufflenet_v2_x0_33": (
34
        "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x0_33.pdparams",
35 36
        "3d7b3ab0eaa5c0927ff1026d31b729bd",
    ),
N
Nyakku Shigure 已提交
37
    "shufflenet_v2_x0_5": (
38
        "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x0_5.pdparams",
39 40
        "5e5cee182a7793c4e4c73949b1a71bd4",
    ),
N
Nyakku Shigure 已提交
41
    "shufflenet_v2_x1_0": (
42
        "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x1_0.pdparams",
43 44
        "122d42478b9e81eb49f8a9ede327b1a4",
    ),
N
Nyakku Shigure 已提交
45
    "shufflenet_v2_x1_5": (
46
        "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x1_5.pdparams",
47 48
        "faced5827380d73531d0ee027c67826d",
    ),
N
Nyakku Shigure 已提交
49
    "shufflenet_v2_x2_0": (
50
        "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_x2_0.pdparams",
51 52
        "cd3dddcd8305e7bcd8ad14d1c69a5784",
    ),
N
Nyakku Shigure 已提交
53
    "shufflenet_v2_swish": (
54
        "https://paddle-hapi.bj.bcebos.com/models/shufflenet_v2_swish.pdparams",
55 56
        "adde0aa3b023e5b0c94a68be1c394b84",
    ),
N
Nyakku Shigure 已提交
57 58 59
}


60 61 62 63 64 65 66 67 68 69 70 71
def create_activation_layer(act):
    if act == "swish":
        return nn.Swish
    elif act == "relu":
        return nn.ReLU
    elif act is None:
        return None
    else:
        raise RuntimeError(
            "The activation function is not supported: {}".format(act))


N
Nyakku Shigure 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
def channel_shuffle(x, groups):
    batch_size, num_channels, height, width = x.shape[0:4]
    channels_per_group = num_channels // groups

    # reshape
    x = paddle.reshape(
        x, shape=[batch_size, groups, channels_per_group, height, width])

    # transpose
    x = paddle.transpose(x, perm=[0, 2, 1, 3, 4])

    # flatten
    x = paddle.reshape(x, shape=[batch_size, num_channels, height, width])
    return x


88
class InvertedResidual(nn.Layer):
89

N
Nyakku Shigure 已提交
90 91 92 93
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
94
                 activation_layer=nn.ReLU):
N
Nyakku Shigure 已提交
95
        super(InvertedResidual, self).__init__()
96 97 98 99 100 101 102 103 104 105 106 107 108 109
        self._conv_pw = ConvNormActivation(in_channels=in_channels // 2,
                                           out_channels=out_channels // 2,
                                           kernel_size=1,
                                           stride=1,
                                           padding=0,
                                           groups=1,
                                           activation_layer=activation_layer)
        self._conv_dw = ConvNormActivation(in_channels=out_channels // 2,
                                           out_channels=out_channels // 2,
                                           kernel_size=3,
                                           stride=stride,
                                           padding=1,
                                           groups=out_channels // 2,
                                           activation_layer=None)
110
        self._conv_linear = ConvNormActivation(
N
Nyakku Shigure 已提交
111 112 113 114 115 116
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
117
            activation_layer=activation_layer)
N
Nyakku Shigure 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131

    def forward(self, inputs):
        x1, x2 = paddle.split(
            inputs,
            num_or_sections=[inputs.shape[1] // 2, inputs.shape[1] // 2],
            axis=1)
        x2 = self._conv_pw(x2)
        x2 = self._conv_dw(x2)
        x2 = self._conv_linear(x2)
        out = paddle.concat([x1, x2], axis=1)
        return channel_shuffle(out, 2)


class InvertedResidualDS(nn.Layer):
132

133 134 135 136 137
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 activation_layer=nn.ReLU):
N
Nyakku Shigure 已提交
138 139 140
        super(InvertedResidualDS, self).__init__()

        # branch1
141 142 143 144 145 146 147
        self._conv_dw_1 = ConvNormActivation(in_channels=in_channels,
                                             out_channels=in_channels,
                                             kernel_size=3,
                                             stride=stride,
                                             padding=1,
                                             groups=in_channels,
                                             activation_layer=None)
148
        self._conv_linear_1 = ConvNormActivation(
N
Nyakku Shigure 已提交
149 150 151 152 153 154
            in_channels=in_channels,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
155
            activation_layer=activation_layer)
N
Nyakku Shigure 已提交
156
        # branch2
157 158 159 160 161 162 163 164 165 166 167 168 169 170
        self._conv_pw_2 = ConvNormActivation(in_channels=in_channels,
                                             out_channels=out_channels // 2,
                                             kernel_size=1,
                                             stride=1,
                                             padding=0,
                                             groups=1,
                                             activation_layer=activation_layer)
        self._conv_dw_2 = ConvNormActivation(in_channels=out_channels // 2,
                                             out_channels=out_channels // 2,
                                             kernel_size=3,
                                             stride=stride,
                                             padding=1,
                                             groups=out_channels // 2,
                                             activation_layer=None)
171
        self._conv_linear_2 = ConvNormActivation(
N
Nyakku Shigure 已提交
172 173 174 175 176 177
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
178
            activation_layer=activation_layer)
N
Nyakku Shigure 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192

    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 = paddle.concat([x1, x2], axis=1)

        return channel_shuffle(out, 2)


class ShuffleNetV2(nn.Layer):
    """ShuffleNetV2 model from
193
    `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
194 195

    Args:
196 197 198
        scale (float, optional): Scale of output channels. Default: True.
        act (str, optional): Activation function of neural network. Default: "relu".
        num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer 
N
Nyakku Shigure 已提交
199
                            will not be defined. Default: 1000.
200 201 202 203
        with_pool (bool, optional): Use pool before the last fc layer or not. Default: True.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 model.
N
Nyakku Shigure 已提交
204 205 206 207 208 209 210 211 212 213 214

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import ShuffleNetV2

            shufflenet_v2_swish = ShuffleNetV2(scale=1.0, act="swish")
            x = paddle.rand([1, 3, 224, 224])
            out = shufflenet_v2_swish(x)
            print(out.shape)
215
            # [1, 1000]
N
Nyakku Shigure 已提交
216 217 218 219 220 221 222 223
    """

    def __init__(self, scale=1.0, act="relu", num_classes=1000, with_pool=True):
        super(ShuffleNetV2, self).__init__()
        self.scale = scale
        self.num_classes = num_classes
        self.with_pool = with_pool
        stage_repeats = [4, 8, 4]
224
        activation_layer = create_activation_layer(act)
N
Nyakku Shigure 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

        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
242 243 244 245 246 247
        self._conv1 = ConvNormActivation(in_channels=3,
                                         out_channels=stage_out_channels[1],
                                         kernel_size=3,
                                         stride=2,
                                         padding=1,
                                         activation_layer=activation_layer)
N
Nyakku Shigure 已提交
248 249 250 251 252 253 254
        self._max_pool = MaxPool2D(kernel_size=3, stride=2, padding=1)

        # 2. bottleneck sequences
        self._block_list = []
        for stage_id, num_repeat in enumerate(stage_repeats):
            for i in range(num_repeat):
                if i == 0:
255 256 257 258 259 260 261
                    block = self.add_sublayer(sublayer=InvertedResidualDS(
                        in_channels=stage_out_channels[stage_id + 1],
                        out_channels=stage_out_channels[stage_id + 2],
                        stride=2,
                        activation_layer=activation_layer),
                                              name=str(stage_id + 2) + "_" +
                                              str(i + 1))
N
Nyakku Shigure 已提交
262
                else:
263 264 265 266 267 268 269
                    block = self.add_sublayer(sublayer=InvertedResidual(
                        in_channels=stage_out_channels[stage_id + 2],
                        out_channels=stage_out_channels[stage_id + 2],
                        stride=1,
                        activation_layer=activation_layer),
                                              name=str(stage_id + 2) + "_" +
                                              str(i + 1))
N
Nyakku Shigure 已提交
270 271
                self._block_list.append(block)
        # 3. last_conv
272
        self._last_conv = ConvNormActivation(
N
Nyakku Shigure 已提交
273 274 275 276 277
            in_channels=stage_out_channels[-2],
            out_channels=stage_out_channels[-1],
            kernel_size=1,
            stride=1,
            padding=0,
278
            activation_layer=activation_layer)
N
Nyakku Shigure 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        # 4. pool
        if with_pool:
            self._pool2d_avg = AdaptiveAvgPool2D(1)

        # 5. fc
        if num_classes > 0:
            self._out_c = stage_out_channels[-1]
            self._fc = Linear(stage_out_channels[-1], num_classes)

    def forward(self, inputs):
        x = self._conv1(inputs)
        x = self._max_pool(x)
        for inv in self._block_list:
            x = inv(x)
        x = self._last_conv(x)

        if self.with_pool:
            x = self._pool2d_avg(x)

        if self.num_classes > 0:
            x = paddle.flatten(x, start_axis=1, stop_axis=-1)
            x = self._fc(x)
        return x


def _shufflenet_v2(arch, pretrained=False, **kwargs):
    model = ShuffleNetV2(**kwargs)
    if pretrained:
        assert (
            arch in model_urls
        ), "{} model do not have a pretrained model now, you should set pretrained=False".format(
            arch)
        weight_path = get_weights_path_from_url(model_urls[arch][0],
                                                model_urls[arch][1])

        param = paddle.load(weight_path)
        model.set_dict(param)
    return model


def shufflenet_v2_x0_25(pretrained=False, **kwargs):
    """ShuffleNetV2 with 0.25x output channels, as described in
321
    `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
322 323

    Args:
324 325 326 327 328 329
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 <api_paddle_vision_ShuffleNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 0.25x output channels.
N
Nyakku Shigure 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import shufflenet_v2_x0_25

            # build model
            model = shufflenet_v2_x0_25()

            # build model and load imagenet pretrained weight
            # model = shufflenet_v2_x0_25(pretrained=True)

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
347
            # [1, 1000]
N
Nyakku Shigure 已提交
348
    """
349 350 351 352
    return _shufflenet_v2("shufflenet_v2_x0_25",
                          scale=0.25,
                          pretrained=pretrained,
                          **kwargs)
N
Nyakku Shigure 已提交
353 354 355 356


def shufflenet_v2_x0_33(pretrained=False, **kwargs):
    """ShuffleNetV2 with 0.33x output channels, as described in
357
    `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
358 359

    Args:
360 361 362 363 364 365
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 <api_paddle_vision_ShuffleNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 0.33x output channels.
N
Nyakku Shigure 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import shufflenet_v2_x0_33

            # build model
            model = shufflenet_v2_x0_33()

            # build model and load imagenet pretrained weight
            # model = shufflenet_v2_x0_33(pretrained=True)

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
383
            # [1, 1000]
N
Nyakku Shigure 已提交
384
    """
385 386 387 388
    return _shufflenet_v2("shufflenet_v2_x0_33",
                          scale=0.33,
                          pretrained=pretrained,
                          **kwargs)
N
Nyakku Shigure 已提交
389 390 391 392


def shufflenet_v2_x0_5(pretrained=False, **kwargs):
    """ShuffleNetV2 with 0.5x output channels, as described in
393
    `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
394 395

    Args:
396 397 398 399 400 401
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 <api_paddle_vision_ShuffleNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 0.5x output channels.
N
Nyakku Shigure 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import shufflenet_v2_x0_5

            # build model
            model = shufflenet_v2_x0_5()

            # build model and load imagenet pretrained weight
            # model = shufflenet_v2_x0_5(pretrained=True)

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
419
            # [1, 1000]
N
Nyakku Shigure 已提交
420
    """
421 422 423 424
    return _shufflenet_v2("shufflenet_v2_x0_5",
                          scale=0.5,
                          pretrained=pretrained,
                          **kwargs)
N
Nyakku Shigure 已提交
425 426 427 428


def shufflenet_v2_x1_0(pretrained=False, **kwargs):
    """ShuffleNetV2 with 1.0x output channels, as described in
429
    `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
430 431

    Args:
432 433 434 435 436 437
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 <api_paddle_vision_ShuffleNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 1.0x output channels.
N
Nyakku Shigure 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import shufflenet_v2_x1_0

            # build model
            model = shufflenet_v2_x1_0()

            # build model and load imagenet pretrained weight
            # model = shufflenet_v2_x1_0(pretrained=True)

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
455
            # [1, 1000]
N
Nyakku Shigure 已提交
456
    """
457 458 459 460
    return _shufflenet_v2("shufflenet_v2_x1_0",
                          scale=1.0,
                          pretrained=pretrained,
                          **kwargs)
N
Nyakku Shigure 已提交
461 462 463 464


def shufflenet_v2_x1_5(pretrained=False, **kwargs):
    """ShuffleNetV2 with 1.5x output channels, as described in
465
    `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
466 467

    Args:
468 469 470 471 472 473
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 <api_paddle_vision_ShuffleNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 1.5x output channels.
N
Nyakku Shigure 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import shufflenet_v2_x1_5

            # build model
            model = shufflenet_v2_x1_5()

            # build model and load imagenet pretrained weight
            # model = shufflenet_v2_x1_5(pretrained=True)

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
491
            # [1, 1000]
N
Nyakku Shigure 已提交
492
    """
493 494 495 496
    return _shufflenet_v2("shufflenet_v2_x1_5",
                          scale=1.5,
                          pretrained=pretrained,
                          **kwargs)
N
Nyakku Shigure 已提交
497 498 499 500


def shufflenet_v2_x2_0(pretrained=False, **kwargs):
    """ShuffleNetV2 with 2.0x output channels, as described in
501
    `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
502 503

    Args:
504 505 506 507 508 509
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 <api_paddle_vision_ShuffleNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with 2.0x output channels.
N
Nyakku Shigure 已提交
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import shufflenet_v2_x2_0

            # build model
            model = shufflenet_v2_x2_0()

            # build model and load imagenet pretrained weight
            # model = shufflenet_v2_x2_0(pretrained=True)

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
527
            # [1, 1000]
N
Nyakku Shigure 已提交
528
    """
529 530 531 532
    return _shufflenet_v2("shufflenet_v2_x2_0",
                          scale=2.0,
                          pretrained=pretrained,
                          **kwargs)
N
Nyakku Shigure 已提交
533 534 535


def shufflenet_v2_swish(pretrained=False, **kwargs):
536 537
    """ShuffleNetV2 with swish activation function, as described in
    `"ShuffleNet V2: Practical Guidelines for Ecient CNN Architecture Design" <https://arxiv.org/pdf/1807.11164.pdf>`_.
N
Nyakku Shigure 已提交
538 539

    Args:
540 541 542 543 544 545
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`ShuffleNetV2 <api_paddle_vision_ShuffleNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of ShuffleNetV2 with swish activation function.
N
Nyakku Shigure 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

    Examples:
        .. code-block:: python

            import paddle
            from paddle.vision.models import shufflenet_v2_swish

            # build model
            model = shufflenet_v2_swish()

            # build model and load imagenet pretrained weight
            # model = shufflenet_v2_swish(pretrained=True)

            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
563
            # [1, 1000]
N
Nyakku Shigure 已提交
564
    """
565 566 567 568 569
    return _shufflenet_v2("shufflenet_v2_swish",
                          scale=1.0,
                          act="swish",
                          pretrained=pretrained,
                          **kwargs)