mobilenet_v1.py 8.4 KB
Newer Older
B
Bin Lu 已提交
1
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
B
Bin Lu 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

B
Bin Lu 已提交
15
from __future__ import absolute_import, division, print_function
B
Bin Lu 已提交
16 17 18 19 20

import numpy as np
import paddle
from paddle import ParamAttr
import paddle.nn as nn
B
Bin Lu 已提交
21
from paddle.nn import Conv2D, BatchNorm, Linear, ReLU, Flatten
B
Bin Lu 已提交
22
from paddle.nn import AdaptiveAvgPool2D
B
Bin Lu 已提交
23 24 25
from paddle.nn.initializer import KaimingNormal

from ppcls.arch.backbone.base.theseus_layer import TheseusLayer
B
Bin Lu 已提交
26
from ppcls.utils.save_load import load_dygraph_pretrain_from, load_dygraph_pretrain_from_url
B
Bin Lu 已提交
27

B
Bin Lu 已提交
28 29 30

MODEL_URLS = {
    "MobileNetV1_x0_25": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/MobileNetV1_x0_25_pretrained.pdparams",
B
Bin Lu 已提交
31
    "MobileNetV1_x0_5": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/MobileNetV1_x0_5_pretrained.pdparams",
B
Bin Lu 已提交
32 33 34 35 36 37
    "MobileNetV1_x0_75": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/MobileNetV1_x0_75_pretrained.pdparams",
    "MobileNetV1": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/MobileNetV1_pretrained.pdparams",
}

__all__ = MODEL_URLS.keys()
    
B
Bin Lu 已提交
38
    
B
Bin Lu 已提交
39 40 41 42 43 44 45
class ConvBNLayer(TheseusLayer):
    def __init__(self,
                 num_channels,
                 filter_size,
                 num_filters,
                 stride,
                 padding,
B
Bin Lu 已提交
46
                 num_groups=1):
B
Bin Lu 已提交
47 48
        super(ConvBNLayer, self).__init__()

B
Bin Lu 已提交
49
        self.conv = Conv2D(
B
Bin Lu 已提交
50 51 52 53 54 55 56
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
            stride=stride,
            padding=padding,
            groups=num_groups,
            weight_attr=ParamAttr(
B
Bin Lu 已提交
57
                initializer=KaimingNormal()),
B
Bin Lu 已提交
58 59
            bias_attr=False)

B
Bin Lu 已提交
60
        self.bn = BatchNorm(
B
Bin Lu 已提交
61 62
            num_filters)
        
B
Bin Lu 已提交
63
        self.relu = ReLU()
B
Bin Lu 已提交
64

B
Bin Lu 已提交
65
    def forward(self, x):
B
Bin Lu 已提交
66 67 68
        x = self.conv(x)
        x = self.bn(x)
        x = self.relu(x)
B
Bin Lu 已提交
69
        return x
B
Bin Lu 已提交
70 71 72 73 74 75 76 77 78


class DepthwiseSeparable(TheseusLayer):
    def __init__(self,
                 num_channels,
                 num_filters1,
                 num_filters2,
                 num_groups,
                 stride,
B
Bin Lu 已提交
79
                 scale):
B
Bin Lu 已提交
80 81
        super(DepthwiseSeparable, self).__init__()

B
Bin Lu 已提交
82
        self.depthwise_conv = ConvBNLayer(
B
Bin Lu 已提交
83 84 85 86 87
            num_channels=num_channels,
            num_filters=int(num_filters1 * scale),
            filter_size=3,
            stride=stride,
            padding=1,
B
Bin Lu 已提交
88
            num_groups=int(num_groups * scale))
B
Bin Lu 已提交
89

B
Bin Lu 已提交
90
        self.pointwise_conv = ConvBNLayer(
B
Bin Lu 已提交
91 92 93 94
            num_channels=int(num_filters1 * scale),
            filter_size=1,
            num_filters=int(num_filters2 * scale),
            stride=1,
B
Bin Lu 已提交
95
            padding=0)
B
Bin Lu 已提交
96

B
Bin Lu 已提交
97
    def forward(self, x):
B
Bin Lu 已提交
98 99
        x = self.depthwise_conv(x)
        x = self.pointwise_conv(x)
B
Bin Lu 已提交
100
        return x
B
Bin Lu 已提交
101 102 103


class MobileNet(TheseusLayer):
B
Bin Lu 已提交
104
    def __init__(self, scale=1.0, class_num=1000, pretrained=False):
B
Bin Lu 已提交
105 106
        super(MobileNet, self).__init__()
        self.scale = scale
B
Bin Lu 已提交
107
        self.pretrained = pretrained
B
Bin Lu 已提交
108

B
Bin Lu 已提交
109
        self.conv = ConvBNLayer(
B
Bin Lu 已提交
110 111 112 113
            num_channels=3,
            filter_size=3,
            num_filters=int(32 * scale),
            stride=2,
B
Bin Lu 已提交
114
            padding=1)
B
Bin Lu 已提交
115
        
B
Bin Lu 已提交
116
        #num_channels, num_filters1, num_filters2, num_groups, stride
B
Bin Lu 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129
        self.cfg = [[int(32 * scale),   32,   64,   32,   1],
                    [int(64 * scale),   64,   128,  64,   2],
                    [int(128 * scale),  128,  128,  128,  1],
                    [int(128 * scale),  128,  256,  128,  2],
                    [int(256 * scale),  256,  256,  256,  1],
                    [int(256 * scale),  256,  512,  256,  2],
                    [int(512 * scale),  512,  512,  512,  1],
                    [int(512 * scale),  512,  512,  512,  1],
                    [int(512 * scale),  512,  512,  512,  1],
                    [int(512 * scale),  512,  512,  512,  1],
                    [int(512 * scale),  512,  512,  512,  1],
                    [int(512 * scale),  512,  1024, 512,  2],
                    [int(1024 * scale), 1024, 1024, 1024, 1]]
B
Bin Lu 已提交
130 131 132 133 134 135 136 137 138
        
        self.blocks = nn.Sequential(*[
                    DepthwiseSeparable(
                            num_channels=params[0],
                            num_filters1=params[1],
                            num_filters2=params[2],
                            num_groups=params[3],
                            stride=params[4],
                            scale=scale) for params in self.cfg])
B
Bin Lu 已提交
139

B
Bin Lu 已提交
140
        self.avg_pool = AdaptiveAvgPool2D(1)
B
Bin Lu 已提交
141
        self.flatten = Flatten(start_axis=1, stop_axis=-1)
B
Bin Lu 已提交
142

B
Bin Lu 已提交
143
        self.fc = Linear(
B
Bin Lu 已提交
144
            int(1024 * scale),
B
Bin Lu 已提交
145
            class_num,
B
Bin Lu 已提交
146
            weight_attr=ParamAttr(initializer=KaimingNormal()))
B
Bin Lu 已提交
147
        
B
Bin Lu 已提交
148
    def forward(self, x):
B
Bin Lu 已提交
149
        x = self.conv(x)
B
Bin Lu 已提交
150
        x = self.blocks(x)
B
Bin Lu 已提交
151
        x = self.avg_pool(x)
B
Bin Lu 已提交
152
        x = self.flatten(x)
B
Bin Lu 已提交
153
        x = self.fc(x)
B
Bin Lu 已提交
154
        return x
B
Bin Lu 已提交
155 156 157


def MobileNetV1_x0_25(**args):
B
Bin Lu 已提交
158 159 160 161 162 163 164 165 166
    """
        MobileNetV1_x0_25
        Args:
            pretrained: bool=False. If `True` load pretrained parameters, `False` otherwise.
            kwargs: 
                class_num: int=1000. Output dim of last fc layer.
        Returns:
            model: nn.Layer. Specific `MobileNetV1_x0_25` model depends on args.
    """
B
Bin Lu 已提交
167
    model = MobileNet(scale=0.25, **args)
B
Bin Lu 已提交
168 169 170 171 172 173 174 175
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["MobileNetV1_x0_25"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
B
Bin Lu 已提交
176 177 178 179
    return model


def MobileNetV1_x0_5(**args):
B
Bin Lu 已提交
180 181 182 183 184 185 186 187 188
    """
        MobileNetV1_x0_5
        Args:
            pretrained: bool=False. If `True` load pretrained parameters, `False` otherwise.
            kwargs: 
                class_num: int=1000. Output dim of last fc layer.
        Returns:
            model: nn.Layer. Specific `MobileNetV1_x0_5` model depends on args.
    """
B
Bin Lu 已提交
189
    model = MobileNet(scale=0.5, **args)
B
Bin Lu 已提交
190 191 192 193 194 195 196 197
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["MobileNetV1_x0_5"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
B
Bin Lu 已提交
198 199 200 201
    return model


def MobileNetV1_x0_75(**args):
B
Bin Lu 已提交
202 203 204 205 206 207 208 209 210
    """
        MobileNetV1_x0_75
        Args:
            pretrained: bool=False. If `True` load pretrained parameters, `False` otherwise.
            kwargs: 
                class_num: int=1000. Output dim of last fc layer.
        Returns:
            model: nn.Layer. Specific `MobileNetV1_x0_75` model depends on args.
    """
B
Bin Lu 已提交
211
    model = MobileNet(scale=0.75, **args)
B
Bin Lu 已提交
212 213 214 215 216 217 218 219
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["MobileNetV1_x0_75"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
B
Bin Lu 已提交
220 221 222 223
    return model


def MobileNetV1(**args):
B
Bin Lu 已提交
224 225 226 227 228 229 230 231 232
    """
        MobileNetV1
        Args:
            pretrained: bool=False. If `True` load pretrained parameters, `False` otherwise.
            kwargs: 
                class_num: int=1000. Output dim of last fc layer.
        Returns:
            model: nn.Layer. Specific `MobileNetV1` model depends on args.
    """
B
Bin Lu 已提交
233
    model = MobileNet(scale=1.0, **args)
B
Bin Lu 已提交
234 235 236 237 238 239 240 241
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["MobileNetV1"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
B
Bin Lu 已提交
242
    return model
B
Bin Lu 已提交
243 244