resnest.py 18.5 KB
Newer Older
W
wqz960 已提交
1 2 3 4 5 6 7 8 9 10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import paddle.fluid as fluid
from paddle.fluid.initializer import MSRA, ConstantInitializer
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.regularizer import L2DecayRegularizer
import math

W
wqz960 已提交
11 12 13 14 15 16 17 18
__all__ = [
    'ResNeSt50', 'ResNeSt101', 'ResNeSt200', 'ResNeSt269',
    'ResNeSt50_fast_1s1x64d', 'ResNeSt50_fast_2s1x64d',
    'ResNeSt50_fast_4s1x64d', 'ResNeSt50_fast_1s2x40d',
    'ResNeSt50_fast_2s2x40d', 'ResNeSt50_fast_2s2x40d',
    'ResNeSt50_fast_4s2x40d', 'ResNeSt50_fast_1s4x24d'
]

W
wqz960 已提交
19 20

class ResNeSt():
W
wqz960 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
    def __init__(self,
                 layers,
                 radix=1,
                 groups=1,
                 bottleneck_width=64,
                 dilated=False,
                 dilation=1,
                 deep_stem=False,
                 stem_width=64,
                 avg_down=False,
                 rectify_avg=False,
                 avd=False,
                 avd_first=False,
                 final_drop=0.0,
                 last_gamma=False,
                 bn_decay=0.0):
W
wqz960 已提交
37 38 39
        self.cardinality = groups
        self.bottleneck_width = bottleneck_width
        # ResNet-D params
W
wqz960 已提交
40
        self.inplanes = stem_width * 2 if deep_stem else 64
W
wqz960 已提交
41 42 43 44 45 46
        self.avg_down = avg_down
        self.last_gamma = last_gamma
        # ResNeSt params
        self.radix = radix
        self.avd = avd
        self.avd_first = avd_first
W
wqz960 已提交
47

W
wqz960 已提交
48 49 50 51 52 53
        self.deep_stem = deep_stem
        self.stem_width = stem_width
        self.layers = layers
        self.final_drop = final_drop
        self.dilated = dilated
        self.dilation = dilation
W
wqz960 已提交
54 55
        self.bn_decay = bn_decay

W
wqz960 已提交
56
        self.rectify_avg = rectify_avg
W
wqz960 已提交
57

W
wqz960 已提交
58 59
    def net(self, input, class_dim=1000):
        if self.deep_stem:
W
wqz960 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
            x = self.conv_bn_layer(
                x=input,
                num_filters=self.stem_width,
                filters_size=3,
                stride=2,
                groups=1,
                act="relu",
                name="conv1")
            x = self.conv_bn_layer(
                x=x,
                num_filters=self.stem_width,
                filters_size=3,
                stride=1,
                groups=1,
                act="relu",
                name="conv2")
            x = self.conv_bn_layer(
                x=x,
                num_filters=self.stem_width * 2,
                filters_size=3,
                stride=1,
                groups=1,
                act="relu",
                name="conv3")
W
wqz960 已提交
84
        else:
W
wqz960 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
            x = self.conv_bn_layer(
                x=input,
                num_filters=64,
                filters_size=7,
                stride=2,
                act="relu",
                name="conv1")

        x = fluid.layers.pool2d(
            input=x,
            pool_size=3,
            pool_type="max",
            pool_stride=2,
            pool_padding=1)

        x = self.resnest_layer(
            x=x,
            planes=64,
            blocks=self.layers[0],
            is_first=False,
            name="layer1")
        x = self.resnest_layer(
littletomatodonkey's avatar
littletomatodonkey 已提交
107
            x=x, planes=128, blocks=self.layers[1], stride=2, name="layer2")
W
wqz960 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        if self.dilated or self.dilation == 4:
            x = self.resnest_layer(
                x=x,
                planes=256,
                blocks=self.layers[2],
                stride=1,
                dilation=2,
                name="layer3")
            x = self.resnest_layer(
                x=x,
                planes=512,
                blocks=self.layers[3],
                stride=1,
                dilation=4,
                name="layer4")
        elif self.dilation == 2:
            x = self.resnest_layer(
                x=x,
                planes=256,
                blocks=self.layers[2],
                stride=2,
                dilation=1,
                name="layer3")
            x = self.resnest_layer(
                x=x,
                planes=512,
                blocks=self.layers[3],
                stride=1,
                dilation=2,
                name="layer4")
W
wqz960 已提交
138
        else:
W
wqz960 已提交
139 140 141 142 143 144 145 146 147 148 149 150
            x = self.resnest_layer(
                x=x,
                planes=256,
                blocks=self.layers[2],
                stride=2,
                name="layer3")
            x = self.resnest_layer(
                x=x,
                planes=512,
                blocks=self.layers[3],
                stride=2,
                name="layer4")
littletomatodonkey's avatar
littletomatodonkey 已提交
151 152
        x = fluid.layers.pool2d(input=x, pool_type="avg", global_pooling=True)
        x = fluid.layers.dropout(x=x, dropout_prob=self.final_drop)
W
wqz960 已提交
153 154 155 156 157 158 159 160
        stdv = 1.0 / math.sqrt(x.shape[1] * 1.0)
        x = fluid.layers.fc(
            input=x,
            size=class_dim,
            param_attr=ParamAttr(
                name="fc_weights",
                initializer=fluid.initializer.Uniform(-stdv, stdv)),
            bias_attr=ParamAttr(name="fc_offset"))
W
wqz960 已提交
161 162
        return x

W
wqz960 已提交
163 164 165 166 167
    def conv_bn_layer(self,
                      x,
                      num_filters,
                      filters_size,
                      stride=1,
W
wqz960 已提交
168
                      groups=1,
W
wqz960 已提交
169
                      act=None,
W
wqz960 已提交
170
                      name=None):
W
wqz960 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        x = fluid.layers.conv2d(
            input=x,
            num_filters=num_filters,
            filter_size=filters_size,
            stride=stride,
            padding=(filters_size - 1) // 2,
            groups=groups,
            act=None,
            param_attr=ParamAttr(
                initializer=MSRA(), name=name + "_weight"),
            bias_attr=False)
        x = fluid.layers.batch_norm(
            input=x,
            act=act,
            param_attr=ParamAttr(
                name=name + "_scale",
                regularizer=L2DecayRegularizer(
                    regularization_coeff=self.bn_decay)),
            bias_attr=ParamAttr(
                name=name + "_offset",
                regularizer=L2DecayRegularizer(
                    regularization_coeff=self.bn_decay)),
            moving_mean_name=name + "_mean",
            moving_variance_name=name + "_variance")
W
wqz960 已提交
195
        return x
W
wqz960 已提交
196 197

    def rsoftmax(self, x, radix, cardinality):
W
wqz960 已提交
198 199
        batch, r, h, w = x.shape
        if radix > 1:
W
wqz960 已提交
200 201 202 203 204
            x = fluid.layers.reshape(
                x=x,
                shape=[
                    0, cardinality, radix, int(r * h * w / cardinality / radix)
                ])
W
wqz960 已提交
205 206
            x = fluid.layers.transpose(x=x, perm=[0, 2, 1, 3])
            x = fluid.layers.softmax(input=x, axis=1)
W
wqz960 已提交
207
            x = fluid.layers.reshape(x=x, shape=[0, r * h * w])
W
wqz960 已提交
208 209 210 211
        else:
            x = fluid.layers.sigmoid(x=x)
        return x

W
wqz960 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    def splat_conv(self,
                   x,
                   in_channels,
                   channels,
                   kernel_size,
                   stride=1,
                   padding=0,
                   dilation=1,
                   groups=1,
                   bias=True,
                   radix=2,
                   reduction_factor=4,
                   rectify_avg=False,
                   name=None):
        x = self.conv_bn_layer(
            x=x,
            num_filters=channels * radix,
            filters_size=kernel_size,
            stride=stride,
            groups=groups * radix,
            act="relu",
            name=name + "_splat1")
W
wqz960 已提交
234 235

        batch, rchannel = x.shape[:2]
W
wqz960 已提交
236
        if radix > 1:
W
wqz960 已提交
237 238 239 240
            splited = fluid.layers.split(input=x, num_or_sections=radix, dim=1)
            gap = fluid.layers.sum(x=splited)
        else:
            gap = x
W
wqz960 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
        gap = fluid.layers.pool2d(
            input=gap, pool_type="avg", global_pooling=True)
        inter_channels = int(max(in_channels * radix // reduction_factor, 32))
        gap = self.conv_bn_layer(
            x=gap,
            num_filters=inter_channels,
            filters_size=1,
            groups=groups,
            act="relu",
            name=name + "_splat2")

        atten = fluid.layers.conv2d(
            input=gap,
            num_filters=channels * radix,
            filter_size=1,
            stride=1,
            padding=0,
            groups=groups,
            act=None,
            param_attr=ParamAttr(
                name=name + "_splat_weights", initializer=MSRA()),
            bias_attr=False)
littletomatodonkey's avatar
littletomatodonkey 已提交
263
        atten = self.rsoftmax(x=atten, radix=radix, cardinality=groups)
W
wqz960 已提交
264 265 266
        atten = fluid.layers.reshape(x=atten, shape=[-1, atten.shape[1], 1, 1])

        if radix > 1:
W
wqz960 已提交
267 268 269 270
            attens = fluid.layers.split(
                input=atten, num_or_sections=radix, dim=1)
            out = fluid.layers.sum([
                fluid.layers.elementwise_mul(
littletomatodonkey's avatar
littletomatodonkey 已提交
271
                    x=split, y=att) for (att, split) in zip(attens, splited)
W
wqz960 已提交
272
            ])
W
wqz960 已提交
273
        else:
littletomatodonkey's avatar
littletomatodonkey 已提交
274
            out = fluid.layers.elementwise_mul(x, atten)
W
wqz960 已提交
275 276
        return out

W
wqz960 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    def bottleneck(self,
                   x,
                   inplanes,
                   planes,
                   stride=1,
                   radix=1,
                   cardinality=1,
                   bottleneck_width=64,
                   avd=False,
                   avd_first=False,
                   dilation=1,
                   is_first=False,
                   rectify_avg=False,
                   last_gamma=False,
                   name=None):

W
wqz960 已提交
293
        short = x
W
wqz960 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

        group_width = int(planes * (bottleneck_width / 64.)) * cardinality
        x = self.conv_bn_layer(
            x=x,
            num_filters=group_width,
            filters_size=1,
            stride=1,
            groups=1,
            act="relu",
            name=name + "_conv1")
        if avd and avd_first and (stride > 1 or is_first):
            x = fluid.layers.pool2d(
                input=x,
                pool_size=3,
                pool_type="avg",
                pool_stride=stride,
                pool_padding=1)
W
wqz960 已提交
311
        if radix >= 1:
W
wqz960 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324
            x = self.splat_conv(
                x=x,
                in_channels=group_width,
                channels=group_width,
                kernel_size=3,
                stride=1,
                padding=dilation,
                dilation=dilation,
                groups=cardinality,
                bias=False,
                radix=radix,
                rectify_avg=rectify_avg,
                name=name + "_splatconv")
W
wqz960 已提交
325
        else:
W
wqz960 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
            x = self.conv_bn_layer(
                x=x,
                num_filters=group_width,
                filters_size=3,
                stride=1,
                padding=dilation,
                dilation=dialtion,
                groups=cardinality,
                act="relu",
                name=name + "_conv2")

        if avd and avd_first == False and (stride > 1 or is_first):
            x = fluid.layers.pool2d(
                input=x,
                pool_size=3,
                pool_type="avg",
                pool_stride=stride,
                pool_padding=1)
        x = self.conv_bn_layer(
            x=x,
            num_filters=planes * 4,
            filters_size=1,
            stride=1,
            groups=1,
            act=None,
            name=name + "_conv3")

        if stride != 1 or self.inplanes != planes * 4:
W
wqz960 已提交
354
            if self.avg_down:
W
wqz960 已提交
355 356 357 358 359 360 361
                if dilation == 1:
                    short = fluid.layers.pool2d(
                        input=short,
                        pool_size=stride,
                        pool_type="avg",
                        pool_stride=stride,
                        ceil_mode=True)
W
wqz960 已提交
362
                else:
W
wqz960 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
                    short = fluid.layers.pool2d(
                        input=short,
                        pool_size=1,
                        pool_type="avg",
                        pool_stride=1,
                        ceil_mode=True)
                short = fluid.layers.conv2d(
                    input=short,
                    num_filters=planes * 4,
                    filter_size=1,
                    stride=1,
                    padding=0,
                    groups=1,
                    act=None,
                    param_attr=ParamAttr(
                        name=name + "_weights", initializer=MSRA()),
                    bias_attr=False)
W
wqz960 已提交
380
            else:
W
wqz960 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
                short = fluid.layers.conv2d(
                    input=short,
                    num_filters=planes * 4,
                    filter_size=1,
                    stride=stride,
                    param_attr=ParamAttr(
                        name=name + "_shortcut_weights", initializer=MSRA()),
                    bias_attr=False)

            short = fluid.layers.batch_norm(
                input=short,
                act=None,
                param_attr=ParamAttr(
                    name=name + "_shortcut_scale",
                    regularizer=L2DecayRegularizer(
                        regularization_coeff=self.bn_decay)),
                bias_attr=ParamAttr(
                    name=name + "_shortcut_offset",
                    regularizer=L2DecayRegularizer(
                        regularization_coeff=self.bn_decay)),
                moving_mean_name=name + "_shortcut_mean",
                moving_variance_name=name + "_shortcut_variance")

W
wqz960 已提交
404
        return fluid.layers.elementwise_add(x=short, y=x, act="relu")
W
wqz960 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

    def resnest_layer(self,
                      x,
                      planes,
                      blocks,
                      stride=1,
                      dilation=1,
                      is_first=True,
                      name=None):
        if dilation == 1 or dilation == 2:
            x = self.bottleneck(
                x=x,
                inplanes=self.inplanes,
                planes=planes,
                stride=stride,
                radix=self.radix,
                cardinality=self.cardinality,
                bottleneck_width=self.bottleneck_width,
                avd=self.avd,
                avd_first=self.avd_first,
                dilation=1,
                is_first=is_first,
                rectify_avg=self.rectify_avg,
                last_gamma=self.last_gamma,
                name=name + "_bottleneck_0")
        elif dilation == 4:
            x = self.bottleneck(
                x=x,
                inplanes=self.inplanes,
                planes=planes,
                stride=stride,
                radix=self.radix,
                cardinality=self.cardinality,
                bottleneck_width=self.bottleneck_width,
                avd=self.avd,
                avd_first=self.avd_first,
                dilation=2,
                is_first=is_first,
                rectify_avg=self.rectify_avg,
                last_gamma=self.last_gamma,
                name=name + "_bottleneck_0")
W
wqz960 已提交
446 447
        else:
            raise RuntimeError("=>unknown dilation size")
W
wqz960 已提交
448 449

        self.inplanes = planes * 4
W
wqz960 已提交
450
        for i in range(1, blocks):
W
wqz960 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464
            name = name + "_bottleneck_" + str(i)
            x = self.bottleneck(
                x=x,
                inplanes=self.inplanes,
                planes=planes,
                radix=self.radix,
                cardinality=self.cardinality,
                bottleneck_width=self.bottleneck_width,
                avd=self.avd,
                avd_first=self.avd_first,
                dilation=dilation,
                rectify_avg=self.rectify_avg,
                last_gamma=self.last_gamma,
                name=name)
W
wqz960 已提交
465
        return x
W
wqz960 已提交
466 467


W
wqz960 已提交
468
def ResNeSt50(**args):
W
wqz960 已提交
469 470 471 472 473 474 475 476 477 478 479 480
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=2,
        groups=1,
        bottleneck_width=64,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=False,
        final_drop=0.0,
        **args)
W
wqz960 已提交
481 482 483 484
    return model


def ResNeSt101(**args):
W
wqz960 已提交
485 486 487 488 489 490 491 492 493 494 495 496
    model = ResNeSt(
        layers=[3, 4, 23, 3],
        radix=2,
        groups=1,
        bottleneck_width=64,
        deep_stem=True,
        stem_width=64,
        avg_down=True,
        avd=True,
        avd_first=False,
        final_drop=0.0,
        **args)
W
wqz960 已提交
497 498 499 500
    return model


def ResNeSt200(**args):
W
wqz960 已提交
501 502 503 504 505 506 507 508 509 510 511 512
    model = ResNeSt(
        layers=[3, 24, 36, 3],
        radix=2,
        groups=1,
        bottleneck_width=64,
        deep_stem=True,
        stem_width=64,
        avg_down=True,
        avd=True,
        avd_first=False,
        final_drop=0.2,
        **args)
W
wqz960 已提交
513 514
    return model

W
wqz960 已提交
515

W
wqz960 已提交
516
def ResNeSt269(**args):
W
wqz960 已提交
517 518 519 520 521 522 523 524 525 526 527 528
    model = ResNeSt(
        layers=[3, 30, 48, 8],
        radix=2,
        groups=1,
        bottleneck_width=64,
        deep_stem=True,
        stem_width=64,
        avg_down=True,
        avd=True,
        avd_first=False,
        final_drop=0.2,
        **args)
W
wqz960 已提交
529 530
    return model

W
wqz960 已提交
531

W
wqz960 已提交
532
def ResNeSt50_fast_1s1x64d(**args):
W
wqz960 已提交
533 534 535 536 537 538 539 540 541 542 543 544
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=1,
        groups=1,
        bottleneck_width=64,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=True,
        final_drop=0.0,
        **args)
W
wqz960 已提交
545 546
    return model

W
wqz960 已提交
547

W
wqz960 已提交
548
def ResNeSt50_fast_2s1x64d(**args):
W
wqz960 已提交
549 550 551 552 553 554 555 556 557 558 559 560
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=2,
        groups=1,
        bottleneck_width=64,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=True,
        final_drop=0.0,
        **args)
W
wqz960 已提交
561 562
    return model

W
wqz960 已提交
563

W
wqz960 已提交
564
def ResNeSt50_fast_4s1x64d(**args):
W
wqz960 已提交
565 566 567 568 569 570 571 572 573 574 575 576
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=2,
        groups=1,
        bottleneck_width=64,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=True,
        final_drop=0.0,
        **args)
W
wqz960 已提交
577 578
    return model

W
wqz960 已提交
579

W
wqz960 已提交
580
def ResNeSt50_fast_1s2x40d(**args):
W
wqz960 已提交
581 582 583 584 585 586 587 588 589 590 591 592
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=1,
        groups=2,
        bottleneck_width=40,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=True,
        final_drop=0.0,
        **args)
W
wqz960 已提交
593 594
    return model

W
wqz960 已提交
595

W
wqz960 已提交
596
def ResNeSt50_fast_2s2x40d(**args):
W
wqz960 已提交
597 598 599 600 601 602 603 604 605 606 607 608
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=2,
        groups=2,
        bottleneck_width=40,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=True,
        final_drop=0.0,
        **args)
W
wqz960 已提交
609 610
    return model

W
wqz960 已提交
611

W
wqz960 已提交
612
def ResNeSt50_fast_4s2x40d(**args):
W
wqz960 已提交
613 614 615 616 617 618 619 620 621 622 623 624
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=4,
        groups=2,
        bottleneck_width=40,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=True,
        final_drop=0.0,
        **args)
W
wqz960 已提交
625 626 627
    return model


W
wqz960 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641
def ResNeSt50_fast_1s4x24d(**args):
    model = ResNeSt(
        layers=[3, 4, 6, 3],
        radix=1,
        groups=4,
        bottleneck_width=24,
        deep_stem=True,
        stem_width=32,
        avg_down=True,
        avd=True,
        avd_first=True,
        final_drop=0.0,
        **args)
    return model