centernet_fpn.py 12.3 KB
Newer Older
F
FlyingQianMM 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import numpy as np
import math
import paddle
import paddle.nn as nn
W
wangguanzhong 已提交
19 20
from paddle import ParamAttr
from paddle.nn.initializer import Uniform
F
Feng Ni 已提交
21
import paddle.nn.functional as F
F
FlyingQianMM 已提交
22 23
from ppdet.core.workspace import register, serializable
from ppdet.modeling.layers import ConvNormLayer
F
Feng Ni 已提交
24
from ppdet.modeling.backbones.hardnet import ConvLayer, HarDBlock
F
FlyingQianMM 已提交
25 26
from ..shape_spec import ShapeSpec

F
Feng Ni 已提交
27 28
__all__ = ['CenterNetDLAFPN', 'CenterNetHarDNetFPN']

F
FlyingQianMM 已提交
29 30

def fill_up_weights(up):
W
wangguanzhong 已提交
31
    weight = up.weight.numpy()
F
FlyingQianMM 已提交
32 33 34 35 36 37 38 39
    f = math.ceil(weight.shape[2] / 2)
    c = (2 * f - 1 - f % 2) / (2. * f)
    for i in range(weight.shape[2]):
        for j in range(weight.shape[3]):
            weight[0, 0, i, j] = \
                (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c))
    for c in range(1, weight.shape[0]):
        weight[c, 0, :, :] = weight[0, 0, :, :]
W
wangguanzhong 已提交
40
    up.weight.set_value(weight)
F
FlyingQianMM 已提交
41 42 43 44 45 46 47 48


class IDAUp(nn.Layer):
    def __init__(self, ch_ins, ch_out, up_strides, dcn_v2=True):
        super(IDAUp, self).__init__()
        for i in range(1, len(ch_ins)):
            ch_in = ch_ins[i]
            up_s = int(up_strides[i])
W
wangguanzhong 已提交
49 50
            fan_in = ch_in * 3 * 3
            stdv = 1. / math.sqrt(fan_in)
F
FlyingQianMM 已提交
51 52 53 54 55 56 57 58 59 60
            proj = nn.Sequential(
                ConvNormLayer(
                    ch_in,
                    ch_out,
                    filter_size=3,
                    stride=1,
                    use_dcn=dcn_v2,
                    bias_on=dcn_v2,
                    norm_decay=None,
                    dcn_lr_scale=1.,
W
wangguanzhong 已提交
61 62
                    dcn_regularizer=None,
                    initializer=Uniform(-stdv, stdv)),
F
FlyingQianMM 已提交
63 64 65 66 67 68 69 70 71 72 73
                nn.ReLU())
            node = nn.Sequential(
                ConvNormLayer(
                    ch_out,
                    ch_out,
                    filter_size=3,
                    stride=1,
                    use_dcn=dcn_v2,
                    bias_on=dcn_v2,
                    norm_decay=None,
                    dcn_lr_scale=1.,
W
wangguanzhong 已提交
74 75
                    dcn_regularizer=None,
                    initializer=Uniform(-stdv, stdv)),
F
FlyingQianMM 已提交
76 77
                nn.ReLU())

W
wangguanzhong 已提交
78 79 80
            kernel_size = up_s * 2
            fan_in = ch_out * kernel_size * kernel_size
            stdv = 1. / math.sqrt(fan_in)
F
FlyingQianMM 已提交
81 82 83 84 85 86 87
            up = nn.Conv2DTranspose(
                ch_out,
                ch_out,
                kernel_size=up_s * 2,
                stride=up_s,
                padding=up_s // 2,
                groups=ch_out,
W
wangguanzhong 已提交
88
                weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)),
F
FlyingQianMM 已提交
89
                bias_attr=False)
W
wangguanzhong 已提交
90
            fill_up_weights(up)
F
FlyingQianMM 已提交
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 142 143 144 145 146 147 148
            setattr(self, 'proj_' + str(i), proj)
            setattr(self, 'up_' + str(i), up)
            setattr(self, 'node_' + str(i), node)

    def forward(self, inputs, start_level, end_level):
        for i in range(start_level + 1, end_level):
            upsample = getattr(self, 'up_' + str(i - start_level))
            project = getattr(self, 'proj_' + str(i - start_level))

            inputs[i] = project(inputs[i])
            inputs[i] = upsample(inputs[i])
            node = getattr(self, 'node_' + str(i - start_level))
            inputs[i] = node(paddle.add(inputs[i], inputs[i - 1]))


class DLAUp(nn.Layer):
    def __init__(self, start_level, channels, scales, ch_in=None, dcn_v2=True):
        super(DLAUp, self).__init__()
        self.start_level = start_level
        if ch_in is None:
            ch_in = channels
        self.channels = channels
        channels = list(channels)
        scales = np.array(scales, dtype=int)
        for i in range(len(channels) - 1):
            j = -i - 2
            setattr(
                self,
                'ida_{}'.format(i),
                IDAUp(
                    ch_in[j:],
                    channels[j],
                    scales[j:] // scales[j],
                    dcn_v2=dcn_v2))
            scales[j + 1:] = scales[j]
            ch_in[j + 1:] = [channels[j] for _ in channels[j + 1:]]

    def forward(self, inputs):
        out = [inputs[-1]]  # start with 32
        for i in range(len(inputs) - self.start_level - 1):
            ida = getattr(self, 'ida_{}'.format(i))
            ida(inputs, len(inputs) - i - 2, len(inputs))
            out.insert(0, inputs[-1])
        return out


@register
@serializable
class CenterNetDLAFPN(nn.Layer):
    """
    Args:
        in_channels (list): number of input feature channels from backbone.
            [16, 32, 64, 128, 256, 512] by default, means the channels of DLA-34
        down_ratio (int): the down ratio from images to heatmap, 4 by default
        last_level (int): the last level of input feature fed into the upsamplng block
        out_channel (int): the channel of the output feature, 0 by default means
            the channel of the input feature whose down ratio is `down_ratio`
        dcn_v2 (bool): whether use the DCNv2, true by default
W
wangguanzhong 已提交
149 150 151
        first_level (int|None): the first level of input feature fed into the upsamplng block.
            if None, the first level stands for logs(down_ratio)
        
F
FlyingQianMM 已提交
152 153 154 155 156 157 158
    """

    def __init__(self,
                 in_channels,
                 down_ratio=4,
                 last_level=5,
                 out_channel=0,
W
wangguanzhong 已提交
159 160
                 dcn_v2=True,
                 first_level=None):
F
FlyingQianMM 已提交
161
        super(CenterNetDLAFPN, self).__init__()
F
Feng Ni 已提交
162
        self.first_level = int(np.log2(
W
wangguanzhong 已提交
163 164 165
            down_ratio)) if first_level is None else first_level
        assert self.first_level >= 0, "first level in CenterNetDLAFPN should be greater or equal to 0, but received {}".format(
            self.first_level)
F
FlyingQianMM 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
        self.down_ratio = down_ratio
        self.last_level = last_level
        scales = [2**i for i in range(len(in_channels[self.first_level:]))]
        self.dla_up = DLAUp(
            self.first_level,
            in_channels[self.first_level:],
            scales,
            dcn_v2=dcn_v2)
        self.out_channel = out_channel
        if out_channel == 0:
            self.out_channel = in_channels[self.first_level]
        self.ida_up = IDAUp(
            in_channels[self.first_level:self.last_level],
            self.out_channel,
            [2**i for i in range(self.last_level - self.first_level)],
            dcn_v2=dcn_v2)

    @classmethod
    def from_config(cls, cfg, input_shape):
        return {'in_channels': [i.channels for i in input_shape]}

    def forward(self, body_feats):
F
Feng Ni 已提交
188

F
FlyingQianMM 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201
        dla_up_feats = self.dla_up(body_feats)

        ida_up_feats = []
        for i in range(self.last_level - self.first_level):
            ida_up_feats.append(dla_up_feats[i].clone())

        self.ida_up(ida_up_feats, 0, len(ida_up_feats))

        return ida_up_feats[-1]

    @property
    def out_shape(self):
        return [ShapeSpec(channels=self.out_channel, stride=self.down_ratio)]
F
Feng Ni 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224


class TransitionUp(nn.Layer):
    def __init__(self, in_channels, out_channels):
        super().__init__()

    def forward(self, x, skip, concat=True):
        w, h = skip.shape[2], skip.shape[3]
        out = F.interpolate(x, size=(w, h), mode="bilinear", align_corners=True)
        if concat:
            out = paddle.concat([out, skip], 1)
        return out


@register
@serializable
class CenterNetHarDNetFPN(nn.Layer):
    """
    Args:
        in_channels (list): number of input feature channels from backbone.
            [96, 214, 458, 784] by default, means the channels of HarDNet85
        num_layers (int): HarDNet laters, 85 by default
        down_ratio (int): the down ratio from images to heatmap, 4 by default
W
wangguanzhong 已提交
225 226 227
        first_level (int|None): the first level of input feature fed into the upsamplng block.
            if None, the first level stands for logs(down_ratio) - 1

F
Feng Ni 已提交
228 229 230 231 232 233 234 235 236
        last_level (int): the last level of input feature fed into the upsamplng block
        out_channel (int): the channel of the output feature, 0 by default means
            the channel of the input feature whose down ratio is `down_ratio`
    """

    def __init__(self,
                 in_channels,
                 num_layers=85,
                 down_ratio=4,
W
wangguanzhong 已提交
237
                 first_level=None,
F
Feng Ni 已提交
238 239 240 241
                 last_level=4,
                 out_channel=0):
        super(CenterNetHarDNetFPN, self).__init__()
        self.first_level = int(np.log2(
W
wangguanzhong 已提交
242 243 244
            down_ratio)) - 1 if first_level is None else first_level
        assert self.first_level >= 0, "first level in CenterNetDLAFPN should be greater or equal to 0, but received {}".format(
            self.first_level)
F
Feng Ni 已提交
245 246 247 248
        self.down_ratio = down_ratio
        self.last_level = last_level
        self.last_pool = nn.AvgPool2D(kernel_size=2, stride=2)

W
wangguanzhong 已提交
249 250
        assert num_layers in [68, 85], "HarDNet-{} not support.".format(
            num_layers)
F
Feng Ni 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
        if num_layers == 85:
            self.last_proj = ConvLayer(784, 256, kernel_size=1)
            self.last_blk = HarDBlock(768, 80, 1.7, 8)
            self.skip_nodes = [1, 3, 8, 13]
            self.SC = [32, 32, 0]
            gr = [64, 48, 28]
            layers = [8, 8, 4]
            ch_list2 = [224 + self.SC[0], 160 + self.SC[1], 96 + self.SC[2]]
            channels = [96, 214, 458, 784]
            self.skip_lv = 3

        elif num_layers == 68:
            self.last_proj = ConvLayer(654, 192, kernel_size=1)
            self.last_blk = HarDBlock(576, 72, 1.7, 8)
            self.skip_nodes = [1, 3, 8, 11]
            self.SC = [32, 32, 0]
            gr = [48, 32, 20]
            layers = [8, 8, 4]
            ch_list2 = [224 + self.SC[0], 96 + self.SC[1], 64 + self.SC[2]]
            channels = [64, 124, 328, 654]
            self.skip_lv = 2

        self.transUpBlocks = nn.LayerList([])
        self.denseBlocksUp = nn.LayerList([])
        self.conv1x1_up = nn.LayerList([])
        self.avg9x9 = nn.AvgPool2D(kernel_size=(9, 9), stride=1, padding=(4, 4))
        prev_ch = self.last_blk.get_out_ch()

        for i in range(3):
            skip_ch = channels[3 - i]
            self.transUpBlocks.append(TransitionUp(prev_ch, prev_ch))
            if i < self.skip_lv:
                cur_ch = prev_ch + skip_ch
            else:
                cur_ch = prev_ch
            self.conv1x1_up.append(
                ConvLayer(
                    cur_ch, ch_list2[i], kernel_size=1))
            cur_ch = ch_list2[i]
            cur_ch -= self.SC[i]
            cur_ch *= 3

            blk = HarDBlock(cur_ch, gr[i], 1.7, layers[i])
            self.denseBlocksUp.append(blk)
            prev_ch = blk.get_out_ch()

        prev_ch += self.SC[0] + self.SC[1] + self.SC[2]
        self.out_channel = prev_ch

    @classmethod
    def from_config(cls, cfg, input_shape):
        return {'in_channels': [i.channels for i in input_shape]}

    def forward(self, body_feats):
        x = body_feats[-1]
        x_sc = []
        x = self.last_proj(x)
        x = self.last_pool(x)
        x2 = self.avg9x9(x)
        x3 = x / (x.sum((2, 3), keepdim=True) + 0.1)
        x = paddle.concat([x, x2, x3], 1)
        x = self.last_blk(x)

        for i in range(3):
            skip_x = body_feats[3 - i]
            x = self.transUpBlocks[i](x, skip_x, (i < self.skip_lv))
            x = self.conv1x1_up[i](x)
            if self.SC[i] > 0:
                end = x.shape[1]
                x_sc.append(x[:, end - self.SC[i]:, :, :])
                x = x[:, :end - self.SC[i], :, :]
            x2 = self.avg9x9(x)
            x3 = x / (x.sum((2, 3), keepdim=True) + 0.1)
            x = paddle.concat([x, x2, x3], 1)
            x = self.denseBlocksUp[i](x)

        scs = [x]
        for i in range(3):
            if self.SC[i] > 0:
                scs.insert(
                    0,
                    F.interpolate(
                        x_sc[i],
                        size=(x.shape[2], x.shape[3]),
                        mode="bilinear",
                        align_corners=True))
        neck_feat = paddle.concat(scs, 1)
        return neck_feat

    @property
    def out_shape(self):
        return [ShapeSpec(channels=self.out_channel, stride=self.down_ratio)]