densenet.py 11.1 KB
Newer Older
C
cuicheng01 已提交
1
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
littletomatodonkey's avatar
littletomatodonkey 已提交
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.

G
gaotingquan 已提交
15 16
# reference: https://arxiv.org/abs/1608.06993

littletomatodonkey's avatar
littletomatodonkey 已提交
17 18 19 20
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

littletomatodonkey's avatar
littletomatodonkey 已提交
21
import numpy as np
W
WuHaobo 已提交
22
import paddle
littletomatodonkey's avatar
littletomatodonkey 已提交
23 24
from paddle import ParamAttr
import paddle.nn as nn
25 26
from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
littletomatodonkey's avatar
littletomatodonkey 已提交
27
from paddle.nn.initializer import Uniform
littletomatodonkey's avatar
littletomatodonkey 已提交
28 29

import math
W
WuHaobo 已提交
30

C
cuicheng01 已提交
31 32
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

littletomatodonkey's avatar
littletomatodonkey 已提交
33 34 35 36 37 38 39 40 41 42 43 44
MODEL_URLS = {
    "DenseNet121":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet121_pretrained.pdparams",
    "DenseNet161":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet161_pretrained.pdparams",
    "DenseNet169":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet169_pretrained.pdparams",
    "DenseNet201":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet201_pretrained.pdparams",
    "DenseNet264":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DenseNet264_pretrained.pdparams",
}
C
cuicheng01 已提交
45 46

__all__ = list(MODEL_URLS.keys())
W
WuHaobo 已提交
47 48


littletomatodonkey's avatar
littletomatodonkey 已提交
49
class BNACConvLayer(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 pad=0,
                 groups=1,
                 act="relu",
                 name=None):
        super(BNACConvLayer, self).__init__()

        self._batch_norm = BatchNorm(
            num_channels,
            act=act,
            param_attr=ParamAttr(name=name + '_bn_scale'),
            bias_attr=ParamAttr(name + '_bn_offset'),
            moving_mean_name=name + '_bn_mean',
            moving_variance_name=name + '_bn_variance')

69
        self._conv = Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
70 71 72
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
littletomatodonkey's avatar
littletomatodonkey 已提交
73 74 75
            stride=stride,
            padding=pad,
            groups=groups,
littletomatodonkey's avatar
littletomatodonkey 已提交
76
            weight_attr=ParamAttr(name=name + "_weights"),
littletomatodonkey's avatar
littletomatodonkey 已提交
77 78 79 80 81 82 83 84
            bias_attr=False)

    def forward(self, input):
        y = self._batch_norm(input)
        y = self._conv(y)
        return y


littletomatodonkey's avatar
littletomatodonkey 已提交
85
class DenseLayer(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    def __init__(self, num_channels, growth_rate, bn_size, dropout, name=None):
        super(DenseLayer, self).__init__()
        self.dropout = dropout

        self.bn_ac_func1 = BNACConvLayer(
            num_channels=num_channels,
            num_filters=bn_size * growth_rate,
            filter_size=1,
            pad=0,
            stride=1,
            name=name + "_x1")

        self.bn_ac_func2 = BNACConvLayer(
            num_channels=bn_size * growth_rate,
            num_filters=growth_rate,
            filter_size=3,
            pad=1,
            stride=1,
            name=name + "_x2")

        if dropout:
littletomatodonkey's avatar
littletomatodonkey 已提交
107
            self.dropout_func = Dropout(p=dropout, mode="downscale_in_infer")
littletomatodonkey's avatar
littletomatodonkey 已提交
108 109 110 111 112 113

    def forward(self, input):
        conv = self.bn_ac_func1(input)
        conv = self.bn_ac_func2(conv)
        if self.dropout:
            conv = self.dropout_func(conv)
littletomatodonkey's avatar
littletomatodonkey 已提交
114
        conv = paddle.concat([input, conv], axis=1)
littletomatodonkey's avatar
littletomatodonkey 已提交
115 116 117
        return conv


littletomatodonkey's avatar
littletomatodonkey 已提交
118
class DenseBlock(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    def __init__(self,
                 num_channels,
                 num_layers,
                 bn_size,
                 growth_rate,
                 dropout,
                 name=None):
        super(DenseBlock, self).__init__()
        self.dropout = dropout

        self.dense_layer_func = []

        pre_channel = num_channels
        for layer in range(num_layers):
            self.dense_layer_func.append(
                self.add_sublayer(
                    "{}_{}".format(name, layer + 1),
                    DenseLayer(
                        num_channels=pre_channel,
                        growth_rate=growth_rate,
                        bn_size=bn_size,
                        dropout=dropout,
                        name=name + '_' + str(layer + 1))))
            pre_channel = pre_channel + growth_rate

    def forward(self, input):
        conv = input
        for func in self.dense_layer_func:
            conv = func(conv)
        return conv


littletomatodonkey's avatar
littletomatodonkey 已提交
151
class TransitionLayer(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
152 153 154 155 156 157 158 159 160 161 162
    def __init__(self, num_channels, num_output_features, name=None):
        super(TransitionLayer, self).__init__()

        self.conv_ac_func = BNACConvLayer(
            num_channels=num_channels,
            num_filters=num_output_features,
            filter_size=1,
            pad=0,
            stride=1,
            name=name)

163
        self.pool2d_avg = AvgPool2D(kernel_size=2, stride=2, padding=0)
littletomatodonkey's avatar
littletomatodonkey 已提交
164 165 166 167 168 169 170

    def forward(self, input):
        y = self.conv_ac_func(input)
        y = self.pool2d_avg(y)
        return y


littletomatodonkey's avatar
littletomatodonkey 已提交
171
class ConvBNLayer(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
172 173 174 175 176 177 178 179 180 181 182
    def __init__(self,
                 num_channels,
                 num_filters,
                 filter_size,
                 stride=1,
                 pad=0,
                 groups=1,
                 act="relu",
                 name=None):
        super(ConvBNLayer, self).__init__()

183
        self._conv = Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
184 185 186
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
littletomatodonkey's avatar
littletomatodonkey 已提交
187 188 189
            stride=stride,
            padding=pad,
            groups=groups,
littletomatodonkey's avatar
littletomatodonkey 已提交
190
            weight_attr=ParamAttr(name=name + "_weights"),
littletomatodonkey's avatar
littletomatodonkey 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
            bias_attr=False)
        self._batch_norm = BatchNorm(
            num_filters,
            act=act,
            param_attr=ParamAttr(name=name + '_bn_scale'),
            bias_attr=ParamAttr(name + '_bn_offset'),
            moving_mean_name=name + '_bn_mean',
            moving_variance_name=name + '_bn_variance')

    def forward(self, input):
        y = self._conv(input)
        y = self._batch_norm(y)
        return y


littletomatodonkey's avatar
littletomatodonkey 已提交
206
class DenseNet(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
207
    def __init__(self, layers=60, bn_size=4, dropout=0, class_num=1000):
littletomatodonkey's avatar
littletomatodonkey 已提交
208
        super(DenseNet, self).__init__()
W
WuHaobo 已提交
209 210 211

        supported_layers = [121, 161, 169, 201, 264]
        assert layers in supported_layers, \
littletomatodonkey's avatar
littletomatodonkey 已提交
212 213
            "supported layers are {} but input layer is {}".format(
                supported_layers, layers)
W
WuHaobo 已提交
214 215 216 217 218 219 220 221
        densenet_spec = {
            121: (64, 32, [6, 12, 24, 16]),
            161: (96, 48, [6, 12, 36, 24]),
            169: (64, 32, [6, 12, 32, 32]),
            201: (64, 32, [6, 12, 48, 32]),
            264: (64, 32, [6, 12, 64, 48])
        }
        num_init_features, growth_rate, block_config = densenet_spec[layers]
littletomatodonkey's avatar
littletomatodonkey 已提交
222 223 224

        self.conv1_func = ConvBNLayer(
            num_channels=3,
W
WuHaobo 已提交
225 226 227
            num_filters=num_init_features,
            filter_size=7,
            stride=2,
littletomatodonkey's avatar
littletomatodonkey 已提交
228
            pad=3,
W
WuHaobo 已提交
229
            act='relu',
littletomatodonkey's avatar
littletomatodonkey 已提交
230 231
            name="conv1")

232
        self.pool2d_max = MaxPool2D(kernel_size=3, stride=2, padding=1)
littletomatodonkey's avatar
littletomatodonkey 已提交
233 234 235 236 237 238

        self.block_config = block_config

        self.dense_block_func_list = []
        self.transition_func_list = []
        pre_num_channels = num_init_features
W
WuHaobo 已提交
239 240
        num_features = num_init_features
        for i, num_layers in enumerate(block_config):
littletomatodonkey's avatar
littletomatodonkey 已提交
241 242 243 244 245 246 247 248 249 250 251
            self.dense_block_func_list.append(
                self.add_sublayer(
                    "db_conv_{}".format(i + 2),
                    DenseBlock(
                        num_channels=pre_num_channels,
                        num_layers=num_layers,
                        bn_size=bn_size,
                        growth_rate=growth_rate,
                        dropout=dropout,
                        name='conv' + str(i + 2))))

W
WuHaobo 已提交
252
            num_features = num_features + num_layers * growth_rate
littletomatodonkey's avatar
littletomatodonkey 已提交
253 254
            pre_num_channels = num_features

W
WuHaobo 已提交
255
            if i != len(block_config) - 1:
littletomatodonkey's avatar
littletomatodonkey 已提交
256 257 258 259 260 261 262 263
                self.transition_func_list.append(
                    self.add_sublayer(
                        "tr_conv{}_blk".format(i + 2),
                        TransitionLayer(
                            num_channels=pre_num_channels,
                            num_output_features=num_features // 2,
                            name='conv' + str(i + 2) + "_blk")))
                pre_num_channels = num_features // 2
W
WuHaobo 已提交
264
                num_features = num_features // 2
littletomatodonkey's avatar
littletomatodonkey 已提交
265 266 267 268

        self.batch_norm = BatchNorm(
            num_features,
            act="relu",
W
WuHaobo 已提交
269 270 271 272
            param_attr=ParamAttr(name='conv5_blk_bn_scale'),
            bias_attr=ParamAttr(name='conv5_blk_bn_offset'),
            moving_mean_name='conv5_blk_bn_mean',
            moving_variance_name='conv5_blk_bn_variance')
littletomatodonkey's avatar
littletomatodonkey 已提交
273

274
        self.pool2d_avg = AdaptiveAvgPool2D(1)
littletomatodonkey's avatar
littletomatodonkey 已提交
275 276 277 278 279

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

        self.out = Linear(
            num_features,
littletomatodonkey's avatar
littletomatodonkey 已提交
280
            class_num,
littletomatodonkey's avatar
littletomatodonkey 已提交
281 282
            weight_attr=ParamAttr(
                initializer=Uniform(-stdv, stdv), name="fc_weights"),
littletomatodonkey's avatar
littletomatodonkey 已提交
283
            bias_attr=ParamAttr(name="fc_offset"))
W
WuHaobo 已提交
284

littletomatodonkey's avatar
littletomatodonkey 已提交
285 286 287
    def forward(self, input):
        conv = self.conv1_func(input)
        conv = self.pool2d_max(conv)
W
WuHaobo 已提交
288

littletomatodonkey's avatar
littletomatodonkey 已提交
289 290 291 292
        for i, num_layers in enumerate(self.block_config):
            conv = self.dense_block_func_list[i](conv)
            if i != len(self.block_config) - 1:
                conv = self.transition_func_list[i](conv)
W
WuHaobo 已提交
293

littletomatodonkey's avatar
littletomatodonkey 已提交
294 295
        conv = self.batch_norm(conv)
        y = self.pool2d_avg(conv)
L
littletomatodonkey 已提交
296
        y = paddle.flatten(y, start_axis=1, stop_axis=-1)
littletomatodonkey's avatar
littletomatodonkey 已提交
297 298
        y = self.out(y)
        return y
W
WuHaobo 已提交
299

littletomatodonkey's avatar
littletomatodonkey 已提交
300

C
cuicheng01 已提交
301 302 303 304 305 306 307 308 309 310 311 312
def _load_pretrained(pretrained, model, model_url, use_ssld=False):
    if pretrained is False:
        pass
    elif pretrained is True:
        load_dygraph_pretrain_from_url(model, model_url, use_ssld=use_ssld)
    elif isinstance(pretrained, str):
        load_dygraph_pretrain(model, pretrained)
    else:
        raise RuntimeError(
            "pretrained type is not available. Please use `string` or `boolean` type."
        )

littletomatodonkey's avatar
littletomatodonkey 已提交
313

C
cuicheng01 已提交
314 315
def DenseNet121(pretrained=False, use_ssld=False, **kwargs):
    model = DenseNet(layers=121, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
316 317
    _load_pretrained(
        pretrained, model, MODEL_URLS["DenseNet121"], use_ssld=use_ssld)
W
WuHaobo 已提交
318 319 320
    return model


C
cuicheng01 已提交
321 322
def DenseNet161(pretrained=False, use_ssld=False, **kwargs):
    model = DenseNet(layers=161, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
323 324
    _load_pretrained(
        pretrained, model, MODEL_URLS["DenseNet161"], use_ssld=use_ssld)
W
WuHaobo 已提交
325 326 327
    return model


C
cuicheng01 已提交
328 329
def DenseNet169(pretrained=False, use_ssld=False, **kwargs):
    model = DenseNet(layers=169, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
330 331
    _load_pretrained(
        pretrained, model, MODEL_URLS["DenseNet169"], use_ssld=use_ssld)
W
WuHaobo 已提交
332 333 334
    return model


C
cuicheng01 已提交
335 336
def DenseNet201(pretrained=False, use_ssld=False, **kwargs):
    model = DenseNet(layers=201, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
337 338
    _load_pretrained(
        pretrained, model, MODEL_URLS["DenseNet201"], use_ssld=use_ssld)
W
WuHaobo 已提交
339 340 341
    return model


C
cuicheng01 已提交
342 343
def DenseNet264(pretrained=False, use_ssld=False, **kwargs):
    model = DenseNet(layers=264, **kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
344 345
    _load_pretrained(
        pretrained, model, MODEL_URLS["DenseNet264"], use_ssld=use_ssld)
W
WuHaobo 已提交
346
    return model