mobilenetv2_space.py 10.3 KB
Newer Older
C
ceci3 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright (c) 2019  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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

C
ceci3 已提交
19
import sys
C
ceci3 已提交
20
import numpy as np
C
ceci3 已提交
21 22
import paddle.fluid as fluid
from paddle.fluid.param_attr import ParamAttr
23
from .search_space_base import SearchSpaceBase
C
ceci3 已提交
24
from .base_layer import conv_bn_layer
25
from .search_space_registry import SEARCHSPACE
C
ceci3 已提交
26

27 28

@SEARCHSPACE.register
C
ceci3 已提交
29
class MobileNetV2Space(SearchSpaceBase):
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    def __init__(self,
                 input_size,
                 output_size,
                 block_num,
                 scale=1.0,
                 class_dim=1000):
        super(MobileNetV2Space, self).__init__(input_size, output_size,
                                               block_num)
        self.head_num = np.array([3, 4, 8, 12, 16, 24, 32])  #7
        self.filter_num1 = np.array([3, 4, 8, 12, 16, 24, 32, 48])  #8
        self.filter_num2 = np.array([8, 12, 16, 24, 32, 48, 64, 80])  #8
        self.filter_num3 = np.array([16, 24, 32, 48, 64, 80, 96, 128])  #8
        self.filter_num4 = np.array(
            [24, 32, 48, 64, 80, 96, 128, 144, 160, 192])  #10
        self.filter_num5 = np.array(
            [32, 48, 64, 80, 96, 128, 144, 160, 192, 224])  #10
        self.filter_num6 = np.array(
            [64, 80, 96, 128, 144, 160, 192, 224, 256, 320, 384, 512])  #12
        self.k_size = np.array([3, 5])  #2
        self.multiply = np.array([1, 2, 3, 4, 6])  #5
        self.repeat = np.array([1, 2, 3, 4, 5, 6])  #6
        self.scale = scale
        self.class_dim = class_dim
C
ceci3 已提交
53 54 55

    def init_tokens(self):
        """
C
ceci3 已提交
56
        The initial token send to controller.
C
ceci3 已提交
57 58
        The first one is the index of the first layers' channel in self.head_num,
        each line in the following represent the index of the [expansion_factor, filter_num, repeat_num, kernel_size]
C
ceci3 已提交
59 60
        """
        # original MobileNetV2
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        return [
            4,  # 1, 16, 1
            4,
            5,
            1,
            0,  # 6, 24, 1
            4,
            5,
            1,
            0,  # 6, 24, 2
            4,
            4,
            2,
            0,  # 6, 32, 3
            4,
            4,
            3,
            0,  # 6, 64, 4
            4,
            5,
            2,
            0,  # 6, 96, 3
            4,
            7,
            2,
            0,  # 6, 160, 3
            4,
            9,
            0,
            0
        ]  # 6, 320, 1
C
ceci3 已提交
92 93 94 95 96 97

    def range_table(self):
        """
        get range table of current search space 
        """
        # head_num + 7 * [multiple(expansion_factor), filter_num, repeat, kernel_size]
98 99 100 101
        return [
            7, 5, 8, 6, 2, 5, 8, 6, 2, 5, 8, 6, 2, 5, 8, 6, 2, 5, 10, 6, 2, 5,
            10, 6, 2, 5, 12, 6, 2
        ]
C
ceci3 已提交
102 103 104

    def token2arch(self, tokens=None):
        """
C
ceci3 已提交
105
        return net_arch function
C
ceci3 已提交
106 107 108 109
        """
        if tokens is None:
            tokens = self.init_tokens()

C
ceci3 已提交
110
        base_bottleneck_params_list = [
C
ceci3 已提交
111
            (1, self.head_num[tokens[0]], 1, 1, 3),
112 113 114 115 116 117 118 119 120 121 122 123 124 125
            (self.multiply[tokens[1]], self.filter_num1[tokens[2]],
             self.repeat[tokens[3]], 2, self.k_size[tokens[4]]),
            (self.multiply[tokens[5]], self.filter_num1[tokens[6]],
             self.repeat[tokens[7]], 2, self.k_size[tokens[8]]),
            (self.multiply[tokens[9]], self.filter_num2[tokens[10]],
             self.repeat[tokens[11]], 2, self.k_size[tokens[12]]),
            (self.multiply[tokens[13]], self.filter_num3[tokens[14]],
             self.repeat[tokens[15]], 2, self.k_size[tokens[16]]),
            (self.multiply[tokens[17]], self.filter_num3[tokens[18]],
             self.repeat[tokens[19]], 1, self.k_size[tokens[20]]),
            (self.multiply[tokens[21]], self.filter_num5[tokens[22]],
             self.repeat[tokens[23]], 2, self.k_size[tokens[24]]),
            (self.multiply[tokens[25]], self.filter_num6[tokens[26]],
             self.repeat[tokens[27]], 1, self.k_size[tokens[28]]),
C
ceci3 已提交
126
        ]
C
ceci3 已提交
127

128 129
        assert self.block_num < 7, 'block number must less than 7, but receive block number is {}'.format(
            self.block_num)
C
ceci3 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142

        # the stride = 2 means downsample feature map in the convolution, so only when stride=2, block_num minus 1,
        # otherwise, add layers to params_list directly.
        bottleneck_params_list = []
        for param_list in base_bottleneck_params_list:
            if param_list[3] == 1:
                bottleneck_params_list.append(param_list)
            else:
                if self.block_num > 1:
                    bottleneck_params_list.append(param_list)
                    self.block_num -= 1
                else:
                    break
C
ceci3 已提交
143

C
ceci3 已提交
144
        def net_arch(input):
C
ceci3 已提交
145
            #conv1
C
ceci3 已提交
146
            # all padding is 'SAME' in the conv2d, can compute the actual padding automatic. 
C
ceci3 已提交
147
            input = conv_bn_layer(
C
ceci3 已提交
148 149 150 151
                input,
                num_filters=int(32 * self.scale),
                filter_size=3,
                stride=2,
C
ceci3 已提交
152 153
                padding='SAME',
                act='relu6',
C
ceci3 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
                name='conv1_1')

            # bottleneck sequences
            i = 1
            in_c = int(32 * self.scale)
            for layer_setting in bottleneck_params_list:
                t, c, n, s, k = layer_setting
                i += 1
                input = self.invresi_blocks(
                    input=input,
                    in_c=in_c,
                    t=t,
                    c=int(c * self.scale),
                    n=n,
                    s=s,
                    k=k,
                    name='conv' + str(i))
                in_c = int(c * self.scale)
C
ceci3 已提交
172 173 174

            # if output_size is 1, add fc layer in the end
            if self.output_size == 1:
175 176 177 178 179
                input = fluid.layers.fc(
                    input=input,
                    size=self.class_dim,
                    param_attr=ParamAttr(name='fc10_weights'),
                    bias_attr=ParamAttr(name='fc10_offset'))
C
ceci3 已提交
180 181 182 183 184
            else:
                assert self.output_size == input.shape[2], \
                          ("output_size must EQUAL to input_size / (2^block_num)."
                          "But receive input_size={}, output_size={}, block_num={}".format(
                          self.input_size, self.output_size, self.block_num))
C
ceci3 已提交
185

C
ceci3 已提交
186 187
            return input

C
ceci3 已提交
188
        return net_arch
C
ceci3 已提交
189 190 191 192

    def shortcut(self, input, data_residual):
        """Build shortcut layer.
        Args:
C
ceci3 已提交
193 194
            input(Variable): input.
            data_residual(Variable): residual layer.
C
ceci3 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        Returns:
            Variable, layer output.
        """
        return fluid.layers.elementwise_add(input, data_residual)

    def inverted_residual_unit(self,
                               input,
                               num_in_filter,
                               num_filters,
                               ifshortcut,
                               stride,
                               filter_size,
                               expansion_factor,
                               reduction_ratio=4,
                               name=None):
        """Build inverted residual unit.
        Args:
C
ceci3 已提交
212 213 214 215 216 217
            input(Variable), input.
            num_in_filter(int), number of in filters.
            num_filters(int), number of filters.
            ifshortcut(bool), whether using shortcut.
            stride(int), stride.
            filter_size(int), filter size.
C
ceci3 已提交
218
            padding(str|int|list), padding.
C
ceci3 已提交
219 220
            expansion_factor(float), expansion factor.
            name(str), name.
C
ceci3 已提交
221 222 223 224
        Returns:
            Variable, layers output.
        """
        num_expfilter = int(round(num_in_filter * expansion_factor))
C
ceci3 已提交
225
        channel_expand = conv_bn_layer(
C
ceci3 已提交
226 227 228 229
            input=input,
            num_filters=num_expfilter,
            filter_size=1,
            stride=1,
C
ceci3 已提交
230
            padding='SAME',
C
ceci3 已提交
231
            num_groups=1,
C
ceci3 已提交
232
            act='relu6',
C
ceci3 已提交
233 234
            name=name + '_expand')

C
ceci3 已提交
235
        bottleneck_conv = conv_bn_layer(
C
ceci3 已提交
236 237 238 239
            input=channel_expand,
            num_filters=num_expfilter,
            filter_size=filter_size,
            stride=stride,
C
ceci3 已提交
240
            padding='SAME',
C
ceci3 已提交
241
            num_groups=num_expfilter,
C
ceci3 已提交
242
            act='relu6',
C
ceci3 已提交
243 244 245
            name=name + '_dwise',
            use_cudnn=False)

C
ceci3 已提交
246
        linear_out = conv_bn_layer(
C
ceci3 已提交
247 248 249 250
            input=bottleneck_conv,
            num_filters=num_filters,
            filter_size=1,
            stride=1,
C
ceci3 已提交
251
            padding='SAME',
C
ceci3 已提交
252
            num_groups=1,
C
ceci3 已提交
253
            act=None,
C
ceci3 已提交
254 255 256 257 258 259
            name=name + '_linear')
        out = linear_out
        if ifshortcut:
            out = self.shortcut(input=input, data_residual=out)
        return out

260
    def invresi_blocks(self, input, in_c, t, c, n, s, k, name=None):
C
ceci3 已提交
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
        """Build inverted residual blocks.
        Args:
            input: Variable, input.
            in_c: int, number of in filters.
            t: float, expansion factor.
            c: int, number of filters.
            n: int, number of layers.
            s: int, stride.
            k: int, filter size.
            name: str, name.
        Returns:
            Variable, layers output.
        """
        first_block = self.inverted_residual_unit(
            input=input,
            num_in_filter=in_c,
            num_filters=c,
            ifshortcut=False,
            stride=s,
            filter_size=k,
            expansion_factor=t,
            name=name + '_1')

        last_residual_block = first_block
        last_c = c

        for i in range(1, n):
            last_residual_block = self.inverted_residual_unit(
                input=last_residual_block,
                num_in_filter=last_c,
                num_filters=c,
                ifshortcut=True,
                stride=1,
                filter_size=k,
                expansion_factor=t,
                name=name + '_' + str(i + 1))
        return last_residual_block