resnet.py 20.5 KB
Newer Older
C
cuicheng01 已提交
1
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
C
cuicheng01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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
from __future__ import absolute_import, division, print_function
C
cuicheng01 已提交
16 17 18 19 20 21 22 23 24 25

import numpy as np
import paddle
from paddle import ParamAttr
import paddle.nn as nn
from paddle.nn import Conv2D, BatchNorm, Linear
from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
from paddle.nn.initializer import Uniform
import math

C
cuicheng01 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
from theseus_layer import TheseusLayer
from ppcls.utils.save_load import load_dygraph_pretrain_from, load_dygraph_pretrain_from_url


MODEL_URLS = {
    "ResNet18": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet18_pretrained.pdparams",
    "ResNet18_vd": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet18_vd_pretrained.pdparams",
    "ResNet34": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet34_pretrained.pdparams",
    "ResNet34_vd": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet34_vd_pretrained.pdparams",
    "ResNet50": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet50_pretrained.pdparams",
    "ResNet50_vd": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet50_vd_pretrained.pdparams",
    "ResNet101": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet101_pretrained.pdparams",
    "ResNet101_vd": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet101_vd_pretrained.pdparams",
    "ResNet152": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet152_pretrained.pdparams",
    "ResNet152_vd": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet152_vd_pretrained.pdparams",
    "ResNet200_vd": "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/ResNet200_vd_pretrained.pdparams",
}
C
cuicheng01 已提交
43

C
cuicheng01 已提交
44
__all__ = MODEL_URLS.keys()
C
cuicheng01 已提交
45 46


C
cuicheng01 已提交
47 48 49 50 51 52 53 54 55
'''
ResNet config: dict.
    key: depth of ResNet.
    values: config's dict of specific model.
        keys:
            block_type: Two different blocks in ResNet, BasicBlock and BottleneckBlock are optional.
            block_depth: The number of blocks in different stages in ResNet.
            num_channels: The number of channels to enter the next stage.
'''
C
cuicheng01 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
NET_CONFIG = {
    "18": {
        "block_type": "BasicBlock", "block_depth": [2, 2, 2, 2], "num_channels": [64, 64, 128, 256]},
    "34": {
        "block_type": "BasicBlock", "block_depth": [3, 4, 6, 3], "num_channels": [64, 64, 128, 256]},
    "50": {
        "block_type": "BottleneckBlock", "block_depth": [3, 4, 6, 3], "num_channels": [64, 256, 512, 1024]},
    "101": {
        "block_type": "BottleneckBlock", "block_depth": [3, 4, 23, 3], "num_channels": [64, 256, 512, 1024]},
    "152": {
        "block_type": "BottleneckBlock", "block_depth": [3, 8, 36, 3], "num_channels": [64, 256, 512, 1024]},
    "200": {
        "block_type": "BottleneckBlock", "block_depth": [3, 12, 48, 3], "num_channels": [64, 256, 512, 1024]},
}


class ConvBNLayer(TheseusLayer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 groups=1,
                 is_vd_mode=False,
                 act=None,
                 lr_mult=1.0):
C
cuicheng01 已提交
82
        super().__init__()
C
cuicheng01 已提交
83 84 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
        self.is_vd_mode = is_vd_mode
        self.act = act
        self.avgpool = AvgPool2D(
            kernel_size=2, stride=2, padding=0, ceil_mode=True)
        self.conv = Conv2D(
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
            stride=stride,
            padding=(filter_size - 1) // 2,
            groups=groups,
            weight_attr=ParamAttr(learning_rate=lr_mult),
            bias_attr=False)
        self.bn = BatchNorm(
            num_filters,
            param_attr=ParamAttr(learning_rate=lr_mult),
            bias_attr=ParamAttr(learning_rate=lr_mult))
        self.relu = nn.ReLU()

    def forward(self, x):
        if self.is_vd_mode:
            x = self.avgpool(x)
        x = self.conv(x)
        x = self.bn(x)
        if self.act:
            x = self.relu(x)
        return x


class BottleneckBlock(TheseusLayer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 stride,
                 shortcut=True,
                 if_first=False,
                 lr_mult=1.0,
                ):
C
cuicheng01 已提交
121
        super().__init__()
C
cuicheng01 已提交
122 123 124 125 126

        self.conv0 = ConvBNLayer(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=1,
C
cuicheng01 已提交
127
            act="relu",
C
cuicheng01 已提交
128 129 130 131 132 133
            lr_mult=lr_mult)
        self.conv1 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters,
            filter_size=3,
            stride=stride,
C
cuicheng01 已提交
134
            act="relu",
C
cuicheng01 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            lr_mult=lr_mult)
        self.conv2 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters * 4,
            filter_size=1,
            act=None,
            lr_mult=lr_mult)

        if not shortcut:
            self.short = ConvBNLayer(
                num_channels=num_channels,
                num_filters=num_filters * 4,
                filter_size=1,
                stride=stride if if_first else 1,
                is_vd_mode=False if if_first else True,
                lr_mult=lr_mult)
        self.relu = nn.ReLU()
        self.shortcut = shortcut

    def forward(self, x):
        identity = x
        x = self.conv0(x)
        x = self.conv1(x)
        x = self.conv2(x)

        if self.shortcut:
            short = identity
        else:
            short = self.short(identity)
        x = paddle.add(x=x, y=short)
        x = self.relu(x)
        return x


class BasicBlock(TheseusLayer):
    def __init__(self,
                 num_channels,
                 num_filters,
                 stride,
                 shortcut=True,
                 if_first=False,
                 lr_mult=1.0):
C
cuicheng01 已提交
177 178
        super().__init__()

C
cuicheng01 已提交
179 180 181 182 183 184
        self.stride = stride
        self.conv0 = ConvBNLayer(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=3,
            stride=stride,
C
cuicheng01 已提交
185
            act="relu",
C
cuicheng01 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
            lr_mult=lr_mult)
        self.conv1 = ConvBNLayer(
            num_channels=num_filters,
            num_filters=num_filters,
            filter_size=3,
            act=None,
            lr_mult=lr_mult)
        if not shortcut:
            self.short = ConvBNLayer(
                num_channels=num_channels,
                num_filters=num_filters,
                filter_size=1,
                stride=stride if if_first else 1,
                is_vd_mode=False if if_first else True,
                lr_mult=lr_mult)
        self.shortcut = shortcut
        self.relu = nn.ReLU()

    def forward(self, x):
        identity = x
        x = self.conv0(x)
        x = self.conv1(x)
        if self.shortcut:
            short = identity
        else:
            short = self.short(identity)
        x = paddle.add(x=x, y=short)
        x = self.relu(x)
        return x


class ResNet(TheseusLayer):
C
cuicheng01 已提交
218 219 220 221 222 223 224 225 226 227
    """
    ResNet
    Args:
        config: dict. config of ResNet.
        version: str="vb". Different version of ResNet, version vd can perform better. 
        class_num: int=1000. The number of classes.
        lr_mult_list: list. Control the learning rate of different stages.
        pretrained: (True or False) or path of pretrained_model. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific ResNet model depends on args.
C
cuicheng01 已提交
228 229 230
    """
    def __init__(self,
                 config,
C
cuicheng01 已提交
231 232 233 234 235
                 version="vb",
                 class_num=1000,
                 lr_mult_list=[1.0, 1.0, 1.0, 1.0, 1.0],
                 pretrained=False):
        super().__init__()
C
cuicheng01 已提交
236 237 238 239

        self.cfg = config
        self.lr_mult_list = lr_mult_list
        self.is_vd_mode = version == "vd"
C
cuicheng01 已提交
240 241 242 243 244 245 246 247
        self.class_num = class_num
        self.num_filters = [64, 128, 256, 512]
        self.block_depth = self.cfg["block_depth"]
        self.block_type = self.cfg["block_type"]
        self.num_channels = self.cfg["num_channels"]
        self.channels_mult = 1 if self.num_channels[-1] == 256 else 4
        self.pretrained = pretrained   
     
C
cuicheng01 已提交
248 249 250 251 252 253 254 255
        assert isinstance(self.lr_mult_list, (
            list, tuple
        )), "lr_mult_list should be in (list, tuple) but got {}".format(
            type(self.lr_mult_list))
        assert len(
            self.lr_mult_list
        ) == 5, "lr_mult_list length should be 5 but got {}".format(
            len(self.lr_mult_list))
C
cuicheng01 已提交
256
        
C
cuicheng01 已提交
257 258

        self.stem_cfg = {
C
cuicheng01 已提交
259
            #num_channels, num_filters, filter_size, stride
C
cuicheng01 已提交
260 261 262 263 264 265 266 267 268 269 270
            "vb": [[3, 64, 7, 2]],
            "vd": [[3, 32, 3, 2],
                   [32, 32, 3, 1],
                   [32, 64, 3, 1]]}
        
        self.stem = nn.Sequential(*[
            ConvBNLayer(
                    num_channels=in_c,
                    num_filters=out_c,
                    filter_size=k,
                    stride=s,
C
cuicheng01 已提交
271
                    act="relu",
C
cuicheng01 已提交
272 273 274 275 276
                    lr_mult=self.lr_mult_list[0])
            for in_c, out_c, k, s in self.stem_cfg[version]
        ])
        
        self.maxpool = MaxPool2D(kernel_size=3, stride=2, padding=1)
C
cuicheng01 已提交
277 278
        block_list = []
        for block_idx in range(len(self.block_depth)):
C
cuicheng01 已提交
279
            shortcut = False
C
cuicheng01 已提交
280 281 282 283 284 285 286
            for i in range(self.block_depth[block_idx]):
                block_list.append(
                    globals()[self.block_type](
                    num_channels=self.num_channels[block_idx]
                    if i == 0 else self.num_filters[block_idx] * self.channels_mult,
                    num_filters=self.num_filters[block_idx],
                    stride=2 if i == 0 and block_idx != 0 else 1,
C
cuicheng01 已提交
287
                    shortcut=shortcut,
C
cuicheng01 已提交
288 289 290 291
                    if_first=block_idx == i == 0 if version == "vd" else True,
                    lr_mult=self.lr_mult_list[block_idx + 1]))
                shortcut = True    
        self.blocks = nn.Sequential(*block_list)
C
cuicheng01 已提交
292 293

        self.avgpool = AdaptiveAvgPool2D(1)
C
cuicheng01 已提交
294
        self.avgpool_channels = self.num_channels[-1] * 2
C
cuicheng01 已提交
295 296 297 298

        stdv = 1.0 / math.sqrt(self.avgpool_channels * 1.0)
        self.out = Linear(
            self.avgpool_channels,
C
cuicheng01 已提交
299
            self.class_num,
C
cuicheng01 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313
            weight_attr=ParamAttr(
                initializer=Uniform(-stdv, stdv)))

    def forward(self, x):
        x = self.stem(x)
        x = self.maxpool(x)
        x = self.blocks(x)
        x = self.avgpool(x)
        x = paddle.reshape(x, shape=[-1, self.avgpool_channels])
        x = self.out(x)
        return x


def ResNet18(**args):
C
cuicheng01 已提交
314 315 316 317 318 319 320 321 322 323
    """
    ResNet18
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet18` model depends on args.
    """
C
cuicheng01 已提交
324
    model = ResNet(config=NET_CONFIG["18"], version="vb", **args)
C
cuicheng01 已提交
325 326 327 328 329 330 331 332
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet18"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
333 334
    return model

C
cuicheng01 已提交
335

C
cuicheng01 已提交
336
def ResNet18_vd(**args):
C
cuicheng01 已提交
337 338 339 340 341 342 343 344 345 346
    """
    ResNet18_vd
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet18_vd` model depends on args.
    """
C
cuicheng01 已提交
347
    model = ResNet(config=NET_CONFIG["18"], version="vd", **args)
C
cuicheng01 已提交
348 349 350 351 352 353 354 355
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet18_vd"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
356 357
    return model

C
cuicheng01 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

def ResNet34(**args):
    """
    ResNet34
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet18` model depends on args.
    """
    model = ResNet(config=NET_CONFIG["34"], version="vb", **args)
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet34"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
    return model


def ResNet34_vd(**args):
    """
    ResNet34_vd
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet18_vd` model depends on args.
    """
    model = ResNet(config=NET_CONFIG["34"], version="vd", **args)
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet34_vd"], use_ssld=True)
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
    return model


C
cuicheng01 已提交
405
def ResNet50(**args):
C
cuicheng01 已提交
406 407 408 409 410 411 412 413 414 415
    """
    ResNet50
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet50` model depends on args.
    """
C
cuicheng01 已提交
416
    model = ResNet(config=NET_CONFIG["50"], version="vb", **args)
C
cuicheng01 已提交
417 418 419 420 421 422 423 424
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet50"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
425 426
    return model

C
cuicheng01 已提交
427

C
cuicheng01 已提交
428
def ResNet50_vd(**args):
C
cuicheng01 已提交
429 430 431 432 433 434 435 436 437 438
    """
    ResNet50_vd
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet50_vd` model depends on args.
    """
C
cuicheng01 已提交
439
    model = ResNet(config=NET_CONFIG["50"], version="vd", **args)
C
cuicheng01 已提交
440 441 442 443 444 445 446 447
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet50_vd"], use_ssld=True)
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
448 449
    return model

C
cuicheng01 已提交
450

C
cuicheng01 已提交
451
def ResNet101(**args):
C
cuicheng01 已提交
452 453 454 455 456 457 458 459 460 461
    """
    ResNet101
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet101` model depends on args.
    """
C
cuicheng01 已提交
462
    model = ResNet(config=NET_CONFIG["101"], version="vb", **args)
C
cuicheng01 已提交
463 464 465 466 467 468 469 470
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet101"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
471 472
    return model

C
cuicheng01 已提交
473

C
cuicheng01 已提交
474
def ResNet101_vd(**args):
C
cuicheng01 已提交
475 476 477 478 479 480 481 482 483 484
    """
    ResNet101_vd
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet101_vd` model depends on args.
    """
C
cuicheng01 已提交
485
    model = ResNet(config=NET_CONFIG["101"], version="vd", **args)
C
cuicheng01 已提交
486 487 488 489 490 491 492 493
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet101_vd"], use_ssld=True)
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
494 495
    return model

C
cuicheng01 已提交
496

C
cuicheng01 已提交
497
def ResNet152(**args):
C
cuicheng01 已提交
498 499 500 501 502 503 504 505 506 507
    """
    ResNet152
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet152` model depends on args.
    """
C
cuicheng01 已提交
508
    model = ResNet(config=NET_CONFIG["152"], version="vb", **args)
C
cuicheng01 已提交
509 510 511 512 513 514 515 516
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet152"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
517 518
    return model

C
cuicheng01 已提交
519

C
cuicheng01 已提交
520
def ResNet152_vd(**args):
C
cuicheng01 已提交
521 522 523 524 525 526 527 528 529 530
    """
    ResNet152_vd
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet152_vd` model depends on args.
    """
C
cuicheng01 已提交
531
    model = ResNet(config=NET_CONFIG["152"], version="vd", **args)
C
cuicheng01 已提交
532 533 534 535 536 537 538 539
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet152_vd"])
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
540 541 542 543
    return model


def ResNet200_vd(**args):
C
cuicheng01 已提交
544 545 546 547 548 549 550 551 552 553
    """
    ResNet200_vd
    Args:
        kwargs: 
            class_num: int=1000. Output dim of last fc layer.
            lr_mult_list: list=[1.0, 1.0, 1.0, 1.0, 1.0]. Control the learning rate of different stages.
            pretrained: bool or str, default: bool=False. Whether to load the pretrained model.
    Returns:
        model: nn.Layer. Specific `ResNet200_vd` model depends on args.
    """
C
cuicheng01 已提交
554
    model = ResNet(config=NET_CONFIG["200"], version="vd", **args)
C
cuicheng01 已提交
555 556 557 558 559 560 561 562
    if isinstance(model.pretrained, bool):
        if model.pretrained is True:
            load_dygraph_pretrain_from_url(model, MODEL_URLS["ResNet200_vd"], use_ssld=True)
    elif isinstance(model.pretrained, str):
        load_dygraph_pretrain(model, model.pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type")
C
cuicheng01 已提交
563
    return model