mobilenet_v1.py 7.8 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

19 20
import numpy as np
import paddle
littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
21 22 23
from paddle import ParamAttr
import paddle.nn as nn
import paddle.nn.functional as F
littletomatodonkey's avatar
littletomatodonkey 已提交
24 25
from paddle.nn import Conv2d, BatchNorm, Linear, Dropout
from paddle.nn import AdaptiveAvgPool2d, MaxPool2d, AvgPool2d
littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
26
from paddle.nn.initializer import MSRA
27
import math
W
WuHaobo 已提交
28 29

__all__ = [
30
    "MobileNetV1_x0_25", "MobileNetV1_x0_5", "MobileNetV1_x0_75", "MobileNetV1"
W
WuHaobo 已提交
31 32 33
]


littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
34
class ConvBNLayer(nn.Layer):
35 36 37 38 39 40 41 42 43 44 45
    def __init__(self,
                 num_channels,
                 filter_size,
                 num_filters,
                 stride,
                 padding,
                 channels=None,
                 num_groups=1,
                 act='relu',
                 name=None):
        super(ConvBNLayer, self).__init__()
W
WuHaobo 已提交
46

littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
47 48 49 50
        self._conv = Conv2d(
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
W
WuHaobo 已提交
51 52 53
            stride=stride,
            padding=padding,
            groups=num_groups,
littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
54
            weight_attr=ParamAttr(
W
WuHaobo 已提交
55 56
                initializer=MSRA(), name=name + "_weights"),
            bias_attr=False)
57 58 59

        self._batch_norm = BatchNorm(
            num_filters,
W
WuHaobo 已提交
60
            act=act,
61 62 63 64 65 66 67 68 69 70 71
            param_attr=ParamAttr(name + "_bn_scale"),
            bias_attr=ParamAttr(name + "_bn_offset"),
            moving_mean_name=name + "_bn_mean",
            moving_variance_name=name + "_bn_variance")

    def forward(self, inputs):
        y = self._conv(inputs)
        y = self._batch_norm(y)
        return y


littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
72
class DepthwiseSeparable(nn.Layer):
73 74 75 76 77 78 79 80 81 82 83 84
    def __init__(self,
                 num_channels,
                 num_filters1,
                 num_filters2,
                 num_groups,
                 stride,
                 scale,
                 name=None):
        super(DepthwiseSeparable, self).__init__()

        self._depthwise_conv = ConvBNLayer(
            num_channels=num_channels,
W
WuHaobo 已提交
85
            num_filters=int(num_filters1 * scale),
86
            filter_size=3,
W
WuHaobo 已提交
87 88 89 90 91
            stride=stride,
            padding=1,
            num_groups=int(num_groups * scale),
            name=name + "_dw")

92 93
        self._pointwise_conv = ConvBNLayer(
            num_channels=int(num_filters1 * scale),
W
WuHaobo 已提交
94 95 96 97 98
            filter_size=1,
            num_filters=int(num_filters2 * scale),
            stride=1,
            padding=0,
            name=name + "_sep")
99 100 101 102 103 104 105

    def forward(self, inputs):
        y = self._depthwise_conv(inputs)
        y = self._pointwise_conv(y)
        return y


littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
106
class MobileNet(nn.Layer):
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    def __init__(self, scale=1.0, class_dim=1000):
        super(MobileNet, self).__init__()
        self.scale = scale
        self.block_list = []

        self.conv1 = ConvBNLayer(
            num_channels=3,
            filter_size=3,
            channels=3,
            num_filters=int(32 * scale),
            stride=2,
            padding=1,
            name="conv1")

        conv2_1 = self.add_sublayer(
            "conv2_1",
            sublayer=DepthwiseSeparable(
                num_channels=int(32 * scale),
                num_filters1=32,
                num_filters2=64,
                num_groups=32,
                stride=1,
                scale=scale,
                name="conv2_1"))
        self.block_list.append(conv2_1)

        conv2_2 = self.add_sublayer(
            "conv2_2",
            sublayer=DepthwiseSeparable(
                num_channels=int(64 * scale),
                num_filters1=64,
                num_filters2=128,
                num_groups=64,
                stride=2,
                scale=scale,
                name="conv2_2"))
        self.block_list.append(conv2_2)

        conv3_1 = self.add_sublayer(
            "conv3_1",
            sublayer=DepthwiseSeparable(
                num_channels=int(128 * scale),
                num_filters1=128,
                num_filters2=128,
                num_groups=128,
                stride=1,
                scale=scale,
                name="conv3_1"))
        self.block_list.append(conv3_1)

        conv3_2 = self.add_sublayer(
            "conv3_2",
            sublayer=DepthwiseSeparable(
                num_channels=int(128 * scale),
                num_filters1=128,
                num_filters2=256,
                num_groups=128,
                stride=2,
                scale=scale,
                name="conv3_2"))
        self.block_list.append(conv3_2)

        conv4_1 = self.add_sublayer(
            "conv4_1",
            sublayer=DepthwiseSeparable(
                num_channels=int(256 * scale),
                num_filters1=256,
                num_filters2=256,
                num_groups=256,
                stride=1,
                scale=scale,
                name="conv4_1"))
        self.block_list.append(conv4_1)

        conv4_2 = self.add_sublayer(
            "conv4_2",
            sublayer=DepthwiseSeparable(
                num_channels=int(256 * scale),
                num_filters1=256,
                num_filters2=512,
                num_groups=256,
                stride=2,
                scale=scale,
                name="conv4_2"))
        self.block_list.append(conv4_2)

        for i in range(5):
            conv5 = self.add_sublayer(
                "conv5_" + str(i + 1),
                sublayer=DepthwiseSeparable(
                    num_channels=int(512 * scale),
                    num_filters1=512,
                    num_filters2=512,
                    num_groups=512,
                    stride=1,
                    scale=scale,
                    name="conv5_" + str(i + 1)))
            self.block_list.append(conv5)

        conv5_6 = self.add_sublayer(
            "conv5_6",
            sublayer=DepthwiseSeparable(
                num_channels=int(512 * scale),
                num_filters1=512,
                num_filters2=1024,
                num_groups=512,
                stride=2,
                scale=scale,
                name="conv5_6"))
        self.block_list.append(conv5_6)

        conv6 = self.add_sublayer(
            "conv6",
            sublayer=DepthwiseSeparable(
                num_channels=int(1024 * scale),
                num_filters1=1024,
                num_filters2=1024,
                num_groups=1024,
                stride=1,
                scale=scale,
                name="conv6"))
        self.block_list.append(conv6)

littletomatodonkey's avatar
littletomatodonkey 已提交
230
        self.pool2d_avg = AdaptiveAvgPool2d(1)
231 232 233 234

        self.out = Linear(
            int(1024 * scale),
            class_dim,
littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
235
            weight_attr=ParamAttr(
236 237 238 239 240 241 242 243
                initializer=MSRA(), name="fc7_weights"),
            bias_attr=ParamAttr(name="fc7_offset"))

    def forward(self, inputs):
        y = self.conv1(inputs)
        for block in self.block_list:
            y = block(y)
        y = self.pool2d_avg(y)
littletomatodonkey's avatar
fix mv1  
littletomatodonkey 已提交
244
        y = paddle.reshape(y, shape=[-1, int(1024 * self.scale)])
245 246
        y = self.out(y)
        return y
W
WuHaobo 已提交
247 248


249 250
def MobileNetV1_x0_25(**args):
    model = MobileNet(scale=0.25, **args)
W
WuHaobo 已提交
251 252 253
    return model


254 255
def MobileNetV1_x0_5(**args):
    model = MobileNet(scale=0.5, **args)
W
WuHaobo 已提交
256 257 258
    return model


259 260
def MobileNetV1_x0_75(**args):
    model = MobileNet(scale=0.75, **args)
W
WuHaobo 已提交
261 262 263
    return model


264 265
def MobileNetV1(**args):
    model = MobileNet(scale=1.0, **args)
W
WuHaobo 已提交
266
    return model