shufflenet_v2.py 9.9 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
from paddle import ParamAttr, reshape, transpose, concat, split
20 21
from paddle.nn import Layer, Conv2D, MaxPool2D, AdaptiveAvgPool2D, BatchNorm, Linear
from paddle.nn.initializer import KaimingNormal
W
weishengyu 已提交
22
from paddle.nn.functional import swish
23

W
WuHaobo 已提交
24
__all__ = [
25
    "ShuffleNetV2_x0_25", "ShuffleNetV2_x0_33", "ShuffleNetV2_x0_5",
L
littletomatodonkey 已提交
26
    "ShuffleNetV2_x1_0", "ShuffleNetV2_x1_5", "ShuffleNetV2_x2_0",
27
    "ShuffleNetV2_swish"
W
WuHaobo 已提交
28 29 30
]


31
def channel_shuffle(x, groups):
32
    batch_size, num_channels, height, width = x.shape[0:4]
33 34 35
    channels_per_group = num_channels // groups

    # reshape
W
weishengyu 已提交
36 37
    x = reshape(
        x=x, shape=[batch_size, groups, channels_per_group, height, width])
38 39 40

    # transpose
    x = transpose(x=x, perm=[0, 2, 1, 3, 4])
41 42

    # flatten
43
    x = reshape(x=x, shape=[batch_size, num_channels, height, width])
44 45 46
    return x


47 48 49 50 51 52 53 54 55
class ConvBNLayer(Layer):
    def __init__(
            self,
            in_channels,
            out_channels,
            kernel_size,
            stride,
            padding,
            groups=1,
W
weishengyu 已提交
56
            act=None,
W
weishengyu 已提交
57
            name=None, ):
58
        super(ConvBNLayer, self).__init__()
59
        self._conv = Conv2D(
60 61 62
            in_channels=in_channels,
            out_channels=out_channels,
            kernel_size=kernel_size,
W
WuHaobo 已提交
63 64
            stride=stride,
            padding=padding,
65
            groups=groups,
W
weishengyu 已提交
66
            weight_attr=ParamAttr(
67
                initializer=KaimingNormal(), name=name + "_weights"),
W
weishengyu 已提交
68
            bias_attr=False)
W
WuHaobo 已提交
69

70
        self._batch_norm = BatchNorm(
71
            out_channels,
72 73
            param_attr=ParamAttr(name=name + "_bn_scale"),
            bias_attr=ParamAttr(name=name + "_bn_offset"),
W
weishengyu 已提交
74
            act=act,
75
            moving_mean_name=name + "_bn_mean",
W
weishengyu 已提交
76
            moving_variance_name=name + "_bn_variance")
77

78
    def forward(self, inputs):
79 80 81 82 83
        y = self._conv(inputs)
        y = self._batch_norm(y)
        return y


84
class InvertedResidual(Layer):
W
weishengyu 已提交
85 86 87 88 89 90
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 act="relu",
                 name=None):
91 92 93 94 95 96 97 98 99
        super(InvertedResidual, self).__init__()
        self._conv_pw = ConvBNLayer(
            in_channels=in_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
100
            name='stage_' + name + '_conv1')
101 102 103 104 105 106 107 108
        self._conv_dw = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=3,
            stride=stride,
            padding=1,
            groups=out_channels // 2,
            act=None,
W
weishengyu 已提交
109
            name='stage_' + name + '_conv2')
110 111 112 113 114 115 116 117
        self._conv_linear = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
118
            name='stage_' + name + '_conv3')
W
WuHaobo 已提交
119

120
    def forward(self, inputs):
W
weishengyu 已提交
121 122 123 124
        x1, x2 = split(
            inputs,
            num_or_sections=[inputs.shape[1] // 2, inputs.shape[1] // 2],
            axis=1)
125 126 127 128 129 130 131 132
        x2 = self._conv_pw(x2)
        x2 = self._conv_dw(x2)
        x2 = self._conv_linear(x2)
        out = concat([x1, x2], axis=1)
        return channel_shuffle(out, 2)


class InvertedResidualDS(Layer):
W
weishengyu 已提交
133 134 135 136 137 138
    def __init__(self,
                 in_channels,
                 out_channels,
                 stride,
                 act="relu",
                 name=None):
139 140 141 142 143 144 145 146 147 148 149
        super(InvertedResidualDS, self).__init__()

        # branch1
        self._conv_dw_1 = ConvBNLayer(
            in_channels=in_channels,
            out_channels=in_channels,
            kernel_size=3,
            stride=stride,
            padding=1,
            groups=in_channels,
            act=None,
W
weishengyu 已提交
150
            name='stage_' + name + '_conv4')
151 152 153 154 155 156 157 158
        self._conv_linear_1 = ConvBNLayer(
            in_channels=in_channels,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
159
            name='stage_' + name + '_conv5')
160 161 162 163 164 165 166 167 168
        # branch2
        self._conv_pw_2 = ConvBNLayer(
            in_channels=in_channels,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
169
            name='stage_' + name + '_conv1')
170 171 172 173 174 175 176 177
        self._conv_dw_2 = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=3,
            stride=stride,
            padding=1,
            groups=out_channels // 2,
            act=None,
W
weishengyu 已提交
178
            name='stage_' + name + '_conv2')
179 180 181 182 183 184 185 186
        self._conv_linear_2 = ConvBNLayer(
            in_channels=out_channels // 2,
            out_channels=out_channels // 2,
            kernel_size=1,
            stride=1,
            padding=0,
            groups=1,
            act=act,
W
weishengyu 已提交
187
            name='stage_' + name + '_conv3')
188 189 190 191 192 193 194 195

    def forward(self, inputs):
        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 = concat([x1, x2], axis=1)
196 197 198 199

        return channel_shuffle(out, 2)


200
class ShuffleNet(Layer):
W
weishengyu 已提交
201
    def __init__(self, class_dim=1000, scale=1.0, act="relu"):
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        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(
224 225 226
            in_channels=3,
            out_channels=stage_out_channels[1],
            kernel_size=3,
227 228 229
            stride=2,
            padding=1,
            act=act,
W
weishengyu 已提交
230
            name='stage1_conv')
231
        self._max_pool = MaxPool2D(kernel_size=3, stride=2, padding=1)
232 233 234

        # 2. bottleneck sequences
        self._block_list = []
235 236
        for stage_id, num_repeat in enumerate(stage_repeats):
            for i in range(num_repeat):
237 238
                if i == 0:
                    block = self.add_sublayer(
239 240 241 242
                        name=str(stage_id + 2) + '_' + str(i + 1),
                        sublayer=InvertedResidualDS(
                            in_channels=stage_out_channels[stage_id + 1],
                            out_channels=stage_out_channels[stage_id + 2],
243 244
                            stride=2,
                            act=act,
W
weishengyu 已提交
245
                            name=str(stage_id + 2) + '_' + str(i + 1)))
246 247
                else:
                    block = self.add_sublayer(
248 249 250 251
                        name=str(stage_id + 2) + '_' + str(i + 1),
                        sublayer=InvertedResidual(
                            in_channels=stage_out_channels[stage_id + 2],
                            out_channels=stage_out_channels[stage_id + 2],
252 253
                            stride=1,
                            act=act,
W
weishengyu 已提交
254
                            name=str(stage_id + 2) + '_' + str(i + 1)))
255
                self._block_list.append(block)
256 257
        # 3. last_conv
        self._last_conv = ConvBNLayer(
258 259 260
            in_channels=stage_out_channels[-2],
            out_channels=stage_out_channels[-1],
            kernel_size=1,
261 262 263
            stride=1,
            padding=0,
            act=act,
W
weishengyu 已提交
264
            name='conv5')
265
        # 4. pool
266
        self._pool2d_avg = AdaptiveAvgPool2D(1)
267 268 269 270 271
        self._out_c = stage_out_channels[-1]
        # 5. fc
        self._fc = Linear(
            stage_out_channels[-1],
            class_dim,
272
            weight_attr=ParamAttr(name='fc6_weights'),
W
weishengyu 已提交
273
            bias_attr=ParamAttr(name='fc6_offset'))
274 275 276 277 278 279 280 281

    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)
282
        y = reshape(y, shape=[-1, self._out_c])
283 284 285 286 287
        y = self._fc(y)
        return y


def ShuffleNetV2_x0_25(**args):
W
dbg  
weishengyu 已提交
288
    model = ShuffleNet(scale=0.25, **args)
289
    return model
W
WuHaobo 已提交
290 291


292 293
def ShuffleNetV2_x0_33(**args):
    model = ShuffleNet(scale=0.33, **args)
W
WuHaobo 已提交
294 295 296
    return model


297 298
def ShuffleNetV2_x0_5(**args):
    model = ShuffleNet(scale=0.5, **args)
W
WuHaobo 已提交
299 300 301
    return model


L
littletomatodonkey 已提交
302
def ShuffleNetV2_x1_0(**args):
303
    model = ShuffleNet(scale=1.0, **args)
W
WuHaobo 已提交
304 305 306
    return model


307 308
def ShuffleNetV2_x1_5(**args):
    model = ShuffleNet(scale=1.5, **args)
W
WuHaobo 已提交
309 310 311
    return model


312 313
def ShuffleNetV2_x2_0(**args):
    model = ShuffleNet(scale=2.0, **args)
W
WuHaobo 已提交
314 315 316
    return model


317
def ShuffleNetV2_swish(**args):
W
dbg  
weishengyu 已提交
318
    model = ShuffleNet(scale=1.0, act="swish", **args)
W
WuHaobo 已提交
319
    return model