shufflenet_v2.py 11.5 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
W
WuHaobo 已提交
21 22
import paddle.fluid as fluid
from paddle.fluid.param_attr import ParamAttr
23 24 25 26
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, BatchNorm, Linear, Dropout
from paddle.fluid.initializer import MSRA
import math
W
WuHaobo 已提交
27 28

__all__ = [
29 30 31
    "ShuffleNetV2_x0_25", "ShuffleNetV2_x0_33", "ShuffleNetV2_x0_5",
    "ShuffleNetV2_x1_0", "ShuffleNetV2_x1_5", "ShuffleNetV2_x2_0",
    "ShuffleNetV2_swish"
W
WuHaobo 已提交
32 33 34
]


35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
def channel_shuffle(x, groups):
    batchsize, num_channels, height, width = x.shape[0], x.shape[1], x.shape[
        2], x.shape[3]
    channels_per_group = num_channels // groups

    # reshape
    x = fluid.layers.reshape(
        x=x, shape=[batchsize, groups, channels_per_group, height, width])

    x = fluid.layers.transpose(x=x, perm=[0, 2, 1, 3, 4])
    # flatten
    x = fluid.layers.reshape(
        x=x, shape=[batchsize, num_channels, height, width])
    return x


class ConvBNLayer(fluid.dygraph.Layer):
    def __init__(self,
                 num_channels,
                 filter_size,
                 num_filters,
                 stride,
                 padding,
                 channels=None,
                 num_groups=1,
                 if_act=True,
                 act='relu',
                 name=None,
                 use_cudnn=True):
        super(ConvBNLayer, self).__init__()
        self._if_act = if_act
        assert act in ['relu', 'swish'], \
            "supported act are {} but your act is {}".format(
                ['relu', 'swish'], act)
        self._act = act
        self._conv = Conv2D(
            num_channels=num_channels,
W
WuHaobo 已提交
72 73 74 75 76 77 78 79
            num_filters=num_filters,
            filter_size=filter_size,
            stride=stride,
            padding=padding,
            groups=num_groups,
            act=None,
            use_cudnn=use_cudnn,
            param_attr=ParamAttr(
80
                initializer=MSRA(), name=name + "_weights"),
W
WuHaobo 已提交
81 82
            bias_attr=False)

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        self._batch_norm = BatchNorm(
            num_filters,
            param_attr=ParamAttr(name=name + "_bn_scale"),
            bias_attr=ParamAttr(name=name + "_bn_offset"),
            moving_mean_name=name + "_bn_mean",
            moving_variance_name=name + "_bn_variance")

    def forward(self, inputs, if_act=True):
        y = self._conv(inputs)
        y = self._batch_norm(y)
        if self._if_act:
            y = fluid.layers.relu(
                y) if self._act == 'relu' else fluid.layers.swish(y)
        return y


class InvertedResidualUnit(fluid.dygraph.Layer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 stride,
                 benchmodel,
                 act='relu',
                 name=None):
        super(InvertedResidualUnit, self).__init__()
        assert stride in [1, 2], \
            "supported stride are {} but your stride is {}".format([
                                                                   1, 2], stride)
        self.benchmodel = benchmodel
W
WuHaobo 已提交
112
        oup_inc = num_filters // 2
113
        inp = num_channels
W
WuHaobo 已提交
114
        if benchmodel == 1:
115 116
            self._conv_pw = ConvBNLayer(
                num_channels=num_channels // 2,
W
WuHaobo 已提交
117 118 119 120 121 122
                num_filters=oup_inc,
                filter_size=1,
                stride=1,
                padding=0,
                num_groups=1,
                if_act=True,
123
                act=act,
W
WuHaobo 已提交
124
                name='stage_' + name + '_conv1')
125 126
            self._conv_dw = ConvBNLayer(
                num_channels=oup_inc,
W
WuHaobo 已提交
127 128 129 130 131 132
                num_filters=oup_inc,
                filter_size=3,
                stride=stride,
                padding=1,
                num_groups=oup_inc,
                if_act=False,
133
                act=act,
W
WuHaobo 已提交
134 135
                use_cudnn=False,
                name='stage_' + name + '_conv2')
136 137
            self._conv_linear = ConvBNLayer(
                num_channels=oup_inc,
W
WuHaobo 已提交
138 139 140 141 142 143
                num_filters=oup_inc,
                filter_size=1,
                stride=1,
                padding=0,
                num_groups=1,
                if_act=True,
144
                act=act,
W
WuHaobo 已提交
145 146
                name='stage_' + name + '_conv3')
        else:
147 148 149
            # branch1
            self._conv_dw_1 = ConvBNLayer(
                num_channels=num_channels,
W
WuHaobo 已提交
150 151 152 153 154 155
                num_filters=inp,
                filter_size=3,
                stride=stride,
                padding=1,
                num_groups=inp,
                if_act=False,
156
                act=act,
W
WuHaobo 已提交
157 158
                use_cudnn=False,
                name='stage_' + name + '_conv4')
159 160
            self._conv_linear_1 = ConvBNLayer(
                num_channels=inp,
W
WuHaobo 已提交
161 162 163 164 165 166
                num_filters=oup_inc,
                filter_size=1,
                stride=1,
                padding=0,
                num_groups=1,
                if_act=True,
167
                act=act,
W
WuHaobo 已提交
168
                name='stage_' + name + '_conv5')
169 170 171
            # branch2
            self._conv_pw_2 = ConvBNLayer(
                num_channels=num_channels,
W
WuHaobo 已提交
172 173 174 175 176 177
                num_filters=oup_inc,
                filter_size=1,
                stride=1,
                padding=0,
                num_groups=1,
                if_act=True,
178
                act=act,
W
WuHaobo 已提交
179
                name='stage_' + name + '_conv1')
180 181
            self._conv_dw_2 = ConvBNLayer(
                num_channels=oup_inc,
W
WuHaobo 已提交
182 183 184 185 186 187
                num_filters=oup_inc,
                filter_size=3,
                stride=stride,
                padding=1,
                num_groups=oup_inc,
                if_act=False,
188
                act=act,
W
WuHaobo 已提交
189 190
                use_cudnn=False,
                name='stage_' + name + '_conv2')
191 192
            self._conv_linear_2 = ConvBNLayer(
                num_channels=oup_inc,
W
WuHaobo 已提交
193 194 195 196 197 198
                num_filters=oup_inc,
                filter_size=1,
                stride=1,
                padding=0,
                num_groups=1,
                if_act=True,
199
                act=act,
W
WuHaobo 已提交
200 201
                name='stage_' + name + '_conv3')

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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 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 321 322 323 324 325
    def forward(self, inputs):
        if self.benchmodel == 1:
            x1, x2 = fluid.layers.split(
                inputs,
                num_or_sections=[inputs.shape[1] // 2, inputs.shape[1] // 2],
                dim=1)
            x2 = self._conv_pw(x2)
            x2 = self._conv_dw(x2)
            x2 = self._conv_linear(x2)
            out = fluid.layers.concat([x1, x2], axis=1)
        else:
            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 = fluid.layers.concat([x1, x2], axis=1)

        return channel_shuffle(out, 2)


class ShuffleNet(fluid.dygraph.Layer):
    def __init__(self, class_dim=1000, scale=1.0, act='relu'):
        super(ShuffleNet, self).__init__()
        self.scale = scale
        self.class_dim = class_dim
        stage_repeats = [4, 8, 4]

        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
        self._conv1 = ConvBNLayer(
            num_channels=3,
            num_filters=stage_out_channels[1],
            filter_size=3,
            stride=2,
            padding=1,
            if_act=True,
            act=act,
            name='stage1_conv')
        self._max_pool = Pool2D(
            pool_type='max', pool_size=3, pool_stride=2, pool_padding=1)

        # 2. bottleneck sequences
        self._block_list = []
        i = 1
        in_c = int(32 * scale)
        for idxstage in range(len(stage_repeats)):
            numrepeat = stage_repeats[idxstage]
            output_channel = stage_out_channels[idxstage + 2]
            for i in range(numrepeat):
                if i == 0:
                    block = self.add_sublayer(
                        str(idxstage + 2) + '_' + str(i + 1),
                        InvertedResidualUnit(
                            num_channels=stage_out_channels[idxstage + 1],
                            num_filters=output_channel,
                            stride=2,
                            benchmodel=2,
                            act=act,
                            name=str(idxstage + 2) + '_' + str(i + 1)))
                    self._block_list.append(block)
                else:
                    block = self.add_sublayer(
                        str(idxstage + 2) + '_' + str(i + 1),
                        InvertedResidualUnit(
                            num_channels=output_channel,
                            num_filters=output_channel,
                            stride=1,
                            benchmodel=1,
                            act=act,
                            name=str(idxstage + 2) + '_' + str(i + 1)))
                    self._block_list.append(block)

        # 3. last_conv
        self._last_conv = ConvBNLayer(
            num_channels=stage_out_channels[-2],
            num_filters=stage_out_channels[-1],
            filter_size=1,
            stride=1,
            padding=0,
            if_act=True,
            act=act,
            name='conv5')

        # 4. pool
        self._pool2d_avg = Pool2D(pool_type='avg', global_pooling=True)
        self._out_c = stage_out_channels[-1]
        # 5. fc
        self._fc = Linear(
            stage_out_channels[-1],
            class_dim,
            param_attr=ParamAttr(name='fc6_weights'),
            bias_attr=ParamAttr(name='fc6_offset'))

    def forward(self, inputs):
        y = self._conv1(inputs)
        y = self._max_pool(y)
        for inv in self._block_list:
            y = inv(y)
        y = self._last_conv(y)
        y = self._pool2d_avg(y)
        y = fluid.layers.reshape(y, shape=[-1, self._out_c])
        y = self._fc(y)
        return y


def ShuffleNetV2_x0_25(**args):
    model = ShuffleNetV2(scale=0.25, **args)
    return model
W
WuHaobo 已提交
326 327


328 329
def ShuffleNetV2_x0_33(**args):
    model = ShuffleNet(scale=0.33, **args)
W
WuHaobo 已提交
330 331 332
    return model


333 334
def ShuffleNetV2_x0_5(**args):
    model = ShuffleNet(scale=0.5, **args)
W
WuHaobo 已提交
335 336 337
    return model


338 339
def ShuffleNetV2(**args):
    model = ShuffleNet(scale=1.0, **args)
W
WuHaobo 已提交
340 341 342
    return model


343 344
def ShuffleNetV2_x1_5(**args):
    model = ShuffleNet(scale=1.5, **args)
W
WuHaobo 已提交
345 346 347
    return model


348 349
def ShuffleNetV2_x2_0(**args):
    model = ShuffleNet(scale=2.0, **args)
W
WuHaobo 已提交
350 351 352
    return model


353 354
def ShuffleNetV2_swish(**args):
    model = ShuffleNet(scale=1.0, act='swish', **args)
W
WuHaobo 已提交
355
    return model