darknet.py 7.0 KB
Newer Older
C
cuicheng01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# copyright (c) 2021 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.

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

17
import paddle
littletomatodonkey's avatar
littletomatodonkey 已提交
18 19 20
from paddle import ParamAttr
import paddle.nn as nn
import paddle.nn.functional as F
21 22
from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
littletomatodonkey's avatar
littletomatodonkey 已提交
23
from paddle.nn.initializer import Uniform
W
WuHaobo 已提交
24
import math
25

C
cuicheng01 已提交
26 27
from ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url

littletomatodonkey's avatar
littletomatodonkey 已提交
28 29 30 31
MODEL_URLS = {
    "DarkNet53":
    "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/DarkNet53_pretrained.pdparams"
}
W
WuHaobo 已提交
32

C
cuicheng01 已提交
33
__all__ = list(MODEL_URLS.keys())
W
WuHaobo 已提交
34

littletomatodonkey's avatar
littletomatodonkey 已提交
35

littletomatodonkey's avatar
littletomatodonkey 已提交
36
class ConvBNLayer(nn.Layer):
37 38 39 40 41 42 43 44 45
    def __init__(self,
                 input_channels,
                 output_channels,
                 filter_size,
                 stride,
                 padding,
                 name=None):
        super(ConvBNLayer, self).__init__()

46
        self._conv = Conv2D(
littletomatodonkey's avatar
littletomatodonkey 已提交
47 48 49
            in_channels=input_channels,
            out_channels=output_channels,
            kernel_size=filter_size,
W
WuHaobo 已提交
50 51
            stride=stride,
            padding=padding,
littletomatodonkey's avatar
littletomatodonkey 已提交
52
            weight_attr=ParamAttr(name=name + ".conv.weights"),
W
WuHaobo 已提交
53 54 55
            bias_attr=False)

        bn_name = name + ".bn"
56 57 58 59 60 61 62 63 64 65 66 67 68 69
        self._bn = BatchNorm(
            num_channels=output_channels,
            act="relu",
            param_attr=ParamAttr(name=bn_name + ".scale"),
            bias_attr=ParamAttr(name=bn_name + ".offset"),
            moving_mean_name=bn_name + ".mean",
            moving_variance_name=bn_name + ".var")

    def forward(self, inputs):
        x = self._conv(inputs)
        x = self._bn(x)
        return x


littletomatodonkey's avatar
littletomatodonkey 已提交
70
class BasicBlock(nn.Layer):
71
    def __init__(self, input_channels, output_channels, name=None):
W
wqz960 已提交
72
        super(BasicBlock, self).__init__()
73 74 75 76 77 78 79 80 81

        self._conv1 = ConvBNLayer(
            input_channels, output_channels, 1, 1, 0, name=name + ".0")
        self._conv2 = ConvBNLayer(
            output_channels, output_channels * 2, 3, 1, 1, name=name + ".1")

    def forward(self, inputs):
        x = self._conv1(inputs)
        x = self._conv2(x)
82
        return paddle.add(x=inputs, y=x)
83 84


littletomatodonkey's avatar
littletomatodonkey 已提交
85
class DarkNet(nn.Layer):
littletomatodonkey's avatar
littletomatodonkey 已提交
86
    def __init__(self, class_num=1000):
W
wqz960 已提交
87
        super(DarkNet, self).__init__()
88 89 90 91 92 93

        self.stages = [1, 2, 8, 8, 4]
        self._conv1 = ConvBNLayer(3, 32, 3, 1, 1, name="yolo_input")
        self._conv2 = ConvBNLayer(
            32, 64, 3, 2, 1, name="yolo_input.downsample")

W
wqz960 已提交
94
        self._basic_block_01 = BasicBlock(64, 32, name="stage.0.0")
95 96 97
        self._downsample_0 = ConvBNLayer(
            64, 128, 3, 2, 1, name="stage.0.downsample")

W
wqz960 已提交
98 99
        self._basic_block_11 = BasicBlock(128, 64, name="stage.1.0")
        self._basic_block_12 = BasicBlock(128, 64, name="stage.1.1")
100 101 102
        self._downsample_1 = ConvBNLayer(
            128, 256, 3, 2, 1, name="stage.1.downsample")

W
wqz960 已提交
103 104 105 106 107 108 109 110
        self._basic_block_21 = BasicBlock(256, 128, name="stage.2.0")
        self._basic_block_22 = BasicBlock(256, 128, name="stage.2.1")
        self._basic_block_23 = BasicBlock(256, 128, name="stage.2.2")
        self._basic_block_24 = BasicBlock(256, 128, name="stage.2.3")
        self._basic_block_25 = BasicBlock(256, 128, name="stage.2.4")
        self._basic_block_26 = BasicBlock(256, 128, name="stage.2.5")
        self._basic_block_27 = BasicBlock(256, 128, name="stage.2.6")
        self._basic_block_28 = BasicBlock(256, 128, name="stage.2.7")
111 112 113
        self._downsample_2 = ConvBNLayer(
            256, 512, 3, 2, 1, name="stage.2.downsample")

W
wqz960 已提交
114 115 116 117 118 119 120 121
        self._basic_block_31 = BasicBlock(512, 256, name="stage.3.0")
        self._basic_block_32 = BasicBlock(512, 256, name="stage.3.1")
        self._basic_block_33 = BasicBlock(512, 256, name="stage.3.2")
        self._basic_block_34 = BasicBlock(512, 256, name="stage.3.3")
        self._basic_block_35 = BasicBlock(512, 256, name="stage.3.4")
        self._basic_block_36 = BasicBlock(512, 256, name="stage.3.5")
        self._basic_block_37 = BasicBlock(512, 256, name="stage.3.6")
        self._basic_block_38 = BasicBlock(512, 256, name="stage.3.7")
122 123 124
        self._downsample_3 = ConvBNLayer(
            512, 1024, 3, 2, 1, name="stage.3.downsample")

W
wqz960 已提交
125 126 127 128
        self._basic_block_41 = BasicBlock(1024, 512, name="stage.4.0")
        self._basic_block_42 = BasicBlock(1024, 512, name="stage.4.1")
        self._basic_block_43 = BasicBlock(1024, 512, name="stage.4.2")
        self._basic_block_44 = BasicBlock(1024, 512, name="stage.4.3")
129

130
        self._pool = AdaptiveAvgPool2D(1)
131 132 133

        stdv = 1.0 / math.sqrt(1024.0)
        self._out = Linear(
littletomatodonkey's avatar
littletomatodonkey 已提交
134
            1024,
littletomatodonkey's avatar
littletomatodonkey 已提交
135
            class_num,
littletomatodonkey's avatar
littletomatodonkey 已提交
136 137
            weight_attr=ParamAttr(
                name="fc_weights", initializer=Uniform(-stdv, stdv)),
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
            bias_attr=ParamAttr(name="fc_offset"))

    def forward(self, inputs):
        x = self._conv1(inputs)
        x = self._conv2(x)

        x = self._basic_block_01(x)
        x = self._downsample_0(x)

        x = self._basic_block_11(x)
        x = self._basic_block_12(x)
        x = self._downsample_1(x)

        x = self._basic_block_21(x)
        x = self._basic_block_22(x)
        x = self._basic_block_23(x)
        x = self._basic_block_24(x)
        x = self._basic_block_25(x)
        x = self._basic_block_26(x)
        x = self._basic_block_27(x)
        x = self._basic_block_28(x)
        x = self._downsample_2(x)

        x = self._basic_block_31(x)
        x = self._basic_block_32(x)
        x = self._basic_block_33(x)
        x = self._basic_block_34(x)
        x = self._basic_block_35(x)
        x = self._basic_block_36(x)
        x = self._basic_block_37(x)
        x = self._basic_block_38(x)
        x = self._downsample_3(x)

        x = self._basic_block_41(x)
        x = self._basic_block_42(x)
        x = self._basic_block_43(x)
        x = self._basic_block_44(x)

        x = self._pool(x)
littletomatodonkey's avatar
littletomatodonkey 已提交
177
        x = paddle.squeeze(x, axis=[2, 3])
178 179 180
        x = self._out(x)
        return x

littletomatodonkey's avatar
littletomatodonkey 已提交
181

C
cuicheng01 已提交
182 183 184 185 186 187 188 189 190 191 192
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 已提交
193 194


C
cuicheng01 已提交
195 196
def DarkNet53(pretrained=False, use_ssld=False, **kwargs):
    model = DarkNet(**kwargs)
littletomatodonkey's avatar
littletomatodonkey 已提交
197 198
    _load_pretrained(
        pretrained, model, MODEL_URLS["DarkNet53"], use_ssld=use_ssld)
littletomatodonkey's avatar
littletomatodonkey 已提交
199
    return model