regnet.py 13.2 KB
Newer Older
C
cuicheng01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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.

C
cuicheng01 已提交
15
# Code was based on https://github.com/facebookresearch/pycls
G
gaotingquan 已提交
16
# reference: https://arxiv.org/abs/1905.13214
C
cuicheng01 已提交
17

C
cuicheng01 已提交
18 19 20 21 22 23 24 25
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import paddle
from paddle import ParamAttr
import paddle.nn as nn
26 27 28
import paddle.nn.functional as F
from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
C
cuicheng01 已提交
29 30 31
from paddle.nn.initializer import Uniform
import math

R
root 已提交
32
from ....utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url
C
cuicheng01 已提交
33

littletomatodonkey's avatar
littletomatodonkey 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47
MODEL_URLS = {
    "RegNetX_200MF":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RegNetX_200MF_pretrained.pdparams",
    "RegNetX_4GF":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RegNetX_4GF_pretrained.pdparams",
    "RegNetX_32GF":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RegNetX_32GF_pretrained.pdparams",
    "RegNetY_200MF":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RegNetY_200MF_pretrained.pdparams",
    "RegNetY_4GF":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RegNetY_4GF_pretrained.pdparams",
    "RegNetY_32GF":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RegNetY_32GF_pretrained.pdparams",
}
C
cuicheng01 已提交
48 49

__all__ = list(MODEL_URLS.keys())
C
cuicheng01 已提交
50

51

C
cuicheng01 已提交
52 53 54 55 56 57 58 59 60
def quantize_float(f, q):
    """Converts a float to closest non-zero int divisible by q."""
    return int(round(f / q) * q)


def adjust_ws_gs_comp(ws, bms, gs):
    """Adjusts the compatibility of widths and groups."""
    ws_bot = [int(w * b) for w, b in zip(ws, bms)]
    gs = [min(g, w_bot) for g, w_bot in zip(gs, ws_bot)]
61
    ws_bot = [quantize_float(w_bot, g) for w_bot, g in zip(ws_bot, gs)]
C
cuicheng01 已提交
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 92 93 94 95 96 97 98 99 100
    ws = [int(w_bot / b) for w_bot, b in zip(ws_bot, bms)]
    return ws, gs


def get_stages_from_blocks(ws, rs):
    """Gets ws/ds of network at each stage from per block values."""
    ts = [
        w != wp or r != rp
        for w, wp, r, rp in zip(ws + [0], [0] + ws, rs + [0], [0] + rs)
    ]
    s_ws = [w for w, t in zip(ws, ts[:-1]) if t]
    s_ds = np.diff([d for d, t in zip(range(len(ts)), ts) if t]).tolist()
    return s_ws, s_ds


def generate_regnet(w_a, w_0, w_m, d, q=8):
    """Generates per block ws from RegNet parameters."""
    assert w_a >= 0 and w_0 > 0 and w_m > 1 and w_0 % q == 0
    ws_cont = np.arange(d) * w_a + w_0
    ks = np.round(np.log(ws_cont / w_0) / np.log(w_m))
    ws = w_0 * np.power(w_m, ks)
    ws = np.round(np.divide(ws, q)) * q
    num_stages, max_stage = len(np.unique(ws)), ks.max() + 1
    ws, ws_cont = ws.astype(int).tolist(), ws_cont.tolist()
    return ws, num_stages, max_stage, ws_cont


class ConvBNLayer(nn.Layer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 groups=1,
                 padding=0,
                 act=None,
                 name=None):
        super(ConvBNLayer, self).__init__()

101
        self._conv = Conv2D(
C
cuicheng01 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
            stride=stride,
            padding=padding,
            groups=groups,
            weight_attr=ParamAttr(name=name + ".conv2d.output.1.w_0"),
            bias_attr=ParamAttr(name=name + ".conv2d.output.1.b_0"))
        bn_name = name + "_bn"
        self._batch_norm = BatchNorm(
            num_filters,
            act=act,
            param_attr=ParamAttr(name=bn_name + ".output.1.w_0"),
            bias_attr=ParamAttr(bn_name + ".output.1.b_0"),
            moving_mean_name=bn_name + "_mean",
            moving_variance_name=bn_name + "_variance")
118

C
cuicheng01 已提交
119 120 121 122
    def forward(self, inputs):
        y = self._conv(inputs)
        y = self._batch_norm(y)
        return y
123 124


C
cuicheng01 已提交
125 126 127 128 129
class BottleneckBlock(nn.Layer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 stride,
130 131
                 bm,
                 gw,
C
cuicheng01 已提交
132
                 se_on,
133
                 se_r,
C
cuicheng01 已提交
134 135 136 137 138 139 140 141
                 shortcut=True,
                 name=None):
        super(BottleneckBlock, self).__init__()

        # Compute the bottleneck width
        w_b = int(round(num_filters * bm))
        # Compute the number of groups
        num_gs = w_b // gw
142
        self.se_on = se_on
C
cuicheng01 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
        self.conv0 = ConvBNLayer(
            num_channels=num_channels,
            num_filters=w_b,
            filter_size=1,
            padding=0,
            act="relu",
            name=name + "_branch2a")
        self.conv1 = ConvBNLayer(
            num_channels=w_b,
            num_filters=w_b,
            filter_size=3,
            stride=stride,
            padding=1,
            groups=num_gs,
            act="relu",
            name=name + "_branch2b")
        if se_on:
            w_se = int(round(num_channels * se_r))
            self.se_block = SELayer(
                num_channels=w_b,
                num_filters=w_b,
C
cuicheng01 已提交
164
                reduction_ratio=w_se,
C
cuicheng01 已提交
165 166 167 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
                name=name + "_branch2se")
        self.conv2 = ConvBNLayer(
            num_channels=w_b,
            num_filters=num_filters,
            filter_size=1,
            act=None,
            name=name + "_branch2c")

        if not shortcut:
            self.short = ConvBNLayer(
                num_channels=num_channels,
                num_filters=num_filters,
                filter_size=1,
                stride=stride,
                name=name + "_branch1")

        self.shortcut = shortcut

    def forward(self, inputs):
        y = self.conv0(inputs)
        conv1 = self.conv1(y)
        if self.se_on:
            conv1 = self.se_block(conv1)
        conv2 = self.conv2(conv1)

        if self.shortcut:
            short = inputs
        else:
            short = self.short(inputs)

195 196
        y = paddle.add(x=short, y=conv2)
        y = F.relu(y)
C
cuicheng01 已提交
197 198
        return y

199

C
cuicheng01 已提交
200 201 202 203
class SELayer(nn.Layer):
    def __init__(self, num_channels, num_filters, reduction_ratio, name=None):
        super(SELayer, self).__init__()

204
        self.pool2d_gap = AdaptiveAvgPool2D(1)
C
cuicheng01 已提交
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

        self._num_channels = num_channels

        med_ch = int(num_channels / reduction_ratio)
        stdv = 1.0 / math.sqrt(num_channels * 1.0)
        self.squeeze = Linear(
            num_channels,
            med_ch,
            weight_attr=ParamAttr(
                initializer=Uniform(-stdv, stdv), name=name + "_sqz_weights"),
            bias_attr=ParamAttr(name=name + "_sqz_offset"))

        stdv = 1.0 / math.sqrt(med_ch * 1.0)
        self.excitation = Linear(
            med_ch,
            num_filters,
            weight_attr=ParamAttr(
                initializer=Uniform(-stdv, stdv), name=name + "_exc_weights"),
            bias_attr=ParamAttr(name=name + "_exc_offset"))

    def forward(self, input):
        pool = self.pool2d_gap(input)
        pool = paddle.reshape(pool, shape=[-1, self._num_channels])
        squeeze = self.squeeze(pool)
        squeeze = F.relu(squeeze)
        excitation = self.excitation(squeeze)
        excitation = F.sigmoid(excitation)
        excitation = paddle.reshape(
            excitation, shape=[-1, self._num_channels, 1, 1])
        out = input * excitation
        return out
236

C
cuicheng01 已提交
237 238

class RegNet(nn.Layer):
239 240 241 242 243 244 245 246 247
    def __init__(self,
                 w_a,
                 w_0,
                 w_m,
                 d,
                 group_w,
                 bot_mul,
                 q=8,
                 se_on=False,
littletomatodonkey's avatar
littletomatodonkey 已提交
248
                 class_num=1000):
C
cuicheng01 已提交
249
        super(RegNet, self).__init__()
250

C
cuicheng01 已提交
251
        # Generate RegNet ws per block
252
        b_ws, num_s, max_s, ws_cont = generate_regnet(w_a, w_0, w_m, d, q)
C
cuicheng01 已提交
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
        # Convert to per stage format
        ws, ds = get_stages_from_blocks(b_ws, b_ws)
        # Generate group widths and bot muls
        gws = [group_w for _ in range(num_s)]
        bms = [bot_mul for _ in range(num_s)]
        # Adjust the compatibility of ws and gws
        ws, gws = adjust_ws_gs_comp(ws, bms, gws)
        # Use the same stride for each stage
        ss = [2 for _ in range(num_s)]
        # Use SE for RegNetY
        se_r = 0.25
        # Construct the model
        # Group params by stage
        stage_params = list(zip(ds, ws, ss, bms, gws))
        # Construct the stem
        stem_type = "simple_stem_in"
        stem_w = 32
        block_type = "res_bottleneck_block"

        self.conv = ConvBNLayer(
            num_channels=3,
            num_filters=stem_w,
            filter_size=3,
            stride=2,
            padding=1,
            act="relu",
            name="stem_conv")

        self.block_list = []
        for block, (d, w_out, stride, bm, gw) in enumerate(stage_params):
            shortcut = False
            for i in range(d):
                num_channels = stem_w if block == i == 0 else in_channels
                # Stride apply to the first block of the stage
                b_stride = stride if i == 0 else 1
288 289
                conv_name = "s" + str(block + 1) + "_b" + str(i +
                                                              1)  # chr(97 + i)
C
cuicheng01 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
                bottleneck_block = self.add_sublayer(
                    conv_name,
                    BottleneckBlock(
                        num_channels=num_channels,
                        num_filters=w_out,
                        stride=b_stride,
                        bm=bm,
                        gw=gw,
                        se_on=se_on,
                        se_r=se_r,
                        shortcut=shortcut,
                        name=conv_name))
                in_channels = w_out
                self.block_list.append(bottleneck_block)
                shortcut = True

306
        self.pool2d_avg = AdaptiveAvgPool2D(1)
C
cuicheng01 已提交
307 308 309 310 311 312 313

        self.pool2d_avg_channels = w_out

        stdv = 1.0 / math.sqrt(self.pool2d_avg_channels * 1.0)

        self.out = Linear(
            self.pool2d_avg_channels,
littletomatodonkey's avatar
littletomatodonkey 已提交
314
            class_num,
C
cuicheng01 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327
            weight_attr=ParamAttr(
                initializer=Uniform(-stdv, stdv), name="fc_0.w_0"),
            bias_attr=ParamAttr(name="fc_0.b_0"))

    def forward(self, inputs):
        y = self.conv(inputs)
        for block in self.block_list:
            y = block(y)
        y = self.pool2d_avg(y)
        y = paddle.reshape(y, shape=[-1, self.pool2d_avg_channels])
        y = self.out(y)
        return y

littletomatodonkey's avatar
littletomatodonkey 已提交
328

C
cuicheng01 已提交
329 330 331 332 333 334 335 336 337 338 339
def _load_pretrained(pretrained, model, model_url, use_ssld=False):
    if pretrained is False:
        pass
    elif pretrained is True:
        load_dygraph_pretrain_from_url(model, model_url, use_ssld=use_ssld)
    elif isinstance(pretrained, str):
        load_dygraph_pretrain(model, pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type."
        )
littletomatodonkey's avatar
littletomatodonkey 已提交
340 341


C
cuicheng01 已提交
342
def RegNetX_200MF(pretrained=False, use_ssld=False, **kwargs):
C
cuicheng01 已提交
343
    model = RegNet(
littletomatodonkey's avatar
littletomatodonkey 已提交
344 345 346 347 348 349 350 351 352 353
        w_a=36.44,
        w_0=24,
        w_m=2.49,
        d=13,
        group_w=8,
        bot_mul=1.0,
        q=8,
        **kwargs)
    _load_pretrained(
        pretrained, model, MODEL_URLS["RegNetX_200MF"], use_ssld=use_ssld)
C
cuicheng01 已提交
354 355 356
    return model


C
cuicheng01 已提交
357
def RegNetX_4GF(pretrained=False, use_ssld=False, **kwargs):
C
cuicheng01 已提交
358
    model = RegNet(
359 360 361 362 363 364 365
        w_a=38.65,
        w_0=96,
        w_m=2.43,
        d=23,
        group_w=40,
        bot_mul=1.0,
        q=8,
C
cuicheng01 已提交
366
        **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
367 368
    _load_pretrained(
        pretrained, model, MODEL_URLS["RegNetX_4GF"], use_ssld=use_ssld)
C
cuicheng01 已提交
369 370 371
    return model


C
cuicheng01 已提交
372
def RegNetX_32GF(pretrained=False, use_ssld=False, **kwargs):
C
cuicheng01 已提交
373
    model = RegNet(
374 375 376 377 378 379 380
        w_a=69.86,
        w_0=320,
        w_m=2.0,
        d=23,
        group_w=168,
        bot_mul=1.0,
        q=8,
C
cuicheng01 已提交
381
        **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
382 383
    _load_pretrained(
        pretrained, model, MODEL_URLS["RegNetX_32GF"], use_ssld=use_ssld)
C
cuicheng01 已提交
384 385 386
    return model


C
cuicheng01 已提交
387
def RegNetY_200MF(pretrained=False, use_ssld=False, **kwargs):
C
cuicheng01 已提交
388 389 390 391 392 393 394 395 396
    model = RegNet(
        w_a=36.44,
        w_0=24,
        w_m=2.49,
        d=13,
        group_w=8,
        bot_mul=1.0,
        q=8,
        se_on=True,
C
cuicheng01 已提交
397
        **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
398 399
    _load_pretrained(
        pretrained, model, MODEL_URLS["RegNetX_32GF"], use_ssld=use_ssld)
C
cuicheng01 已提交
400 401 402
    return model


C
cuicheng01 已提交
403
def RegNetY_4GF(pretrained=False, use_ssld=False, **kwargs):
C
cuicheng01 已提交
404 405 406 407 408 409 410 411 412
    model = RegNet(
        w_a=31.41,
        w_0=96,
        w_m=2.24,
        d=22,
        group_w=64,
        bot_mul=1.0,
        q=8,
        se_on=True,
C
cuicheng01 已提交
413
        **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
414 415
    _load_pretrained(
        pretrained, model, MODEL_URLS["RegNetX_32GF"], use_ssld=use_ssld)
C
cuicheng01 已提交
416 417 418
    return model


C
cuicheng01 已提交
419
def RegNetY_32GF(pretrained=False, use_ssld=False, **kwargs):
C
cuicheng01 已提交
420 421 422 423 424 425 426 427 428
    model = RegNet(
        w_a=115.89,
        w_0=232,
        w_m=2.53,
        d=20,
        group_w=232,
        bot_mul=1.0,
        q=8,
        se_on=True,
C
cuicheng01 已提交
429
        **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
430 431
    _load_pretrained(
        pretrained, model, MODEL_URLS["RegNetX_32GF"], use_ssld=use_ssld)
C
cuicheng01 已提交
432
    return model