dla.py 15.8 KB
Newer Older
jm_12138's avatar
jm_12138 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# copyright (c) 2021 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/ucbdrive/dla
G
gaotingquan 已提交
16
# reference: https://arxiv.org/abs/1707.06484
C
cuicheng01 已提交
17

18 19 20 21 22 23 24 25
import math

import paddle
import paddle.nn as nn
import paddle.nn.functional as F

from paddle.nn.initializer import Normal, Constant

R
root 已提交
26 27
from ..base.theseus_layer import Identity
from ....utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url
28 29 30

MODEL_URLS = {
    "DLA34":
C
cuicheng01 已提交
31
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA34_pretrained.pdparams",
32
    "DLA46_c":
C
cuicheng01 已提交
33
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA46_c_pretrained.pdparams",
34
    "DLA46x_c":
C
cuicheng01 已提交
35
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA46x_c_pretrained.pdparams",
36
    "DLA60":
C
cuicheng01 已提交
37
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA60_pretrained.pdparams",
38
    "DLA60x":
C
cuicheng01 已提交
39
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA60x_pretrained.pdparams",
40
    "DLA60x_c":
C
cuicheng01 已提交
41
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA60x_c_pretrained.pdparams",
42
    "DLA102":
C
cuicheng01 已提交
43
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA102_pretrained.pdparams",
44
    "DLA102x":
C
cuicheng01 已提交
45
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA102x_pretrained.pdparams",
46
    "DLA102x2":
C
cuicheng01 已提交
47
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA102x2_pretrained.pdparams",
48
    "DLA169":
C
cuicheng01 已提交
49
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DLA169_pretrained.pdparams"
50 51 52 53 54 55 56 57 58 59 60 61
}

__all__ = MODEL_URLS.keys()

zeros_ = Constant(value=0.)
ones_ = Constant(value=1.)


class DlaBasic(nn.Layer):
    def __init__(self, inplanes, planes, stride=1, dilation=1, **cargs):
        super(DlaBasic, self).__init__()
        self.conv1 = nn.Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
62 63 64 65 66 67 68
            inplanes,
            planes,
            kernel_size=3,
            stride=stride,
            padding=dilation,
            bias_attr=False,
            dilation=dilation)
69 70 71
        self.bn1 = nn.BatchNorm2D(planes)
        self.relu = nn.ReLU()
        self.conv2 = nn.Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
72 73 74 75 76 77 78
            planes,
            planes,
            kernel_size=3,
            stride=1,
            padding=dilation,
            bias_attr=False,
            dilation=dilation)
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
        self.bn2 = nn.BatchNorm2D(planes)
        self.stride = stride

    def forward(self, x, residual=None):
        if residual is None:
            residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        out += residual
        out = self.relu(out)

        return out


class DlaBottleneck(nn.Layer):
    expansion = 2

littletomatodonkey's avatar
littletomatodonkey 已提交
102 103 104 105 106 107 108
    def __init__(self,
                 inplanes,
                 outplanes,
                 stride=1,
                 dilation=1,
                 cardinality=1,
                 base_width=64):
109 110
        super(DlaBottleneck, self).__init__()
        self.stride = stride
littletomatodonkey's avatar
littletomatodonkey 已提交
111 112
        mid_planes = int(
            math.floor(outplanes * (base_width / 64)) * cardinality)
113 114
        mid_planes = mid_planes // self.expansion

littletomatodonkey's avatar
littletomatodonkey 已提交
115 116
        self.conv1 = nn.Conv2D(
            inplanes, mid_planes, kernel_size=1, bias_attr=False)
117 118
        self.bn1 = nn.BatchNorm2D(mid_planes)
        self.conv2 = nn.Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
119 120 121 122 123 124 125 126
            mid_planes,
            mid_planes,
            kernel_size=3,
            stride=stride,
            padding=dilation,
            bias_attr=False,
            dilation=dilation,
            groups=cardinality)
127
        self.bn2 = nn.BatchNorm2D(mid_planes)
littletomatodonkey's avatar
littletomatodonkey 已提交
128 129
        self.conv3 = nn.Conv2D(
            mid_planes, outplanes, kernel_size=1, bias_attr=False)
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
        self.bn3 = nn.BatchNorm2D(outplanes)
        self.relu = nn.ReLU()

    def forward(self, x, residual=None):
        if residual is None:
            residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        out += residual
        out = self.relu(out)

        return out


class DlaRoot(nn.Layer):
    def __init__(self, in_channels, out_channels, kernel_size, residual):
        super(DlaRoot, self).__init__()
        self.conv = nn.Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
158 159 160 161 162 163
            in_channels,
            out_channels,
            1,
            stride=1,
            bias_attr=False,
            padding=(kernel_size - 1) // 2)
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        self.bn = nn.BatchNorm2D(out_channels)
        self.relu = nn.ReLU()
        self.residual = residual

    def forward(self, *x):
        children = x
        x = self.conv(paddle.concat(x, 1))
        x = self.bn(x)
        if self.residual:
            x += children[0]
        x = self.relu(x)

        return x


class DlaTree(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
180 181 182 183 184 185 186 187 188 189 190 191
    def __init__(self,
                 levels,
                 block,
                 in_channels,
                 out_channels,
                 stride=1,
                 dilation=1,
                 cardinality=1,
                 base_width=64,
                 level_root=False,
                 root_dim=0,
                 root_kernel_size=1,
192 193 194 195 196 197 198 199 200 201
                 root_residual=False):
        super(DlaTree, self).__init__()
        if root_dim == 0:
            root_dim = 2 * out_channels
        if level_root:
            root_dim += in_channels

        self.downsample = nn.MaxPool2D(
            stride, stride=stride) if stride > 1 else Identity()
        self.project = Identity()
littletomatodonkey's avatar
littletomatodonkey 已提交
202 203
        cargs = dict(
            dilation=dilation, cardinality=cardinality, base_width=base_width)
204 205 206 207 208 209

        if levels == 1:
            self.tree1 = block(in_channels, out_channels, stride, **cargs)
            self.tree2 = block(out_channels, out_channels, 1, **cargs)
            if in_channels != out_channels:
                self.project = nn.Sequential(
littletomatodonkey's avatar
littletomatodonkey 已提交
210 211 212 213 214 215
                    nn.Conv2D(
                        in_channels,
                        out_channels,
                        kernel_size=1,
                        stride=1,
                        bias_attr=False),
216 217
                    nn.BatchNorm2D(out_channels))
        else:
littletomatodonkey's avatar
littletomatodonkey 已提交
218 219 220 221
            cargs.update(
                dict(
                    root_kernel_size=root_kernel_size,
                    root_residual=root_residual))
222
            self.tree1 = DlaTree(
littletomatodonkey's avatar
littletomatodonkey 已提交
223 224 225 226 227 228 229
                levels - 1,
                block,
                in_channels,
                out_channels,
                stride,
                root_dim=0,
                **cargs)
230
            self.tree2 = DlaTree(
littletomatodonkey's avatar
littletomatodonkey 已提交
231 232 233 234 235 236
                levels - 1,
                block,
                out_channels,
                out_channels,
                root_dim=root_dim + out_channels,
                **cargs)
237 238

        if levels == 1:
littletomatodonkey's avatar
littletomatodonkey 已提交
239 240
            self.root = DlaRoot(root_dim, out_channels, root_kernel_size,
                                root_residual)
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

        self.level_root = level_root
        self.root_dim = root_dim
        self.levels = levels

    def forward(self, x, residual=None, children=None):
        children = [] if children is None else children
        bottom = self.downsample(x)
        residual = self.project(bottom)

        if self.level_root:
            children.append(bottom)
        x1 = self.tree1(x, residual)

        if self.levels == 1:
            x2 = self.tree2(x1)
            x = self.root(x2, x1, *children)
        else:
            children.append(x1)
            x = self.tree2(x1, children=children)
        return x


class DLA(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
265 266 267 268 269 270 271 272 273 274 275
    def __init__(self,
                 levels,
                 channels,
                 in_chans=3,
                 cardinality=1,
                 base_width=64,
                 block=DlaBottleneck,
                 residual_root=False,
                 drop_rate=0.0,
                 class_num=1000,
                 with_pool=True):
276 277
        super(DLA, self).__init__()
        self.channels = channels
littletomatodonkey's avatar
littletomatodonkey 已提交
278
        self.class_num = class_num
279 280 281 282 283 284 285
        self.with_pool = with_pool
        self.cardinality = cardinality
        self.base_width = base_width
        self.drop_rate = drop_rate

        self.base_layer = nn.Sequential(
            nn.Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
286 287 288 289 290 291
                in_chans,
                channels[0],
                kernel_size=7,
                stride=1,
                padding=3,
                bias_attr=False),
292 293 294
            nn.BatchNorm2D(channels[0]),
            nn.ReLU())

littletomatodonkey's avatar
littletomatodonkey 已提交
295 296 297 298
        self.level0 = self._make_conv_level(channels[0], channels[0],
                                            levels[0])
        self.level1 = self._make_conv_level(
            channels[0], channels[1], levels[1], stride=2)
299 300

        cargs = dict(
littletomatodonkey's avatar
littletomatodonkey 已提交
301 302 303
            cardinality=cardinality,
            base_width=base_width,
            root_residual=residual_root)
304 305

        self.level2 = DlaTree(
littletomatodonkey's avatar
littletomatodonkey 已提交
306 307 308 309 310 311 312
            levels[2],
            block,
            channels[1],
            channels[2],
            2,
            level_root=False,
            **cargs)
313
        self.level3 = DlaTree(
littletomatodonkey's avatar
littletomatodonkey 已提交
314 315 316 317 318 319 320
            levels[3],
            block,
            channels[2],
            channels[3],
            2,
            level_root=True,
            **cargs)
321
        self.level4 = DlaTree(
littletomatodonkey's avatar
littletomatodonkey 已提交
322 323 324 325 326 327 328
            levels[4],
            block,
            channels[3],
            channels[4],
            2,
            level_root=True,
            **cargs)
329
        self.level5 = DlaTree(
littletomatodonkey's avatar
littletomatodonkey 已提交
330 331 332 333 334 335 336
            levels[5],
            block,
            channels[4],
            channels[5],
            2,
            level_root=True,
            **cargs)
337 338 339

        self.feature_info = [
            # rare to have a meaningful stride 1 level
littletomatodonkey's avatar
littletomatodonkey 已提交
340 341 342 343 344 345 346 347 348 349 350 351
            dict(
                num_chs=channels[0], reduction=1, module='level0'),
            dict(
                num_chs=channels[1], reduction=2, module='level1'),
            dict(
                num_chs=channels[2], reduction=4, module='level2'),
            dict(
                num_chs=channels[3], reduction=8, module='level3'),
            dict(
                num_chs=channels[4], reduction=16, module='level4'),
            dict(
                num_chs=channels[5], reduction=32, module='level5'),
352 353 354 355 356 357 358
        ]

        self.num_features = channels[-1]

        if with_pool:
            self.global_pool = nn.AdaptiveAvgPool2D(1)

littletomatodonkey's avatar
littletomatodonkey 已提交
359 360
        if class_num > 0:
            self.fc = nn.Conv2D(self.num_features, class_num, 1)
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

        for m in self.sublayers():
            if isinstance(m, nn.Conv2D):
                n = m._kernel_size[0] * m._kernel_size[1] * m._out_channels
                normal_ = Normal(mean=0.0, std=math.sqrt(2. / n))
                normal_(m.weight)
            elif isinstance(m, nn.BatchNorm2D):
                ones_(m.weight)
                zeros_(m.bias)

    def _make_conv_level(self, inplanes, planes, convs, stride=1, dilation=1):
        modules = []
        for i in range(convs):
            modules.extend([
                nn.Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
376 377 378
                    inplanes,
                    planes,
                    kernel_size=3,
379
                    stride=stride if i == 0 else 1,
littletomatodonkey's avatar
littletomatodonkey 已提交
380 381 382 383
                    padding=dilation,
                    bias_attr=False,
                    dilation=dilation), nn.BatchNorm2D(planes), nn.ReLU()
            ])
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
            inplanes = planes
        return nn.Sequential(*modules)

    def forward_features(self, x):
        x = self.base_layer(x)

        x = self.level0(x)
        x = self.level1(x)
        x = self.level2(x)
        x = self.level3(x)
        x = self.level4(x)
        x = self.level5(x)

        return x

    def forward(self, x):
        x = self.forward_features(x)

        if self.with_pool:
            x = self.global_pool(x)

        if self.drop_rate > 0.:
            x = F.dropout(x, p=self.drop_rate, training=self.training)

littletomatodonkey's avatar
littletomatodonkey 已提交
408
        if self.class_num > 0:
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
            x = self.fc(x)
            x = x.flatten(1)

        return x


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."
        )


def DLA34(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
429 430 431 432
    model = DLA(levels=(1, 1, 1, 2, 2, 1),
                channels=(16, 32, 64, 128, 256, 512),
                block=DlaBasic,
                **kwargs)
433 434 435 436 437
    _load_pretrained(pretrained, model, MODEL_URLS["DLA34"])
    return model


def DLA46_c(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
438 439 440 441
    model = DLA(levels=(1, 1, 1, 2, 2, 1),
                channels=(16, 32, 64, 64, 128, 256),
                block=DlaBottleneck,
                **kwargs)
442 443 444 445 446
    _load_pretrained(pretrained, model, MODEL_URLS["DLA46_c"])
    return model


def DLA46x_c(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
447 448 449 450 451 452
    model = DLA(levels=(1, 1, 1, 2, 2, 1),
                channels=(16, 32, 64, 64, 128, 256),
                block=DlaBottleneck,
                cardinality=32,
                base_width=4,
                **kwargs)
453 454 455 456 457
    _load_pretrained(pretrained, model, MODEL_URLS["DLA46x_c"])
    return model


def DLA60(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
458 459 460 461
    model = DLA(levels=(1, 1, 1, 2, 3, 1),
                channels=(16, 32, 128, 256, 512, 1024),
                block=DlaBottleneck,
                **kwargs)
462 463 464 465 466
    _load_pretrained(pretrained, model, MODEL_URLS["DLA60"])
    return model


def DLA60x(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
467 468 469 470 471 472
    model = DLA(levels=(1, 1, 1, 2, 3, 1),
                channels=(16, 32, 128, 256, 512, 1024),
                block=DlaBottleneck,
                cardinality=32,
                base_width=4,
                **kwargs)
473 474 475 476 477
    _load_pretrained(pretrained, model, MODEL_URLS["DLA60x"])
    return model


def DLA60x_c(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
478 479 480 481 482 483
    model = DLA(levels=(1, 1, 1, 2, 3, 1),
                channels=(16, 32, 64, 64, 128, 256),
                block=DlaBottleneck,
                cardinality=32,
                base_width=4,
                **kwargs)
484 485 486 487 488
    _load_pretrained(pretrained, model, MODEL_URLS["DLA60x_c"])
    return model


def DLA102(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
489 490 491 492 493
    model = DLA(levels=(1, 1, 1, 3, 4, 1),
                channels=(16, 32, 128, 256, 512, 1024),
                block=DlaBottleneck,
                residual_root=True,
                **kwargs)
494 495 496 497 498
    _load_pretrained(pretrained, model, MODEL_URLS["DLA102"])
    return model


def DLA102x(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
499 500 501 502 503 504 505
    model = DLA(levels=(1, 1, 1, 3, 4, 1),
                channels=(16, 32, 128, 256, 512, 1024),
                block=DlaBottleneck,
                cardinality=32,
                base_width=4,
                residual_root=True,
                **kwargs)
506 507 508 509 510
    _load_pretrained(pretrained, model, MODEL_URLS["DLA102x"])
    return model


def DLA102x2(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
511 512 513 514 515 516 517
    model = DLA(levels=(1, 1, 1, 3, 4, 1),
                channels=(16, 32, 128, 256, 512, 1024),
                block=DlaBottleneck,
                cardinality=64,
                base_width=4,
                residual_root=True,
                **kwargs)
518 519 520 521 522
    _load_pretrained(pretrained, model, MODEL_URLS["DLA102x2"])
    return model


def DLA169(pretrained=False, **kwargs):
littletomatodonkey's avatar
littletomatodonkey 已提交
523 524 525 526 527
    model = DLA(levels=(1, 1, 2, 3, 5, 1),
                channels=(16, 32, 128, 256, 512, 1024),
                block=DlaBottleneck,
                residual_root=True,
                **kwargs)
528 529
    _load_pretrained(pretrained, model, MODEL_URLS["DLA169"])
    return model