hrnet.py 16.1 KB
Newer Older
W
weishengyu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
# 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.

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

import math
import numpy as np
import paddle
from paddle import ParamAttr
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
from paddle.nn.initializer import Uniform

from ppcls.arch.backbone.base.theseus_layer import TheseusLayer

__all__ = [
    "HRNet_W18_C",
    "HRNet_W30_C",
    "HRNet_W32_C",
    "HRNet_W40_C",
    "HRNet_W44_C",
    "HRNet_W48_C",
    "HRNet_W60_C",
    "HRNet_W64_C",
    "SE_HRNet_W18_C",
    "SE_HRNet_W30_C",
    "SE_HRNet_W32_C",
    "SE_HRNet_W40_C",
    "SE_HRNet_W44_C",
    "SE_HRNet_W48_C",
    "SE_HRNet_W60_C",
    "SE_HRNet_W64_C",
]


class ConvBNLayer(TheseusLayer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 groups=1,
57
                 act="relu"):
W
weishengyu 已提交
58 59
        super(ConvBNLayer, self).__init__()

W
add nn  
weishengyu 已提交
60
        self._conv = nn.Conv2D(
W
weishengyu 已提交
61 62 63 64 65 66 67
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
            stride=stride,
            padding=(filter_size - 1) // 2,
            groups=groups,
            bias_attr=False)
W
add nn  
weishengyu 已提交
68
        self._batch_norm = nn.BatchNorm(
W
weishengyu 已提交
69
            num_filters,
W
weishengyu 已提交
70
            act=act)
W
weishengyu 已提交
71

W
weishengyu 已提交
72 73
    def forward(self, x, res_dict=None):
        y = self._conv(x)
W
weishengyu 已提交
74 75 76 77 78 79 80 81 82 83
        y = self._batch_norm(y)
        return y


class BottleneckBlock(TheseusLayer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 has_se,
                 stride=1,
W
weishengyu 已提交
84
                 downsample=False):
W
weishengyu 已提交
85 86 87 88 89 90 91 92 93
        super(BottleneckBlock, self).__init__()

        self.has_se = has_se
        self.downsample = downsample

        self.conv1 = ConvBNLayer(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=1,
W
weishengyu 已提交
94
            act="relu")
W
weishengyu 已提交
95 96 97 98 99
        self.conv2 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters,
            filter_size=3,
            stride=stride,
W
weishengyu 已提交
100
            act="relu")
W
weishengyu 已提交
101 102 103 104
        self.conv3 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters * 4,
            filter_size=1,
W
weishengyu 已提交
105
            act=None)
W
weishengyu 已提交
106 107 108 109 110 111

        if self.downsample:
            self.conv_down = ConvBNLayer(
                num_channels=num_channels,
                num_filters=num_filters * 4,
                filter_size=1,
W
weishengyu 已提交
112
                act=None)
W
weishengyu 已提交
113 114 115 116 117

        if self.has_se:
            self.se = SELayer(
                num_channels=num_filters * 4,
                num_filters=num_filters * 4,
W
weishengyu 已提交
118
                reduction_ratio=16)
W
weishengyu 已提交
119

W
weishengyu 已提交
120 121 122
    def forward(self, x, res_dict=None):
        residual = x
        conv1 = self.conv1(x)
W
weishengyu 已提交
123 124 125 126
        conv2 = self.conv2(conv1)
        conv3 = self.conv3(conv2)

        if self.downsample:
W
weishengyu 已提交
127
            residual = self.conv_down(x)
W
weishengyu 已提交
128 129 130 131 132 133 134 135 136

        if self.has_se:
            conv3 = self.se(conv3)

        y = paddle.add(x=residual, y=conv3)
        y = F.relu(y)
        return y


W
dbg  
weishengyu 已提交
137
class BasicBlock(nn.Layer):
W
weishengyu 已提交
138 139 140
    def __init__(self,
                 num_channels,
                 num_filters,
W
weishengyu 已提交
141
                 has_se=False):
W
weishengyu 已提交
142 143 144 145 146 147 148 149
        super(BasicBlock, self).__init__()

        self.has_se = has_se

        self.conv1 = ConvBNLayer(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=3,
W
dbg  
weishengyu 已提交
150
            stride=1,
W
dbg  
weishengyu 已提交
151
            act="relu")
W
weishengyu 已提交
152 153 154 155 156
        self.conv2 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters,
            filter_size=3,
            stride=1,
W
dbg  
weishengyu 已提交
157
            act=None)
W
weishengyu 已提交
158 159 160 161 162

        if self.has_se:
            self.se = SELayer(
                num_channels=num_filters,
                num_filters=num_filters,
W
weishengyu 已提交
163
                reduction_ratio=16)
W
weishengyu 已提交
164

W
dbg  
weishengyu 已提交
165
    def forward(self, input):
W
weishengyu 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178
        residual = input
        conv1 = self.conv1(input)
        conv2 = self.conv2(conv1)

        if self.has_se:
            conv2 = self.se(conv2)

        y = paddle.add(x=residual, y=conv2)
        y = F.relu(y)
        return y


class SELayer(TheseusLayer):
W
weishengyu 已提交
179
    def __init__(self, num_channels, num_filters, reduction_ratio):
W
weishengyu 已提交
180 181 182 183 184 185 186 187
        super(SELayer, self).__init__()

        self.pool2d_gap = AdaptiveAvgPool2D(1)

        self._num_channels = num_channels

        med_ch = int(num_channels / reduction_ratio)
        stdv = 1.0 / math.sqrt(num_channels * 1.0)
W
add nn  
weishengyu 已提交
188
        self.squeeze = nn.Linear(
W
weishengyu 已提交
189 190 191
            num_channels,
            med_ch,
            weight_attr=ParamAttr(
W
weishengyu 已提交
192
                initializer=Uniform(-stdv, stdv)))
W
weishengyu 已提交
193 194

        stdv = 1.0 / math.sqrt(med_ch * 1.0)
W
add nn  
weishengyu 已提交
195
        self.excitation = nn.Linear(
W
weishengyu 已提交
196 197 198
            med_ch,
            num_filters,
            weight_attr=ParamAttr(
W
weishengyu 已提交
199
                initializer=Uniform(-stdv, stdv)))
W
weishengyu 已提交
200

W
weishengyu 已提交
201
    def forward(self, input, res_dict=None):
W
weishengyu 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
        pool = self.pool2d_gap(input)
        pool = paddle.squeeze(pool, axis=[2, 3])
        squeeze = self.squeeze(pool)
        squeeze = F.relu(squeeze)
        excitation = self.excitation(squeeze)
        excitation = F.sigmoid(excitation)
        excitation = paddle.unsqueeze(excitation, axis=[2, 3])
        out = input * excitation
        return out


class Stage(TheseusLayer):
    def __init__(self,
                 num_modules,
                 num_filters,
W
weishengyu 已提交
217
                 has_se=False):
W
weishengyu 已提交
218 219 220 221
        super(Stage, self).__init__()

        self._num_modules = num_modules

W
dbg  
weishengyu 已提交
222
        self.stage_func_list = nn.LayerList()
W
weishengyu 已提交
223
        for i in range(num_modules):
W
weishengyu 已提交
224 225 226
            self.stage_func_list.append(
                HighResolutionModule(
                    num_filters=num_filters,
W
weishengyu 已提交
227
                    has_se=has_se))
W
weishengyu 已提交
228

W
weishengyu 已提交
229
    def forward(self, input, res_dict=None):
W
weishengyu 已提交
230 231 232 233 234 235 236 237 238
        out = input
        for idx in range(self._num_modules):
            out = self.stage_func_list[idx](out)
        return out


class HighResolutionModule(TheseusLayer):
    def __init__(self,
                 num_filters,
W
weishengyu 已提交
239
                 has_se=False):
W
weishengyu 已提交
240 241
        super(HighResolutionModule, self).__init__()

W
weishengyu 已提交
242
        self.basic_block_list = nn.LayerList()
W
dbg  
weishengyu 已提交
243 244

        for i in range(len(num_filters)):
W
weishengyu 已提交
245 246
            self.basic_block_list.append(
                nn.Sequential(*[
W
dbg  
weishengyu 已提交
247
                    BasicBlock(
W
weishengyu 已提交
248
                        num_channels=num_filters[i],
W
dbg  
weishengyu 已提交
249
                        num_filters=num_filters[i],
W
weishengyu 已提交
250
                        has_se=has_se) for j in range(4)]))
W
weishengyu 已提交
251 252 253

        self.fuse_func = FuseLayers(
            in_channels=num_filters,
W
weishengyu 已提交
254
            out_channels=num_filters)
W
weishengyu 已提交
255

W
weishengyu 已提交
256
    def forward(self, input, res_dict=None):
W
dbg  
weishengyu 已提交
257 258 259 260 261 262 263 264
        outs = []
        for idx, input in enumerate(input):
            conv = input
            basic_block_list = self.basic_block_list[idx]
            for basic_block_func in basic_block_list:
                conv = basic_block_func(conv)
            outs.append(conv)
        out = self.fuse_func(outs)
W
weishengyu 已提交
265 266 267 268 269 270
        return out


class FuseLayers(TheseusLayer):
    def __init__(self,
                 in_channels,
W
weishengyu 已提交
271
                 out_channels):
W
weishengyu 已提交
272 273
        super(FuseLayers, self).__init__()

W
weishengyu 已提交
274
        self._actual_ch = len(in_channels)
W
weishengyu 已提交
275 276
        self._in_channels = in_channels

W
weishengyu 已提交
277 278
        self.residual_func_list = nn.LayerList()
        for i in range(len(in_channels)):
W
weishengyu 已提交
279 280
            for j in range(len(in_channels)):
                if j > i:
W
weishengyu 已提交
281
                    self.residual_func_list.append(
W
weishengyu 已提交
282 283 284 285 286
                        ConvBNLayer(
                            num_channels=in_channels[j],
                            num_filters=out_channels[i],
                            filter_size=1,
                            stride=1,
W
weishengyu 已提交
287
                            act=None))
W
weishengyu 已提交
288 289 290 291
                elif j < i:
                    pre_num_filters = in_channels[j]
                    for k in range(i - j):
                        if k == i - j - 1:
W
weishengyu 已提交
292
                            self.residual_func_list.append(
W
weishengyu 已提交
293 294 295 296 297
                                ConvBNLayer(
                                    num_channels=pre_num_filters,
                                    num_filters=out_channels[i],
                                    filter_size=3,
                                    stride=2,
W
weishengyu 已提交
298
                                    act=None))
W
weishengyu 已提交
299 300
                            pre_num_filters = out_channels[i]
                        else:
W
weishengyu 已提交
301
                            self.residual_func_list.append(
W
weishengyu 已提交
302 303 304 305 306
                                ConvBNLayer(
                                    num_channels=pre_num_filters,
                                    num_filters=out_channels[j],
                                    filter_size=3,
                                    stride=2,
W
weishengyu 已提交
307
                                    act="relu"))
W
weishengyu 已提交
308 309
                            pre_num_filters = out_channels[j]

W
weishengyu 已提交
310
    def forward(self, input, res_dict=None):
W
weishengyu 已提交
311 312
        outs = []
        residual_func_idx = 0
W
weishengyu 已提交
313
        for i in range(len(self._in_channels)):
W
weishengyu 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
            residual = input[i]
            for j in range(len(self._in_channels)):
                if j > i:
                    y = self.residual_func_list[residual_func_idx](input[j])
                    residual_func_idx += 1

                    y = F.upsample(y, scale_factor=2**(j - i), mode="nearest")
                    residual = paddle.add(x=residual, y=y)
                elif j < i:
                    y = input[j]
                    for k in range(i - j):
                        y = self.residual_func_list[residual_func_idx](y)
                        residual_func_idx += 1

                    residual = paddle.add(x=residual, y=y)

            residual = F.relu(residual)
            outs.append(residual)

        return outs


class LastClsOut(TheseusLayer):
    def __init__(self,
                 num_channel_list,
                 has_se,
W
weishengyu 已提交
340
                 num_filters_list=[32, 64, 128, 256]):
W
weishengyu 已提交
341 342
        super(LastClsOut, self).__init__()

W
weishengyu 已提交
343
        self.func_list = nn.LayerList()
W
weishengyu 已提交
344
        for idx in range(len(num_channel_list)):
W
weishengyu 已提交
345
            self.func_list.append(
W
weishengyu 已提交
346 347 348 349
                BottleneckBlock(
                    num_channels=num_channel_list[idx],
                    num_filters=num_filters_list[idx],
                    has_se=has_se,
W
weishengyu 已提交
350
                    downsample=True))
W
weishengyu 已提交
351

W
weishengyu 已提交
352
    def forward(self, inputs, res_dict=None):
W
weishengyu 已提交
353 354 355 356 357 358 359 360
        outs = []
        for idx, input in enumerate(inputs):
            out = self.func_list[idx](input)
            outs.append(out)
        return outs


class HRNet(TheseusLayer):
W
dbg  
weishengyu 已提交
361
    """
362 363 364 365 366
    HRNet
    Args:
        width: int=18. Base channel number of HRNet.
        has_se: bool=False. If 'True', add se module to HRNet.
        class_num: int=1000. Output num of last fc layer.
W
dbg  
weishengyu 已提交
367
    """
368
    def __init__(self, width=18, has_se=False, class_num=1000):
W
weishengyu 已提交
369 370 371 372
        super(HRNet, self).__init__()

        self.width = width
        self.has_se = has_se
373
        self._class_num = class_num
W
weishengyu 已提交
374

W
weishengyu 已提交
375 376 377
        channels_2 = [self.width, self.width * 2]
        channels_3 = [self.width, self.width * 2, self.width * 4]
        channels_4 = [self.width, self.width * 2, self.width * 4, self.width * 8]
W
weishengyu 已提交
378 379 380 381 382 383

        self.conv_layer1_1 = ConvBNLayer(
            num_channels=3,
            num_filters=64,
            filter_size=3,
            stride=2,
W
weishengyu 已提交
384
            act='relu')
W
weishengyu 已提交
385 386 387 388 389 390

        self.conv_layer1_2 = ConvBNLayer(
            num_channels=64,
            num_filters=64,
            filter_size=3,
            stride=2,
W
weishengyu 已提交
391
            act='relu')
W
weishengyu 已提交
392

W
dbg  
weishengyu 已提交
393
        self.layer1 = nn.Sequential(*[
W
weishengyu 已提交
394
            BottleneckBlock(
W
weishengyu 已提交
395 396 397 398
                num_channels=64 if i == 0 else 256,
                num_filters=64,
                has_se=has_se,
                stride=1,
W
weishengyu 已提交
399
                downsample=True if i == 0 else False)
W
weishengyu 已提交
400 401
            for i in range(4)
        ])
W
weishengyu 已提交
402

W
dbg  
weishengyu 已提交
403
        self.tr1_1 = ConvBNLayer(
W
weishengyu 已提交
404 405
            num_channels=256,
            num_filters=width,
W
dbg  
weishengyu 已提交
406 407
            filter_size=3)
        self.tr1_2 = ConvBNLayer(
W
dbg  
weishengyu 已提交
408
            num_channels=256,
W
weishengyu 已提交
409
            num_filters=width * 2,
W
dbg  
weishengyu 已提交
410 411 412
            filter_size=3,
            stride=2
        )
W
weishengyu 已提交
413 414

        self.st2 = Stage(
W
dbg  
weishengyu 已提交
415
            num_modules=1,
W
weishengyu 已提交
416
            num_filters=channels_2,
W
weishengyu 已提交
417
            has_se=self.has_se)
W
weishengyu 已提交
418

W
dbg  
weishengyu 已提交
419
        self.tr2 = ConvBNLayer(
W
weishengyu 已提交
420 421
            num_channels=width * 2,
            num_filters=width * 4,
W
dbg  
weishengyu 已提交
422 423 424
            filter_size=3,
            stride=2
        )
W
weishengyu 已提交
425
        self.st3 = Stage(
W
dbg  
weishengyu 已提交
426
            num_modules=4,
W
weishengyu 已提交
427
            num_filters=channels_3,
W
weishengyu 已提交
428
            has_se=self.has_se)
W
weishengyu 已提交
429

W
dbg  
weishengyu 已提交
430
        self.tr3 = ConvBNLayer(
W
weishengyu 已提交
431 432
            num_channels=width * 4,
            num_filters=width * 8,
W
dbg  
weishengyu 已提交
433 434 435
            filter_size=3,
            stride=2
        )
W
weishengyu 已提交
436

W
weishengyu 已提交
437
        self.st4 = Stage(
W
dbg  
weishengyu 已提交
438
            num_modules=3,
W
weishengyu 已提交
439
            num_filters=channels_4,
W
weishengyu 已提交
440
            has_se=self.has_se)
W
weishengyu 已提交
441 442 443 444 445 446

        # classification
        num_filters_list = [32, 64, 128, 256]
        self.last_cls = LastClsOut(
            num_channel_list=channels_4,
            has_se=self.has_se,
W
weishengyu 已提交
447
            num_filters_list=num_filters_list)
W
weishengyu 已提交
448 449

        last_num_filters = [256, 512, 1024]
W
weishengyu 已提交
450
        self.cls_head_conv_list = nn.LayerList()
W
weishengyu 已提交
451 452 453 454 455 456
        for idx in range(3):
            self.cls_head_conv_list.append(
                    ConvBNLayer(
                        num_channels=num_filters_list[idx] * 4,
                        num_filters=last_num_filters[idx],
                        filter_size=3,
W
weishengyu 已提交
457
                        stride=2))
W
weishengyu 已提交
458 459 460 461 462

        self.conv_last = ConvBNLayer(
            num_channels=1024,
            num_filters=2048,
            filter_size=1,
W
weishengyu 已提交
463
            stride=1)
W
weishengyu 已提交
464 465 466 467 468

        self.pool2d_avg = AdaptiveAvgPool2D(1)

        stdv = 1.0 / math.sqrt(2048 * 1.0)

W
add nn  
weishengyu 已提交
469
        self.out = nn.Linear(
W
weishengyu 已提交
470
            2048,
471
            class_num,
W
weishengyu 已提交
472
            weight_attr=ParamAttr(
W
weishengyu 已提交
473
                initializer=Uniform(-stdv, stdv)))
W
weishengyu 已提交
474

W
weishengyu 已提交
475
    def forward(self, input, res_dict=None):
W
weishengyu 已提交
476 477 478
        conv1 = self.conv_layer1_1(input)
        conv2 = self.conv_layer1_2(conv1)

W
weishengyu 已提交
479
        la1 = self.layer1(conv2)
W
weishengyu 已提交
480

W
dbg  
weishengyu 已提交
481 482
        tr1_1 = self.tr1_1(la1)
        tr1_2 = self.tr1_2(la1)
W
dbg  
weishengyu 已提交
483
        st2 = self.st2([tr1_1, tr1_2])
W
weishengyu 已提交
484

W
dbg  
weishengyu 已提交
485 486 487
        tr2 = self.tr2(st2[-1])
        st2.append(tr2)
        st3 = self.st3(st2)
W
weishengyu 已提交
488

W
dbg  
weishengyu 已提交
489 490 491
        tr3 = self.tr3(st3[-1])
        st3.append(tr3)
        st4 = self.st4(st3)
W
weishengyu 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

        last_cls = self.last_cls(st4)

        y = last_cls[0]
        for idx in range(3):
            y = paddle.add(last_cls[idx + 1], self.cls_head_conv_list[idx](y))

        y = self.conv_last(y)
        y = self.pool2d_avg(y)
        y = paddle.reshape(y, shape=[-1, y.shape[1]])
        y = self.out(y)
        return y


def HRNet_W18_C(**args):
    model = HRNet(width=18, **args)
    return model


def HRNet_W30_C(**args):
    model = HRNet(width=30, **args)
    return model


def HRNet_W32_C(**args):
    model = HRNet(width=32, **args)
    return model


def HRNet_W40_C(**args):
    model = HRNet(width=40, **args)
    return model


def HRNet_W44_C(**args):
    model = HRNet(width=44, **args)
    return model


def HRNet_W48_C(**args):
    model = HRNet(width=48, **args)
    return model


def HRNet_W60_C(**args):
    model = HRNet(width=60, **args)
    return model


def HRNet_W64_C(**args):
    model = HRNet(width=64, **args)
    return model


def SE_HRNet_W18_C(**args):
    model = HRNet(width=18, has_se=True, **args)
    return model


def SE_HRNet_W30_C(**args):
    model = HRNet(width=30, has_se=True, **args)
    return model


def SE_HRNet_W32_C(**args):
    model = HRNet(width=32, has_se=True, **args)
    return model


def SE_HRNet_W40_C(**args):
    model = HRNet(width=40, has_se=True, **args)
    return model


def SE_HRNet_W44_C(**args):
    model = HRNet(width=44, has_se=True, **args)
    return model


def SE_HRNet_W48_C(**args):
    model = HRNet(width=48, has_se=True, **args)
    return model


def SE_HRNet_W60_C(**args):
    model = HRNet(width=60, has_se=True, **args)
    return model


def SE_HRNet_W64_C(**args):
    model = HRNet(width=64, has_se=True, **args)
    return model