yolo_fpn.py 14.4 KB
Newer Older
Q
qingqing01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2020 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 paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle import ParamAttr
from ppdet.core.workspace import register, serializable
20
from ..backbones.darknet import ConvBNLayer
W
wangxinxin08 已提交
21
import numpy as np
Q
qingqing01 已提交
22

23 24 25 26
from ..shape_spec import ShapeSpec

__all__ = ['YOLOv3FPN', 'PPYOLOFPN']

Q
qingqing01 已提交
27 28

class YoloDetBlock(nn.Layer):
29
    def __init__(self, ch_in, channel, norm_type, name, data_format='NCHW'):
Q
qingqing01 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
        super(YoloDetBlock, self).__init__()
        self.ch_in = ch_in
        self.channel = channel
        assert channel % 2 == 0, \
            "channel {} cannot be divided by 2".format(channel)
        conv_def = [
            ['conv0', ch_in, channel, 1, '.0.0'],
            ['conv1', channel, channel * 2, 3, '.0.1'],
            ['conv2', channel * 2, channel, 1, '.1.0'],
            ['conv3', channel, channel * 2, 3, '.1.1'],
            ['route', channel * 2, channel, 1, '.2'],
        ]

        self.conv_module = nn.Sequential()
        for idx, (conv_name, ch_in, ch_out, filter_size,
                  post_name) in enumerate(conv_def):
            self.conv_module.add_sublayer(
                conv_name,
                ConvBNLayer(
                    ch_in=ch_in,
                    ch_out=ch_out,
                    filter_size=filter_size,
                    padding=(filter_size - 1) // 2,
                    norm_type=norm_type,
54
                    data_format=data_format,
Q
qingqing01 已提交
55 56 57 58 59 60 61 62
                    name=name + post_name))

        self.tip = ConvBNLayer(
            ch_in=channel,
            ch_out=channel * 2,
            filter_size=3,
            padding=1,
            norm_type=norm_type,
63
            data_format=data_format,
Q
qingqing01 已提交
64 65 66 67 68 69 70 71
            name=name + '.tip')

    def forward(self, inputs):
        route = self.conv_module(inputs)
        tip = self.tip(route)
        return route, tip


W
wangxinxin08 已提交
72
class SPP(nn.Layer):
73 74 75 76 77 78 79 80
    def __init__(self,
                 ch_in,
                 ch_out,
                 k,
                 pool_size,
                 norm_type,
                 name,
                 data_format='NCHW'):
W
wangxinxin08 已提交
81 82 83 84 85 86 87 88 89
        super(SPP, self).__init__()
        self.pool = []
        for size in pool_size:
            pool = self.add_sublayer(
                '{}.pool1'.format(name),
                nn.MaxPool2D(
                    kernel_size=size,
                    stride=1,
                    padding=size // 2,
90
                    data_format=data_format,
W
wangxinxin08 已提交
91 92 93
                    ceil_mode=False))
            self.pool.append(pool)
        self.conv = ConvBNLayer(
94 95 96 97 98 99 100
            ch_in,
            ch_out,
            k,
            padding=k // 2,
            norm_type=norm_type,
            name=name,
            data_format=data_format)
W
wangxinxin08 已提交
101 102 103 104 105 106 107 108 109 110 111

    def forward(self, x):
        outs = [x]
        for pool in self.pool:
            outs.append(pool(x))
        y = paddle.concat(outs, axis=1)
        y = self.conv(y)
        return y


class DropBlock(nn.Layer):
112
    def __init__(self, block_size, keep_prob, name, data_format='NCHW'):
W
wangxinxin08 已提交
113 114 115 116
        super(DropBlock, self).__init__()
        self.block_size = block_size
        self.keep_prob = keep_prob
        self.name = name
117
        self.data_format = data_format
W
wangxinxin08 已提交
118 119 120 121 122 123

    def forward(self, x):
        if not self.training or self.keep_prob == 1:
            return x
        else:
            gamma = (1. - self.keep_prob) / (self.block_size**2)
124 125 126 127 128
            if self.data_format == 'NCHW':
                shape = x.shape[2:]
            else:
                shape = x.shape[1:3]
            for s in shape:
W
wangxinxin08 已提交
129 130 131 132
                gamma *= s / (s - self.block_size + 1)

            matrix = paddle.cast(paddle.rand(x.shape, x.dtype) < gamma, x.dtype)
            mask_inv = F.max_pool2d(
133 134 135 136 137
                matrix,
                self.block_size,
                stride=1,
                padding=self.block_size // 2,
                data_format=self.data_format)
W
wangxinxin08 已提交
138 139 140 141 142 143
            mask = 1. - mask_inv
            y = x * mask * (mask.numel() / mask.sum())
            return y


class CoordConv(nn.Layer):
144 145 146 147 148 149 150 151
    def __init__(self,
                 ch_in,
                 ch_out,
                 filter_size,
                 padding,
                 norm_type,
                 name,
                 data_format='NCHW'):
W
wangxinxin08 已提交
152 153 154 155 156 157 158
        super(CoordConv, self).__init__()
        self.conv = ConvBNLayer(
            ch_in + 2,
            ch_out,
            filter_size=filter_size,
            padding=padding,
            norm_type=norm_type,
159
            data_format=data_format,
W
wangxinxin08 已提交
160
            name=name)
161
        self.data_format = data_format
W
wangxinxin08 已提交
162 163 164

    def forward(self, x):
        b = x.shape[0]
165 166 167 168 169 170
        if self.data_format == 'NCHW':
            h = x.shape[2]
            w = x.shape[3]
        else:
            h = x.shape[1]
            w = x.shape[2]
W
wangxinxin08 已提交
171 172

        gx = paddle.arange(w, dtype='float32') / (w - 1.) * 2.0 - 1.
173 174 175 176
        if self.data_format == 'NCHW':
            gx = gx.reshape([1, 1, 1, w]).expand([b, 1, h, w])
        else:
            gx = gx.reshape([1, 1, w, 1]).expand([b, h, w, 1])
W
wangxinxin08 已提交
177 178 179
        gx.stop_gradient = True

        gy = paddle.arange(h, dtype='float32') / (h - 1.) * 2.0 - 1.
180 181 182 183
        if self.data_format == 'NCHW':
            gy = gy.reshape([1, 1, h, 1]).expand([b, 1, h, w])
        else:
            gy = gy.reshape([1, h, 1, 1]).expand([b, h, w, 1])
W
wangxinxin08 已提交
184 185
        gy.stop_gradient = True

186 187 188 189
        if self.data_format == 'NCHW':
            y = paddle.concat([x, gx, gy], axis=1)
        else:
            y = paddle.concat([x, gx, gy], axis=-1)
W
wangxinxin08 已提交
190 191 192 193 194
        y = self.conv(y)
        return y


class PPYOLODetBlock(nn.Layer):
195
    def __init__(self, cfg, name, data_format='NCHW'):
W
wangxinxin08 已提交
196 197 198
        super(PPYOLODetBlock, self).__init__()
        self.conv_module = nn.Sequential()
        for idx, (conv_name, layer, args, kwargs) in enumerate(cfg[:-1]):
199 200
            kwargs.update(
                name='{}.{}'.format(name, conv_name), data_format=data_format)
W
wangxinxin08 已提交
201 202 203
            self.conv_module.add_sublayer(conv_name, layer(*args, **kwargs))

        conv_name, layer, args, kwargs = cfg[-1]
204 205
        kwargs.update(
            name='{}.{}'.format(name, conv_name), data_format=data_format)
W
wangxinxin08 已提交
206 207 208 209 210 211 212 213
        self.tip = layer(*args, **kwargs)

    def forward(self, inputs):
        route = self.conv_module(inputs)
        tip = self.tip(route)
        return route, tip


Q
qingqing01 已提交
214 215 216
@register
@serializable
class YOLOv3FPN(nn.Layer):
217
    __shared__ = ['norm_type', 'data_format']
Q
qingqing01 已提交
218

219 220 221 222
    def __init__(self,
                 in_channels=[256, 512, 1024],
                 norm_type='bn',
                 data_format='NCHW'):
Q
qingqing01 已提交
223
        super(YOLOv3FPN, self).__init__()
224 225 226 227 228
        assert len(in_channels) > 0, "in_channels length should > 0"
        self.in_channels = in_channels
        self.num_blocks = len(in_channels)

        self._out_channels = []
Q
qingqing01 已提交
229 230
        self.yolo_blocks = []
        self.routes = []
231
        self.data_format = data_format
Q
qingqing01 已提交
232 233
        for i in range(self.num_blocks):
            name = 'yolo_block.{}'.format(i)
234 235 236
            in_channel = in_channels[-i - 1]
            if i > 0:
                in_channel += 512 // (2**i)
Q
qingqing01 已提交
237 238 239
            yolo_block = self.add_sublayer(
                name,
                YoloDetBlock(
240
                    in_channel,
Q
qingqing01 已提交
241 242
                    channel=512 // (2**i),
                    norm_type=norm_type,
243
                    data_format=data_format,
Q
qingqing01 已提交
244 245
                    name=name))
            self.yolo_blocks.append(yolo_block)
246 247
            # tip layer output channel doubled
            self._out_channels.append(1024 // (2**i))
Q
qingqing01 已提交
248 249 250 251 252 253 254 255 256 257 258 259

            if i < self.num_blocks - 1:
                name = 'yolo_transition.{}'.format(i)
                route = self.add_sublayer(
                    name,
                    ConvBNLayer(
                        ch_in=512 // (2**i),
                        ch_out=256 // (2**i),
                        filter_size=1,
                        stride=1,
                        padding=0,
                        norm_type=norm_type,
260
                        data_format=data_format,
Q
qingqing01 已提交
261 262 263 264 265 266 267 268 269
                        name=name))
                self.routes.append(route)

    def forward(self, blocks):
        assert len(blocks) == self.num_blocks
        blocks = blocks[::-1]
        yolo_feats = []
        for i, block in enumerate(blocks):
            if i > 0:
270 271 272 273
                if self.data_format == 'NCHW':
                    block = paddle.concat([route, block], axis=1)
                else:
                    block = paddle.concat([route, block], axis=-1)
Q
qingqing01 已提交
274 275 276 277 278
            route, tip = self.yolo_blocks[i](block)
            yolo_feats.append(tip)

            if i < self.num_blocks - 1:
                route = self.routes[i](route)
279 280
                route = F.interpolate(
                    route, scale_factor=2., data_format=self.data_format)
Q
qingqing01 已提交
281 282

        return yolo_feats
W
wangxinxin08 已提交
283

284 285 286 287 288 289 290 291
    @classmethod
    def from_config(cls, cfg, input_shape):
        return {'in_channels': [i.channels for i in input_shape], }

    @property
    def out_shape(self):
        return [ShapeSpec(channels=c) for c in self._out_channels]

W
wangxinxin08 已提交
292 293 294 295

@register
@serializable
class PPYOLOFPN(nn.Layer):
296
    __shared__ = ['norm_type', 'data_format']
W
wangxinxin08 已提交
297

298 299 300 301 302
    def __init__(self,
                 in_channels=[512, 1024, 2048],
                 norm_type='bn',
                 data_format='NCHW',
                 **kwargs):
W
wangxinxin08 已提交
303
        super(PPYOLOFPN, self).__init__()
304 305 306
        assert len(in_channels) > 0, "in_channels length should > 0"
        self.in_channels = in_channels
        self.num_blocks = len(in_channels)
W
wangxinxin08 已提交
307 308 309 310 311 312 313 314
        # parse kwargs
        self.coord_conv = kwargs.get('coord_conv', False)
        self.drop_block = kwargs.get('drop_block', False)
        if self.drop_block:
            self.block_size = kwargs.get('block_size', 3)
            self.keep_prob = kwargs.get('keep_prob', 0.9)

        self.spp = kwargs.get('spp', False)
W
wangxinxin08 已提交
315
        self.conv_block_num = kwargs.get('conv_block_num', 2)
W
wangxinxin08 已提交
316
        self.data_format = data_format
W
wangxinxin08 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329
        if self.coord_conv:
            ConvLayer = CoordConv
        else:
            ConvLayer = ConvBNLayer

        if self.drop_block:
            dropblock_cfg = [[
                'dropblock', DropBlock, [self.block_size, self.keep_prob],
                dict()
            ]]
        else:
            dropblock_cfg = []

330
        self._out_channels = []
W
wangxinxin08 已提交
331 332
        self.yolo_blocks = []
        self.routes = []
333 334 335
        for i, ch_in in enumerate(self.in_channels[::-1]):
            if i > 0:
                ch_in += 512 // (2**i)
W
wangxinxin08 已提交
336
            channel = 64 * (2**self.num_blocks) // (2**i)
W
wangxinxin08 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
            base_cfg = []
            c_in, c_out = ch_in, channel
            for j in range(self.conv_block_num):
                base_cfg += [
                    [
                        'conv{}'.format(2 * j), ConvLayer, [c_in, c_out, 1],
                        dict(
                            padding=0, norm_type=norm_type)
                    ],
                    [
                        'conv{}'.format(2 * j + 1), ConvBNLayer,
                        [c_out, c_out * 2, 3], dict(
                            padding=1, norm_type=norm_type)
                    ],
                ]
                c_in, c_out = c_out * 2, c_out

            base_cfg += [[
                'route', ConvLayer, [c_in, c_out, 1], dict(
                    padding=0, norm_type=norm_type)
            ], [
                'tip', ConvLayer, [c_out, c_out * 2, 3], dict(
                    padding=1, norm_type=norm_type)
            ]]

            if self.conv_block_num == 2:
                if i == 0:
                    if self.spp:
                        spp_cfg = [[
                            'spp', SPP, [channel * 4, channel, 1], dict(
                                pool_size=[5, 9, 13], norm_type=norm_type)
                        ]]
                    else:
                        spp_cfg = []
                    cfg = base_cfg[0:3] + spp_cfg + base_cfg[
                        3:4] + dropblock_cfg + base_cfg[4:6]
                else:
                    cfg = base_cfg[0:2] + dropblock_cfg + base_cfg[2:6]
            elif self.conv_block_num == 0:
                if self.spp and i == 0:
W
wangxinxin08 已提交
377
                    spp_cfg = [[
W
wangxinxin08 已提交
378 379
                        'spp', SPP, [c_in * 4, c_in, 1], dict(
                            pool_size=[5, 9, 13], norm_type=norm_type)
W
wangxinxin08 已提交
380 381 382
                    ]]
                else:
                    spp_cfg = []
W
wangxinxin08 已提交
383
                cfg = spp_cfg + dropblock_cfg + base_cfg
W
wangxinxin08 已提交
384 385 386
            name = 'yolo_block.{}'.format(i)
            yolo_block = self.add_sublayer(name, PPYOLODetBlock(cfg, name))
            self.yolo_blocks.append(yolo_block)
387
            self._out_channels.append(channel * 2)
W
wangxinxin08 已提交
388 389 390 391 392 393
            if i < self.num_blocks - 1:
                name = 'yolo_transition.{}'.format(i)
                route = self.add_sublayer(
                    name,
                    ConvBNLayer(
                        ch_in=channel,
W
wangxinxin08 已提交
394
                        ch_out=256 // (2**i),
W
wangxinxin08 已提交
395 396 397 398
                        filter_size=1,
                        stride=1,
                        padding=0,
                        norm_type=norm_type,
399
                        data_format=data_format,
W
wangxinxin08 已提交
400 401 402 403 404 405 406 407 408
                        name=name))
                self.routes.append(route)

    def forward(self, blocks):
        assert len(blocks) == self.num_blocks
        blocks = blocks[::-1]
        yolo_feats = []
        for i, block in enumerate(blocks):
            if i > 0:
409 410 411 412
                if self.data_format == 'NCHW':
                    block = paddle.concat([route, block], axis=1)
                else:
                    block = paddle.concat([route, block], axis=-1)
W
wangxinxin08 已提交
413 414 415 416 417
            route, tip = self.yolo_blocks[i](block)
            yolo_feats.append(tip)

            if i < self.num_blocks - 1:
                route = self.routes[i](route)
418 419
                route = F.interpolate(
                    route, scale_factor=2., data_format=self.data_format)
W
wangxinxin08 已提交
420

421 422 423 424 425 426 427 428 429
        return yolo_feats

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

    @property
    def out_shape(self):
        return [ShapeSpec(channels=c) for c in self._out_channels]