mobilenet_v2.py 6.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 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.

15
#order: standard library, third party, local library 
16 17
import os
import time
18
import math
19 20 21 22 23 24 25 26
import sys
import numpy as np
import argparse
import paddle
import paddle.fluid as fluid
from paddle.fluid.initializer import MSRA
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.layer_helper import LayerHelper
C
chajchaj 已提交
27
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, BatchNorm, Linear
28 29 30 31 32 33 34
from paddle.fluid.dygraph.base import to_variable
from paddle.fluid import framework



class ConvBNLayer(fluid.dygraph.Layer):
    def __init__(self,
C
chajchaj 已提交
35
                 num_channels,
36 37 38 39 40 41 42
                 filter_size,
                 num_filters,
                 stride,
                 padding,
                 channels=None,
                 num_groups=1,
                 use_cudnn=True):
C
chajchaj 已提交
43
        super(ConvBNLayer, self).__init__()
44

C
chajchaj 已提交
45
        tmp_param = ParamAttr(name=self.full_name() + "_weights")
46
        self._conv = Conv2D(
C
chajchaj 已提交
47
            num_channels=num_channels,
48 49 50 51 52 53 54 55 56 57 58 59
            num_filters=num_filters,
            filter_size=filter_size,
            stride=stride,
            padding=padding,
            groups=num_groups,
            act=None,
            use_cudnn=use_cudnn,
            param_attr=tmp_param,
            bias_attr=False)

        self._batch_norm = BatchNorm(
            num_filters,
C
chajchaj 已提交
60 61 62 63
            param_attr=ParamAttr(name=self.full_name() + "_bn" + "_scale"),
            bias_attr=ParamAttr(name=self.full_name() + "_bn" + "_offset"),
            moving_mean_name=self.full_name() + "_bn" + '_mean',
            moving_variance_name=self.full_name() + "_bn" + '_variance')
64 65 66 67 68 69 70 71 72 73

    def forward(self, inputs, if_act=True):
        y = self._conv(inputs)
        y = self._batch_norm(y)
        if if_act:
            y = fluid.layers.relu6(y)
        return y


class InvertedResidualUnit(fluid.dygraph.Layer):
C
chajchaj 已提交
74 75 76 77 78 79 80 81 82 83
    def __init__(
            self,
            num_channels,
            num_in_filter,
            num_filters,
            stride,
            filter_size,
            padding,
            expansion_factor, ):
        super(InvertedResidualUnit, self).__init__()
84 85
        num_expfilter = int(round(num_in_filter * expansion_factor))
        self._expand_conv = ConvBNLayer(
C
chajchaj 已提交
86
            num_channels=num_channels,
87 88 89 90 91 92 93
            num_filters=num_expfilter,
            filter_size=1,
            stride=1,
            padding=0,
            num_groups=1)

        self._bottleneck_conv = ConvBNLayer(
C
chajchaj 已提交
94
            num_channels=num_expfilter,
95 96 97 98 99 100 101 102
            num_filters=num_expfilter,
            filter_size=filter_size,
            stride=stride,
            padding=padding,
            num_groups=num_expfilter,
            use_cudnn=False)

        self._linear_conv = ConvBNLayer(
C
chajchaj 已提交
103
            num_channels=num_expfilter,
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
            num_filters=num_filters,
            filter_size=1,
            stride=1,
            padding=0,
            num_groups=1)

    def forward(self, inputs, ifshortcut):
        y = self._expand_conv(inputs, if_act=True)
        y = self._bottleneck_conv(y, if_act=True)
        y = self._linear_conv(y, if_act=False)
        if ifshortcut:
            y = fluid.layers.elementwise_add(inputs, y)
        return y


class InvresiBlocks(fluid.dygraph.Layer):
C
chajchaj 已提交
120 121
    def __init__(self, in_c, t, c, n, s):
        super(InvresiBlocks, self).__init__()
122 123

        self._first_block = InvertedResidualUnit(
C
chajchaj 已提交
124
            num_channels=in_c,
125 126 127 128 129 130 131 132 133 134 135
            num_in_filter=in_c,
            num_filters=c,
            stride=s,
            filter_size=3,
            padding=1,
            expansion_factor=t)

        self._inv_blocks = []
        for i in range(1, n):
            tmp = self.add_sublayer(
                sublayer=InvertedResidualUnit(
C
chajchaj 已提交
136
                    num_channels=c,
137 138 139 140 141 142
                    num_in_filter=c,
                    num_filters=c,
                    stride=1,
                    filter_size=3,
                    padding=1,
                    expansion_factor=t),
C
chajchaj 已提交
143
                name=self.full_name() + "_" + str(i + 1))
144 145 146 147 148 149 150 151 152 153
            self._inv_blocks.append(tmp)

    def forward(self, inputs):
        y = self._first_block(inputs, ifshortcut=False)
        for inv_block in self._inv_blocks:
            y = inv_block(y, ifshortcut=True)
        return y


class MobileNetV2(fluid.dygraph.Layer):
C
chajchaj 已提交
154 155
    def __init__(self, class_dim=1000, scale=1.0):
        super(MobileNetV2, self).__init__()
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
        self.scale = scale
        self.class_dim = class_dim

        bottleneck_params_list = [
            (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),
        ]

        #1. conv1 
        self._conv1 = ConvBNLayer(
C
chajchaj 已提交
171
            num_channels=3,
172 173 174 175 176 177 178 179 180 181 182 183 184 185
            num_filters=int(32 * scale),
            filter_size=3,
            stride=2,
            padding=1)

        #2. bottleneck sequences
        self._invl = []
        i = 1
        in_c = int(32 * scale)
        for layer_setting in bottleneck_params_list:
            t, c, n, s = layer_setting
            i += 1
            tmp = self.add_sublayer(
                sublayer=InvresiBlocks(
C
chajchaj 已提交
186
                    in_c=in_c, t=t, c=int(c * scale), n=n, s=s),
187 188 189 190 191
                name='conv' + str(i))
            self._invl.append(tmp)
            in_c = int(c * scale)

        #3. last_conv
C
chajchaj 已提交
192
        self._out_c = int(1280 * scale) if scale > 1.0 else 1280
193
        self._conv9 = ConvBNLayer(
C
chajchaj 已提交
194 195
            num_channels=in_c,
            num_filters=self._out_c,
196 197 198 199 200
            filter_size=1,
            stride=1,
            padding=0)

        #4. pool
C
chajchaj 已提交
201
        self._pool2d_avg = Pool2D(pool_type='avg', global_pooling=True)
202 203

        #5. fc
C
chajchaj 已提交
204 205 206 207 208 209
        tmp_param = ParamAttr(name=self.full_name() + "fc10_weights")
        self._fc = Linear(
            self._out_c,
            class_dim,
            param_attr=tmp_param,
            bias_attr=ParamAttr(name="fc10_offset"))
210 211 212 213 214 215 216

    def forward(self, inputs):
        y = self._conv1(inputs, if_act=True)
        for inv in self._invl:
            y = inv(y)
        y = self._conv9(y, if_act=True)
        y = self._pool2d_avg(y)
C
chajchaj 已提交
217
        y = fluid.layers.reshape(y, shape=[-1, self._out_c])
218 219
        y = self._fc(y)
        return y