mobilenetv2.py 7.1 KB
Newer Older
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
L
LielinJiang 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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.

import paddle
L
LielinJiang 已提交
16
import paddle.nn as nn
17
from paddle.utils.download import get_weights_path_from_url
L
LielinJiang 已提交
18

19
from ..ops import ConvNormActivation
R
Ryan 已提交
20
from ._utils import _make_divisible
N
Nyakku Shigure 已提交
21

22
__all__ = []
L
LielinJiang 已提交
23 24

model_urls = {
25 26 27 28
    'mobilenetv2_1.0': (
        'https://paddle-hapi.bj.bcebos.com/models/mobilenet_v2_x1.0.pdparams',
        '0340af0a901346c8d46f4529882fb63d',
    )
L
LielinJiang 已提交
29 30 31
}


L
LielinJiang 已提交
32
class InvertedResidual(nn.Layer):
33 34 35
    def __init__(
        self, inp, oup, stride, expand_ratio, norm_layer=nn.BatchNorm2D
    ):
36
        super().__init__()
L
LielinJiang 已提交
37 38 39 40 41 42 43 44 45
        self.stride = stride
        assert stride in [1, 2]

        hidden_dim = int(round(inp * expand_ratio))
        self.use_res_connect = self.stride == 1 and inp == oup

        layers = []
        if expand_ratio != 1:
            layers.append(
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
                ConvNormActivation(
                    inp,
                    hidden_dim,
                    kernel_size=1,
                    norm_layer=norm_layer,
                    activation_layer=nn.ReLU6,
                )
            )
        layers.extend(
            [
                ConvNormActivation(
                    hidden_dim,
                    hidden_dim,
                    stride=stride,
                    groups=hidden_dim,
                    norm_layer=norm_layer,
                    activation_layer=nn.ReLU6,
                ),
                nn.Conv2D(hidden_dim, oup, 1, 1, 0, bias_attr=False),
                norm_layer(oup),
            ]
        )
L
LielinJiang 已提交
68 69 70 71 72 73 74 75 76 77
        self.conv = nn.Sequential(*layers)

    def forward(self, x):
        if self.use_res_connect:
            return x + self.conv(x)
        else:
            return self.conv(x)


class MobileNetV2(nn.Layer):
78 79 80 81
    """MobileNetV2 model from
    `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.

    Args:
82
        scale (float, optional): Scale of channels in each layer. Default: 1.0.
83
        num_classes (int, optional): Output dim of last fc layer. If num_classes <= 0, last fc layer
84
                            will not be defined. Default: 1000.
85 86 87 88
        with_pool (bool, optional): Use pool before the last fc layer or not. Default: True.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of MobileNetV2 model.
L
LielinJiang 已提交
89

90 91
    Examples:
        .. code-block:: python
92

93 94
            import paddle
            from paddle.vision.models import MobileNetV2
L
LielinJiang 已提交
95

96
            model = MobileNetV2()
L
LielinJiang 已提交
97

98 99 100 101
            x = paddle.rand([1, 3, 224, 224])
            out = model(x)

            print(out.shape)
102
            # [1, 1000]
103
    """
L
LielinJiang 已提交
104

105
    def __init__(self, scale=1.0, num_classes=1000, with_pool=True):
106
        super().__init__()
L
LielinJiang 已提交
107 108
        self.num_classes = num_classes
        self.with_pool = with_pool
L
LielinJiang 已提交
109 110 111 112 113
        input_channel = 32
        last_channel = 1280

        block = InvertedResidual
        round_nearest = 8
C
cnn 已提交
114
        norm_layer = nn.BatchNorm2D
L
LielinJiang 已提交
115 116 117 118 119 120 121 122 123
        inverted_residual_setting = [
            [1, 16, 1, 1],
            [6, 24, 2, 2],
            [6, 32, 3, 2],
            [6, 64, 4, 2],
            [6, 96, 3, 1],
            [6, 160, 3, 2],
            [6, 320, 1, 1],
        ]
L
LielinJiang 已提交
124

L
LielinJiang 已提交
125
        input_channel = _make_divisible(input_channel * scale, round_nearest)
126 127 128
        self.last_channel = _make_divisible(
            last_channel * max(1.0, scale), round_nearest
        )
L
LielinJiang 已提交
129
        features = [
130 131 132 133 134 135 136
            ConvNormActivation(
                3,
                input_channel,
                stride=2,
                norm_layer=norm_layer,
                activation_layer=nn.ReLU6,
            )
L
LielinJiang 已提交
137 138
        ]

L
LielinJiang 已提交
139 140 141 142 143
        for t, c, n, s in inverted_residual_setting:
            output_channel = _make_divisible(c * scale, round_nearest)
            for i in range(n):
                stride = s if i == 0 else 1
                features.append(
144 145 146 147 148 149 150 151
                    block(
                        input_channel,
                        output_channel,
                        stride,
                        expand_ratio=t,
                        norm_layer=norm_layer,
                    )
                )
L
LielinJiang 已提交
152 153 154
                input_channel = output_channel

        features.append(
155 156 157 158 159 160 161 162
            ConvNormActivation(
                input_channel,
                self.last_channel,
                kernel_size=1,
                norm_layer=norm_layer,
                activation_layer=nn.ReLU6,
            )
        )
L
LielinJiang 已提交
163 164

        self.features = nn.Sequential(*features)
L
LielinJiang 已提交
165 166

        if with_pool:
C
cnn 已提交
167
            self.pool2d_avg = nn.AdaptiveAvgPool2D(1)
L
LielinJiang 已提交
168 169 170

        if self.num_classes > 0:
            self.classifier = nn.Sequential(
171 172
                nn.Dropout(0.2), nn.Linear(self.last_channel, num_classes)
            )
L
LielinJiang 已提交
173 174 175

    def forward(self, x):
        x = self.features(x)
L
LielinJiang 已提交
176 177

        if self.with_pool:
L
LielinJiang 已提交
178 179
            x = self.pool2d_avg(x)

L
LielinJiang 已提交
180
        if self.num_classes > 0:
L
LielinJiang 已提交
181 182 183
            x = paddle.flatten(x, 1)
            x = self.classifier(x)
        return x
L
LielinJiang 已提交
184 185 186 187 188


def _mobilenet(arch, pretrained=False, **kwargs):
    model = MobileNetV2(**kwargs)
    if pretrained:
189 190 191 192 193 194 195 196
        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]
        )
197 198

        param = paddle.load(weight_path)
199
        model.load_dict(param)
L
LielinJiang 已提交
200 201 202 203 204

    return model


def mobilenet_v2(pretrained=False, scale=1.0, **kwargs):
205 206
    """MobileNetV2 from
    `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
207

L
LielinJiang 已提交
208
    Args:
209 210 211 212 213 214 215
        pretrained (bool, optional): Whether to load pre-trained weights. If True, returns a model pre-trained
                            on ImageNet. Default: False.
        scale (float, optional): Scale of channels in each layer. Default: 1.0.
        **kwargs (optional): Additional keyword arguments. For details, please refer to :ref:`MobileNetV2 <api_paddle_vision_MobileNetV2>`.

    Returns:
        :ref:`api_paddle_nn_Layer`. An instance of MobileNetV2 model.
L
LielinJiang 已提交
216 217 218 219

    Examples:
        .. code-block:: python

220
            import paddle
221
            from paddle.vision.models import mobilenet_v2
L
LielinJiang 已提交
222 223 224 225 226 227 228 229 230

            # build model
            model = mobilenet_v2()

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

            # build mobilenet v2 with scale=0.5
            model = mobilenet_v2(scale=0.5)
231 232 233 234 235

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

            print(out.shape)
236
            # [1, 1000]
L
LielinJiang 已提交
237
    """
238 239 240
    model = _mobilenet(
        'mobilenetv2_' + str(scale), pretrained, scale=scale, **kwargs
    )
L
LielinJiang 已提交
241
    return model