resnest.py 18.6 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 107 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 138 139 140 141
            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(
            x=x, 
            planes=128, 
            blocks=self.layers[1], 
            stride=2, 
            name="layer2")
        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 已提交
142
        else:
W
wqz960 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
            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")
        x = fluid.layers.pool2d(
            input=x, pool_type="avg", global_pooling=True)
        x = fluid.layers.dropout(
            x=x, dropout_prob=self.final_drop)
        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 已提交
167 168
        return x

W
wqz960 已提交
169 170 171 172 173
    def conv_bn_layer(self,
                      x,
                      num_filters,
                      filters_size,
                      stride=1,
W
wqz960 已提交
174
                      groups=1,
W
wqz960 已提交
175
                      act=None,
W
wqz960 已提交
176
                      name=None):
W
wqz960 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        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 已提交
201
        return x
W
wqz960 已提交
202 203

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

W
wqz960 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    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 已提交
240 241

        batch, rchannel = x.shape[:2]
W
wqz960 已提交
242
        if radix > 1:
W
wqz960 已提交
243 244 245 246
            splited = fluid.layers.split(input=x, num_or_sections=radix, dim=1)
            gap = fluid.layers.sum(x=splited)
        else:
            gap = x
W
wqz960 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        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)
        atten = self.rsoftmax(
            x=atten, radix=radix, cardinality=groups)
W
wqz960 已提交
271 272 273
        atten = fluid.layers.reshape(x=atten, shape=[-1, atten.shape[1], 1, 1])

        if radix > 1:
W
wqz960 已提交
274 275 276 277 278 279
            attens = fluid.layers.split(
                input=atten, num_or_sections=radix, dim=1)
            out = fluid.layers.sum([
                fluid.layers.elementwise_mul(
                    x=att, y=split) for (att, split) in zip(attens, splited)
            ])
W
wqz960 已提交
280 281 282 283
        else:
            out = fluid.layers.elementwise_mul(atten, x)
        return out

W
wqz960 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    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 已提交
300
        short = x
W
wqz960 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317

        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 已提交
318
        if radix >= 1:
W
wqz960 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331
            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 已提交
332
        else:
W
wqz960 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
            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 已提交
361
            if self.avg_down:
W
wqz960 已提交
362 363 364 365 366 367 368
                if dilation == 1:
                    short = fluid.layers.pool2d(
                        input=short,
                        pool_size=stride,
                        pool_type="avg",
                        pool_stride=stride,
                        ceil_mode=True)
W
wqz960 已提交
369
                else:
W
wqz960 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
                    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 已提交
387
            else:
W
wqz960 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
                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 已提交
411
        return fluid.layers.elementwise_add(x=short, y=x, act="relu")
W
wqz960 已提交
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 446 447 448 449 450 451 452

    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 已提交
453 454
        else:
            raise RuntimeError("=>unknown dilation size")
W
wqz960 已提交
455 456

        self.inplanes = planes * 4
W
wqz960 已提交
457
        for i in range(1, blocks):
W
wqz960 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471
            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 已提交
472
        return x
W
wqz960 已提交
473 474


W
wqz960 已提交
475
def ResNeSt50(**args):
W
wqz960 已提交
476 477 478 479 480 481 482 483 484 485 486 487
    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 已提交
488 489 490 491
    return model


def ResNeSt101(**args):
W
wqz960 已提交
492 493 494 495 496 497 498 499 500 501 502 503
    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 已提交
504 505 506 507
    return model


def ResNeSt200(**args):
W
wqz960 已提交
508 509 510 511 512 513 514 515 516 517 518 519
    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 已提交
520 521
    return model

W
wqz960 已提交
522

W
wqz960 已提交
523
def ResNeSt269(**args):
W
wqz960 已提交
524 525 526 527 528 529 530 531 532 533 534 535
    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 已提交
536 537
    return model

W
wqz960 已提交
538

W
wqz960 已提交
539
def ResNeSt50_fast_1s1x64d(**args):
W
wqz960 已提交
540 541 542 543 544 545 546 547 548 549 550 551
    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 已提交
552 553
    return model

W
wqz960 已提交
554

W
wqz960 已提交
555
def ResNeSt50_fast_2s1x64d(**args):
W
wqz960 已提交
556 557 558 559 560 561 562 563 564 565 566 567
    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 已提交
568 569
    return model

W
wqz960 已提交
570

W
wqz960 已提交
571
def ResNeSt50_fast_4s1x64d(**args):
W
wqz960 已提交
572 573 574 575 576 577 578 579 580 581 582 583
    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 已提交
584 585
    return model

W
wqz960 已提交
586

W
wqz960 已提交
587
def ResNeSt50_fast_1s2x40d(**args):
W
wqz960 已提交
588 589 590 591 592 593 594 595 596 597 598 599
    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 已提交
600 601
    return model

W
wqz960 已提交
602

W
wqz960 已提交
603
def ResNeSt50_fast_2s2x40d(**args):
W
wqz960 已提交
604 605 606 607 608 609 610 611 612 613 614 615
    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 已提交
616 617
    return model

W
wqz960 已提交
618

W
wqz960 已提交
619
def ResNeSt50_fast_4s2x40d(**args):
W
wqz960 已提交
620 621 622 623 624 625 626 627 628 629 630 631
    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 已提交
632 633 634
    return model


W
wqz960 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648
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