mobilenet_block.py 16.5 KB
Newer Older
C
ceci3 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# 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

import numpy as np
import paddle.fluid as fluid
from paddle.fluid.param_attr import ParamAttr
from .search_space_base import SearchSpaceBase
from .base_layer import conv_bn_layer
from .search_space_registry import SEARCHSPACE
C
update  
ceci3 已提交
25
from .utils import compute_downsample_num, check_points
C
ceci3 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

__all__ = ["MobileNetV1BlockSpace", "MobileNetV2BlockSpace"]


@SEARCHSPACE.register
class MobileNetV2BlockSpace(SearchSpaceBase):
    def __init__(self,
                 input_size,
                 output_size,
                 block_num,
                 block_mask=None,
                 scale=1.0):
        super(MobileNetV2BlockSpace, self).__init__(input_size, output_size,
                                                    block_num, block_mask)

C
ceci3 已提交
41 42
        if self.block_mask == None:
            # use input_size and output_size to compute self.downsample_num
C
update  
ceci3 已提交
43 44
            self.downsample_num = compute_downsample_num(self.input_size,
                                                         self.output_size)
C
ceci3 已提交
45
        if self.block_num != None:
C
update  
ceci3 已提交
46 47
            assert self.downsample_num <= self.block_num, 'downsample numeber must be LESS THAN OR EQUAL TO block_num, but NOW: downsample numeber is {}, block_num is {}'.format(
                self.downsample_num, self.block_num)
C
ceci3 已提交
48 49

        # self.filter_num means channel number
C
update  
ceci3 已提交
50 51 52 53
        self.filter_num = np.array([
            3, 4, 8, 12, 16, 24, 32, 48, 64, 80, 96, 128, 144, 160, 192, 224,
            256, 320, 384, 512
        ])  # 20
C
ceci3 已提交
54 55 56 57 58 59 60 61 62 63 64 65
        # self.k_size means kernel size
        self.k_size = np.array([3, 5])  #2
        # self.multiply means expansion_factor of each _inverted_residual_unit
        self.multiply = np.array([1, 2, 3, 4, 5, 6])  #6
        # self.repeat means repeat_num _inverted_residual_unit in each _invresi_blocks
        self.repeat = np.array([1, 2, 3, 4, 5, 6])  #6
        self.scale = scale

    def init_tokens(self):
        if self.block_mask != None:
            return [0] * (len(self.block_mask) * 4)
        else:
C
update  
ceci3 已提交
66
            return [0] * (self.block_num * 4)
C
ceci3 已提交
67 68 69 70

    def range_table(self):
        range_table_base = []
        if self.block_mask != None:
C
update  
ceci3 已提交
71
            range_table_length = len(self.block_mask)
C
ceci3 已提交
72
        else:
C
ceci3 已提交
73
            range_table_length = self.block_num
C
update  
ceci3 已提交
74 75 76 77 78 79 80

        for i in range(range_table_length):
            range_table_base.append(len(self.multiply))
            range_table_base.append(len(self.filter_num))
            range_table_base.append(len(self.repeat))
            range_table_base.append(len(self.k_size))

C
ceci3 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        return range_table_base

    def token2arch(self, tokens=None):
        """
        return mobilenetv2 net_arch function
        """

        if tokens == None:
            tokens = self.init_tokens()

        self.bottleneck_params_list = []
        if self.block_mask != None:
            for i in range(len(self.block_mask)):
                self.bottleneck_params_list.append(
                    (self.multiply[tokens[i * 4]],
                     self.filter_num[tokens[i * 4 + 1]],
                     self.repeat[tokens[i * 4 + 2]], 2
                     if self.block_mask[i] == 1 else 1,
                     self.k_size[tokens[i * 4 + 3]]))
        else:
C
ceci3 已提交
101
            repeat_num = int(self.block_num / self.downsample_num)
C
ceci3 已提交
102 103 104
            num_minus = self.block_num % self.downsample_num
            ### if block_num > downsample_num, add stride=1 block at last (block_num-downsample_num) layers
            for i in range(self.downsample_num):
C
update  
ceci3 已提交
105 106 107 108 109
                self.bottleneck_params_list.append(
                    (self.multiply[tokens[i * 4]],
                     self.filter_num[tokens[i * 4 + 1]],
                     self.repeat[tokens[i * 4 + 2]], 2,
                     self.k_size[tokens[i * 4 + 3]]))
C
ceci3 已提交
110 111 112 113

                ### if block_num / downsample_num > 1, add (block_num / downsample_num) times stride=1 block 
                for k in range(repeat_num - 1):
                    kk = k * self.downsample_num + i
C
update  
ceci3 已提交
114 115 116 117 118 119
                    self.bottleneck_params_list.append(
                        (self.multiply[tokens[kk * 4]],
                         self.filter_num[tokens[kk * 4 + 1]],
                         self.repeat[tokens[kk * 4 + 2]], 1,
                         self.k_size[tokens[kk * 4 + 3]]))

C
ceci3 已提交
120
                if self.downsample_num - i <= num_minus:
C
ceci3 已提交
121
                    j = self.downsample_num * (repeat_num - 1) + i
C
update  
ceci3 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134
                    self.bottleneck_params_list.append(
                        (self.multiply[tokens[j * 4]],
                         self.filter_num[tokens[j * 4 + 1]],
                         self.repeat[tokens[j * 4 + 2]], 1,
                         self.k_size[tokens[j * 4 + 3]]))

            if self.downsample_num == 0 and self.block_num != 0:
                for i in range(len(self.block_num)):
                    self.bottleneck_params_list.append(
                        (self.multiply[tokens[i * 4]],
                         self.filter_num[tokens[i * 4 + 1]],
                         self.repeat[tokens[i * 4 + 2]], 1,
                         self.k_size[tokens[i * 4 + 3]]))
C
ceci3 已提交
135

C
update  
ceci3 已提交
136
        def net_arch(input, return_mid_layer=False, return_block=None):
C
ceci3 已提交
137 138 139
            # all padding is 'SAME' in the conv2d, can compute the actual padding automatic. 
            # bottleneck sequences
            in_c = int(32 * self.scale)
C
ceci3 已提交
140 141 142 143
            mid_layer = dict()
            layer_count = 0
            depthwise_conv = None

C
ceci3 已提交
144 145
            for i, layer_setting in enumerate(self.bottleneck_params_list):
                t, c, n, s, k = layer_setting
C
ceci3 已提交
146 147 148

                if s == 2:
                    layer_count += 1
C
update  
ceci3 已提交
149
                if check_points((layer_count - 1), return_block):
C
update  
ceci3 已提交
150
                    mid_layer[layer_count - 1] = depthwise_conv
C
ceci3 已提交
151

C
ceci3 已提交
152 153 154 155 156 157 158 159
                input, depthwise_conv = self._invresi_blocks(
                    input=input,
                    in_c=in_c,
                    t=t,
                    c=int(c * self.scale),
                    n=n,
                    s=s,
                    k=k,
C
update  
ceci3 已提交
160
                    name='mobilenetv2_' + str(i + 1))
C
ceci3 已提交
161 162
                in_c = int(c * self.scale)

C
update  
ceci3 已提交
163
            if check_points(layer_count, return_block):
C
update  
ceci3 已提交
164 165
                mid_layer[layer_count] = depthwise_conv

C
ceci3 已提交
166
            if return_mid_layer:
C
ceci3 已提交
167
                return input, mid_layer
C
ceci3 已提交
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 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
            else:
                return input,

        return net_arch

    def _shortcut(self, input, data_residual):
        """Build shortcut layer.
        Args:
            input(Variable): input.
            data_residual(Variable): residual layer.
        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:
            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.
            padding(str|int|list), padding.
            expansion_factor(float), expansion factor.
            name(str), name.
        Returns:
            Variable, layers output.
        """
        num_expfilter = int(round(num_in_filter * expansion_factor))
        channel_expand = conv_bn_layer(
            input=input,
            num_filters=num_expfilter,
            filter_size=1,
            stride=1,
            padding='SAME',
            num_groups=1,
            act='relu6',
            name=name + '_expand')

        bottleneck_conv = conv_bn_layer(
            input=channel_expand,
            num_filters=num_expfilter,
            filter_size=filter_size,
            stride=stride,
            padding='SAME',
            num_groups=num_expfilter,
            act='relu6',
            name=name + '_dwise',
            use_cudnn=False)

        depthwise_output = bottleneck_conv

        linear_out = conv_bn_layer(
            input=bottleneck_conv,
            num_filters=num_filters,
            filter_size=1,
            stride=1,
            padding='SAME',
            num_groups=1,
            act=None,
            name=name + '_linear')
        out = linear_out
        if ifshortcut:
            out = self._shortcut(input=input, data_residual=out)
        return out, depthwise_output

    def _invresi_blocks(self, input, in_c, t, c, n, s, k, name=None):
        """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, depthwise_output = 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, depthwise_output = 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, depthwise_output


@SEARCHSPACE.register
class MobileNetV1BlockSpace(SearchSpaceBase):
C
update  
ceci3 已提交
287 288 289 290 291 292 293 294
    def __init__(self,
                 input_size,
                 output_size,
                 block_num,
                 block_mask=None,
                 scale=1.0):
        super(MobileNetV1BlockSpace, self).__init__(input_size, output_size,
                                                    block_num, block_mask)
C
ceci3 已提交
295
        # use input_size and output_size to compute self.downsample_num
C
update  
ceci3 已提交
296 297
        self.downsample_num = compute_downsample_num(self.input_size,
                                                     self.output_size)
C
ceci3 已提交
298
        if self.block_num != None:
C
update  
ceci3 已提交
299 300
            assert self.downsample_num <= self.block_num, 'downsample numeber must be LESS THAN OR EQUAL TO block_num, but NOW: downsample numeber is {}, block_num is {}'.format(
                self.downsample_num, self.block_num)
C
ceci3 已提交
301 302

        # self.filter_num means channel number
C
update  
ceci3 已提交
303 304 305 306
        self.filter_num = np.array([
            3, 4, 8, 12, 16, 24, 32, 48, 64, 80, 96, 128, 144, 160, 192, 224,
            256, 320, 384, 512, 576, 640, 768, 1024, 1048
        ])
C
ceci3 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        self.k_size = np.array([3, 5])
        self.scale = scale

    def init_tokens(self):
        if self.block_mask != None:
            return [0] * (len(self.block_mask) * 3)
        else:
            return [0] * (self.block_num * 3)

    def range_table(self):
        range_table_base = []
        if self.block_mask != None:
            for i in range(len(self.block_mask)):
                range_table_base.append(len(self.filter_num))
                range_table_base.append(len(self.filter_num))
                range_table_base.append(len(self.k_size))
        else:
C
ceci3 已提交
324
            for i in range(self.block_num):
C
ceci3 已提交
325 326 327 328 329 330 331 332 333 334
                range_table_base.append(len(self.filter_num))
                range_table_base.append(len(self.filter_num))
                range_table_base.append(len(self.k_size))

        return range_table_base

    def token2arch(self, tokens=None):
        if tokens == None:
            tokens = self.init_tokens()

C
fix  
ceci3 已提交
335
        self.bottleneck_params_list = []
C
ceci3 已提交
336
        if self.block_mask != None:
C
ceci3 已提交
337
            for i in range(len(self.block_mask)):
C
update  
ceci3 已提交
338 339 340 341 342
                self.bottleneck_params_list.append(
                    (self.filter_num[tokens[i * 3]],
                     self.filter_num[tokens[i * 3 + 1]], 2
                     if self.block_mask[i] == 1 else 1,
                     self.k_size[tokens[i * 3 + 2]]))
C
ceci3 已提交
343
        else:
C
ceci3 已提交
344
            repeat_num = int(self.block_num / self.downsample_num)
C
ceci3 已提交
345
            num_minus = self.block_num % self.downsample_num
C
ceci3 已提交
346
            for i in range(self.downsample_num):
C
ceci3 已提交
347
                ### if block_num > downsample_num, add stride=1 block at last (block_num-downsample_num) layers
C
update  
ceci3 已提交
348 349 350 351
                self.bottleneck_params_list.append(
                    (self.filter_num[tokens[i * 3]],
                     self.filter_num[tokens[i * 3 + 1]], 2,
                     self.k_size[tokens[i * 3 + 2]]))
C
ceci3 已提交
352 353 354 355

                ### if block_num / downsample_num > 1, add (block_num / downsample_num) times stride=1 block 
                for k in range(repeat_num - 1):
                    kk = k * self.downsample_num + i
C
update  
ceci3 已提交
356 357 358 359 360
                    self.bottleneck_params_list.append(
                        (self.filter_num[tokens[kk * 3]],
                         self.filter_num[tokens[kk * 3 + 1]], 1,
                         self.k_size[tokens[kk * 3 + 2]]))

C
ceci3 已提交
361
                if self.downsample_num - i <= num_minus:
C
ceci3 已提交
362
                    j = self.downsample_num * (repeat_num - 1) + i
C
update  
ceci3 已提交
363 364 365 366 367 368 369 370 371 372 373
                    self.bottleneck_params_list.append(
                        (self.filter_num[tokens[j * 3]],
                         self.filter_num[tokens[j * 3 + 1]], 1,
                         self.k_size[tokens[j * 3 + 2]]))

            if self.downsample_num == 0 and self.block_num != 0:
                for i in range(len(self.block_num)):
                    self.bottleneck_params_list.append(
                        (self.filter_num[tokens[i * 3]],
                         self.filter_num[tokens[i * 3 + 1]], 1,
                         self.k_size[tokens[i * 3 + 2]]))
C
ceci3 已提交
374

C
update  
ceci3 已提交
375
        def net_arch(input, return_mid_layer=False, return_block=None):
C
ceci3 已提交
376 377
            mid_layer = dict()
            layer_count = 0
C
update  
ceci3 已提交
378

C
ceci3 已提交
379 380
            for i, layer_setting in enumerate(self.bottleneck_params_list):
                filter_num1, filter_num2, stride, kernel_size = layer_setting
C
ceci3 已提交
381 382
                if stride == 2:
                    layer_count += 1
C
update  
ceci3 已提交
383
                if check_points((layer_count - 1), return_block):
C
update  
ceci3 已提交
384
                    mid_layer[layer_count - 1] = input
C
ceci3 已提交
385

C
ceci3 已提交
386 387 388 389 390 391 392 393
                input = self._depthwise_separable(
                    input=input,
                    num_filters1=filter_num1,
                    num_filters2=filter_num2,
                    stride=stride,
                    scale=self.scale,
                    kernel_size=kernel_size,
                    name='mobilenetv1_{}'.format(str(i + 1)))
C
update  
ceci3 已提交
394

C
ceci3 已提交
395 396 397
            if return_mid_layer:
                return input, mid_layer
            else:
C
ceci3 已提交
398
                return input,
C
ceci3 已提交
399 400 401 402 403 404 405 406 407 408 409

        return net_arch

    def _depthwise_separable(self,
                             input,
                             num_filters1,
                             num_filters2,
                             stride,
                             scale,
                             kernel_size,
                             name=None):
C
fix  
ceci3 已提交
410
        num_groups = input.shape[1]
C
ceci3 已提交
411 412 413 414 415 416 417

        s_oc = int(num_filters1 * scale)
        if s_oc > num_groups:
            output_channel = s_oc - (s_oc % num_groups)
        else:
            output_channel = num_groups

C
ceci3 已提交
418 419 420
        depthwise_conv = conv_bn_layer(
            input=input,
            filter_size=kernel_size,
C
ceci3 已提交
421
            num_filters=output_channel,
C
ceci3 已提交
422
            stride=stride,
C
fix  
ceci3 已提交
423
            num_groups=num_groups,
C
ceci3 已提交
424 425 426 427 428 429 430 431 432 433
            use_cudnn=False,
            name=name + '_dw')
        pointwise_conv = conv_bn_layer(
            input=depthwise_conv,
            filter_size=1,
            num_filters=int(num_filters2 * scale),
            stride=1,
            name=name + '_sep')

        return pointwise_conv