pyramidbox.py 17.9 KB
Newer Older
B
baiyfbupt 已提交
1 2 3 4
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

5
import numpy as np
B
baiyf 已提交
6
import six
7 8 9 10
import paddle.fluid as fluid
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.initializer import Xavier
from paddle.fluid.initializer import Constant
11
from paddle.fluid.initializer import Bilinear
12 13 14 15
from paddle.fluid.regularizer import L2Decay


def conv_bn(input, filter, ksize, stride, padding, act='relu', bias_attr=False):
B
Bai Yifan 已提交
16 17
    p_attr = ParamAttr(learning_rate=1., regularizer=L2Decay(0.))
    b_attr = ParamAttr(learning_rate=0., regularizer=L2Decay(0.))
18 19 20 21 22 23 24 25
    conv = fluid.layers.conv2d(
        input=input,
        filter_size=ksize,
        num_filters=filter,
        stride=stride,
        padding=padding,
        act=None,
        bias_attr=bias_attr)
B
Bai Yifan 已提交
26 27 28 29 30 31 32
    return fluid.layers.batch_norm(
        input=conv,
        act=act,
        epsilon=0.001,
        momentum=0.999,
        param_attr=p_attr,
        bias_attr=b_attr)
33 34 35 36 37 38 39 40 41


def conv_block(input, groups, filters, ksizes, strides=None, with_pool=True):
    assert len(filters) == groups
    assert len(ksizes) == groups
    strides = [1] * groups if strides is None else strides
    w_attr = ParamAttr(learning_rate=1., initializer=Xavier())
    b_attr = ParamAttr(learning_rate=2., regularizer=L2Decay(0.))
    conv = input
B
baiyf 已提交
42
    for i in six.moves.xrange(groups):
43 44 45 46 47
        conv = fluid.layers.conv2d(
            input=conv,
            num_filters=filters[i],
            filter_size=ksizes[i],
            stride=strides[i],
B
baiyf 已提交
48
            padding=(ksizes[i] - 1) // 2,
49 50 51 52 53
            param_attr=w_attr,
            bias_attr=b_attr,
            act='relu')
    if with_pool:
        pool = fluid.layers.pool2d(
B
baiyfbupt 已提交
54 55 56 57 58
            input=conv,
            pool_size=2,
            pool_type='max',
            pool_stride=2,
            ceil_mode=True)
Q
qingqing01 已提交
59
        return conv, pool
60 61 62 63 64
    else:
        return conv


class PyramidBox(object):
Q
qingqing01 已提交
65
    def __init__(self,
66 67 68 69 70
                 data_shape=None,
                 image=None,
                 face_box=None,
                 head_box=None,
                 gt_label=None,
71
                 use_transposed_conv2d=True,
Q
qingqing01 已提交
72 73
                 is_infer=False,
                 sub_network=False):
74 75 76
        """
        TODO(qingqing): add comments.
        """
77 78 79
        self.data_shape = data_shape
        self.min_sizes = [16., 32., 64., 128., 256., 512.]
        self.steps = [4., 8., 16., 32., 64., 128.]
80
        self.use_transposed_conv2d = use_transposed_conv2d
81
        self.is_infer = is_infer
82
        self.sub_network = sub_network
83 84 85 86
        self.image = image
        self.face_box = face_box
        self.head_box = head_box
        self.gt_label = gt_label
87

88
        # the base network is VGG with atrous layers
89 90
        if is_infer:
            self._input()
91
        self._vgg()
92 93 94 95
        if sub_network:
            self._low_level_fpn()
            self._cpm_module()
            self._pyramidbox()
Q
qingqing01 已提交
96 97
        else:
            self._vgg_ssd()
98 99 100 101 102

    def _input(self):
        self.image = fluid.layers.data(
            name='image', shape=self.data_shape, dtype='float32')
        if not self.is_infer:
103 104 105 106
            self.face_box = fluid.layers.data(
                name='face_box', shape=[4], dtype='float32', lod_level=1)
            self.head_box = fluid.layers.data(
                name='head_box', shape=[4], dtype='float32', lod_level=1)
107 108 109 110
            self.gt_label = fluid.layers.data(
                name='gt_label', shape=[1], dtype='int32', lod_level=1)

    def _vgg(self):
Q
qingqing01 已提交
111 112
        self.conv1, self.pool1 = conv_block(self.image, 2, [64] * 2, [3] * 2)
        self.conv2, self.pool2 = conv_block(self.pool1, 2, [128] * 2, [3] * 2)
113 114

        #priorbox min_size is 16
Q
qingqing01 已提交
115
        self.conv3, self.pool3 = conv_block(self.pool2, 3, [256] * 3, [3] * 3)
116
        #priorbox min_size is 32
Q
qingqing01 已提交
117
        self.conv4, self.pool4 = conv_block(self.pool3, 3, [512] * 3, [3] * 3)
118
        #priorbox min_size is 64
Q
qingqing01 已提交
119
        self.conv5, self.pool5 = conv_block(self.pool4, 3, [512] * 3, [3] * 3)
120 121

        # fc6 and fc7 in paper, priorbox min_size is 128
Q
qingqing01 已提交
122 123
        self.conv6 = conv_block(
            self.pool5, 2, [1024, 1024], [3, 1], with_pool=False)
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
        # conv6_1 and conv6_2 in paper, priorbox min_size is 256
        self.conv7 = conv_block(
            self.conv6, 2, [256, 512], [1, 3], [1, 2], with_pool=False)
        # conv7_1 and conv7_2 in paper, priorbox mini_size is 512
        self.conv8 = conv_block(
            self.conv7, 2, [128, 256], [1, 3], [1, 2], with_pool=False)

    def _low_level_fpn(self):
        """
        Low-level feature pyramid network.
        """

        def fpn(up_from, up_to):
            ch = up_to.shape[1]
            b_attr = ParamAttr(learning_rate=2., regularizer=L2Decay(0.))
            conv1 = fluid.layers.conv2d(
                up_from, ch, 1, act='relu', bias_attr=b_attr)
141 142 143 144 145 146 147 148 149 150 151 152 153 154
            if self.use_transposed_conv2d:
                w_attr = ParamAttr(
                    learning_rate=0.,
                    regularizer=L2Decay(0.),
                    initializer=Bilinear())
                upsampling = fluid.layers.conv2d_transpose(
                    conv1,
                    ch,
                    output_size=None,
                    filter_size=4,
                    padding=1,
                    stride=2,
                    groups=ch,
                    param_attr=w_attr,
155
                    bias_attr=False,
156
                    use_cudnn=False)
157 158 159 160
            else:
                upsampling = fluid.layers.resize_bilinear(
                    conv1, out_shape=up_to.shape[2:])

161 162
            conv2 = fluid.layers.conv2d(
                up_to, ch, 1, act='relu', bias_attr=b_attr)
B
baiyfbupt 已提交
163 164
            if self.is_infer:
                upsampling = fluid.layers.crop(upsampling, shape=conv2)
165
            # eltwise mul
166
            conv_fuse = upsampling * conv2
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 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 218 219 220 221 222 223 224 225 226 227
            return conv_fuse

        self.lfpn2_on_conv5 = fpn(self.conv6, self.conv5)
        self.lfpn1_on_conv4 = fpn(self.lfpn2_on_conv5, self.conv4)
        self.lfpn0_on_conv3 = fpn(self.lfpn1_on_conv4, self.conv3)

    def _cpm_module(self):
        """
        Context-sensitive Prediction Module 
        """

        def cpm(input):
            # residual
            branch1 = conv_bn(input, 1024, 1, 1, 0, None)
            branch2a = conv_bn(input, 256, 1, 1, 0, act='relu')
            branch2b = conv_bn(branch2a, 256, 3, 1, 1, act='relu')
            branch2c = conv_bn(branch2b, 1024, 1, 1, 0, None)
            sum = branch1 + branch2c
            rescomb = fluid.layers.relu(x=sum)

            # ssh
            b_attr = ParamAttr(learning_rate=2., regularizer=L2Decay(0.))
            ssh_1 = fluid.layers.conv2d(rescomb, 256, 3, 1, 1, bias_attr=b_attr)
            ssh_dimred = fluid.layers.conv2d(
                rescomb, 128, 3, 1, 1, act='relu', bias_attr=b_attr)
            ssh_2 = fluid.layers.conv2d(
                ssh_dimred, 128, 3, 1, 1, bias_attr=b_attr)
            ssh_3a = fluid.layers.conv2d(
                ssh_dimred, 128, 3, 1, 1, act='relu', bias_attr=b_attr)
            ssh_3b = fluid.layers.conv2d(ssh_3a, 128, 3, 1, 1, bias_attr=b_attr)

            ssh_concat = fluid.layers.concat([ssh_1, ssh_2, ssh_3b], axis=1)
            ssh_out = fluid.layers.relu(x=ssh_concat)
            return ssh_out

        self.ssh_conv3 = cpm(self.lfpn0_on_conv3)
        self.ssh_conv4 = cpm(self.lfpn1_on_conv4)
        self.ssh_conv5 = cpm(self.lfpn2_on_conv5)
        self.ssh_conv6 = cpm(self.conv6)
        self.ssh_conv7 = cpm(self.conv7)
        self.ssh_conv8 = cpm(self.conv8)

    def _l2_norm_scale(self, input, init_scale=1.0, channel_shared=False):
        from paddle.fluid.layer_helper import LayerHelper
        helper = LayerHelper("Scale")
        l2_norm = fluid.layers.l2_normalize(
            input, axis=1)  # l2 norm along channel
        shape = [1] if channel_shared else [input.shape[1]]
        scale = helper.create_parameter(
            attr=helper.param_attr,
            shape=shape,
            dtype=input.dtype,
            default_initializer=Constant(init_scale))
        out = fluid.layers.elementwise_mul(
            x=l2_norm, y=scale, axis=-1 if channel_shared else 1)
        return out

    def _pyramidbox(self):
        """
        Get prior-boxes and pyramid-box
        """
Q
qingqing01 已提交
228 229 230 231
        self.ssh_conv3_norm = self._l2_norm_scale(
            self.ssh_conv3, init_scale=10.)
        self.ssh_conv4_norm = self._l2_norm_scale(self.ssh_conv4, init_scale=8.)
        self.ssh_conv5_norm = self._l2_norm_scale(self.ssh_conv5, init_scale=5.)
232 233 234

        def permute_and_reshape(input, last_dim):
            trans = fluid.layers.transpose(input, perm=[0, 2, 3, 1])
235
            compile_shape = [
B
baiyf 已提交
236
                trans.shape[0], np.prod(trans.shape[1:]) // last_dim, last_dim
237
            ]
238 239 240 241
            run_shape = fluid.layers.assign(
                np.array([0, -1, last_dim]).astype("int32"))
            return fluid.layers.reshape(
                trans, shape=compile_shape, actual_shape=run_shape)
242 243 244 245

        face_locs, face_confs = [], []
        head_locs, head_confs = [], []
        boxes, vars = [], []
B
Bai Yifan 已提交
246 247 248 249 250 251 252

        b_attr = ParamAttr(learning_rate=2., regularizer=L2Decay(0.))
        mbox_loc = fluid.layers.conv2d(
            self.ssh_conv3_norm, 8, 3, 1, 1, bias_attr=b_attr)
        face_loc, head_loc = fluid.layers.split(
            mbox_loc, num_or_sections=2, dim=1)
        face_loc = permute_and_reshape(face_loc, 4)
253 254
        if not self.is_infer:
            head_loc = permute_and_reshape(head_loc, 4)
B
Bai Yifan 已提交
255 256 257 258 259 260 261 262 263

        mbox_conf = fluid.layers.conv2d(
            self.ssh_conv3_norm, 8, 3, 1, 1, bias_attr=b_attr)
        face_conf3, face_conf1, head_conf3, head_conf1 = fluid.layers.split(
            mbox_conf, num_or_sections=[3, 1, 3, 1], dim=1)
        face_conf3_maxin = fluid.layers.reduce_max(
            face_conf3, dim=1, keep_dim=True)
        face_conf = fluid.layers.concat([face_conf3_maxin, face_conf1], axis=1)
        face_conf = permute_and_reshape(face_conf, 2)
264 265 266 267 268 269
        if not self.is_infer:
            head_conf3_maxin = fluid.layers.reduce_max(
                head_conf3, dim=1, keep_dim=True)
            head_conf = fluid.layers.concat(
                [head_conf3_maxin, head_conf1], axis=1)
            head_conf = permute_and_reshape(head_conf, 2)
B
Bai Yifan 已提交
270 271 272

        face_locs.append(face_loc)
        face_confs.append(face_conf)
273 274 275
        if not self.is_infer:
            head_locs.append(head_loc)
            head_confs.append(head_conf)
B
Bai Yifan 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

        box, var = fluid.layers.prior_box(
            self.ssh_conv3_norm,
            self.image,
            min_sizes=[16.],
            steps=[4.] * 2,
            aspect_ratios=[1.],
            clip=False,
            flip=True,
            offset=0.5)
        box = fluid.layers.reshape(box, shape=[-1, 4])
        var = fluid.layers.reshape(var, shape=[-1, 4])
        boxes.append(box)
        vars.append(var)

291
        inputs = [
B
Bai Yifan 已提交
292 293
            self.ssh_conv4_norm, self.ssh_conv5_norm, self.ssh_conv6,
            self.ssh_conv7, self.ssh_conv8
294 295 296 297 298 299
        ]
        for i, input in enumerate(inputs):
            mbox_loc = fluid.layers.conv2d(input, 8, 3, 1, 1, bias_attr=b_attr)
            face_loc, head_loc = fluid.layers.split(
                mbox_loc, num_or_sections=2, dim=1)
            face_loc = permute_and_reshape(face_loc, 4)
300 301
            if not self.is_infer:
                head_loc = permute_and_reshape(head_loc, 4)
302 303 304 305 306 307 308 309 310 311

            mbox_conf = fluid.layers.conv2d(input, 6, 3, 1, 1, bias_attr=b_attr)
            face_conf1, face_conf3, head_conf = fluid.layers.split(
                mbox_conf, num_or_sections=[1, 3, 2], dim=1)
            face_conf3_maxin = fluid.layers.reduce_max(
                face_conf3, dim=1, keep_dim=True)
            face_conf = fluid.layers.concat(
                [face_conf1, face_conf3_maxin], axis=1)

            face_conf = permute_and_reshape(face_conf, 2)
312 313
            if not self.is_infer:
                head_conf = permute_and_reshape(head_conf, 2)
314 315 316 317

            face_locs.append(face_loc)
            face_confs.append(face_conf)

318 319 320
            if not self.is_infer:
                head_locs.append(head_loc)
                head_confs.append(head_conf)
321 322 323 324

            box, var = fluid.layers.prior_box(
                input,
                self.image,
B
Bai Yifan 已提交
325 326
                min_sizes=[self.min_sizes[i + 1]],
                steps=[self.steps[i + 1]] * 2,
327
                aspect_ratios=[1.],
328 329
                clip=False,
                flip=True,
330 331 332 333 334 335 336 337 338 339
                offset=0.5)
            box = fluid.layers.reshape(box, shape=[-1, 4])
            var = fluid.layers.reshape(var, shape=[-1, 4])

            boxes.append(box)
            vars.append(var)

        self.face_mbox_loc = fluid.layers.concat(face_locs, axis=1)
        self.face_mbox_conf = fluid.layers.concat(face_confs, axis=1)

340 341 342
        if not self.is_infer:
            self.head_mbox_loc = fluid.layers.concat(head_locs, axis=1)
            self.head_mbox_conf = fluid.layers.concat(head_confs, axis=1)
343 344 345 346

        self.prior_boxes = fluid.layers.concat(boxes)
        self.box_vars = fluid.layers.concat(vars)

Q
qingqing01 已提交
347 348 349 350
    def _vgg_ssd(self):
        self.conv3_norm = self._l2_norm_scale(self.conv3, init_scale=10.)
        self.conv4_norm = self._l2_norm_scale(self.conv4, init_scale=8.)
        self.conv5_norm = self._l2_norm_scale(self.conv5, init_scale=5.)
351

Q
qingqing01 已提交
352 353
        def permute_and_reshape(input, last_dim):
            trans = fluid.layers.transpose(input, perm=[0, 2, 3, 1])
354
            compile_shape = [
B
baiyf 已提交
355
                trans.shape[0], np.prod(trans.shape[1:]) // last_dim, last_dim
Q
qingqing01 已提交
356
            ]
357 358 359 360
            run_shape = fluid.layers.assign(
                np.array([0, -1, last_dim]).astype("int32"))
            return fluid.layers.reshape(
                trans, shape=compile_shape, actual_shape=run_shape)
Q
qingqing01 已提交
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 405 406 407 408 409 410

        locs, confs = [], []
        boxes, vars = [], []
        b_attr = ParamAttr(learning_rate=2., regularizer=L2Decay(0.))

        # conv3
        mbox_loc = fluid.layers.conv2d(
            self.conv3_norm, 4, 3, 1, 1, bias_attr=b_attr)
        loc = permute_and_reshape(mbox_loc, 4)
        mbox_conf = fluid.layers.conv2d(
            self.conv3_norm, 4, 3, 1, 1, bias_attr=b_attr)
        conf1, conf3 = fluid.layers.split(
            mbox_conf, num_or_sections=[1, 3], dim=1)
        conf3_maxin = fluid.layers.reduce_max(conf3, dim=1, keep_dim=True)
        conf = fluid.layers.concat([conf1, conf3_maxin], axis=1)
        conf = permute_and_reshape(conf, 2)
        box, var = fluid.layers.prior_box(
            self.conv3_norm,
            self.image,
            min_sizes=[16.],
            steps=[4, 4],
            aspect_ratios=[1.],
            clip=False,
            flip=True,
            offset=0.5)
        box = fluid.layers.reshape(box, shape=[-1, 4])
        var = fluid.layers.reshape(var, shape=[-1, 4])

        locs.append(loc)
        confs.append(conf)
        boxes.append(box)
        vars.append(var)

        min_sizes = [32., 64., 128., 256., 512.]
        steps = [8., 16., 32., 64., 128.]
        inputs = [
            self.conv4_norm, self.conv5_norm, self.conv6, self.conv7, self.conv8
        ]
        for i, input in enumerate(inputs):
            mbox_loc = fluid.layers.conv2d(input, 4, 3, 1, 1, bias_attr=b_attr)
            loc = permute_and_reshape(mbox_loc, 4)

            mbox_conf = fluid.layers.conv2d(input, 2, 3, 1, 1, bias_attr=b_attr)
            conf = permute_and_reshape(mbox_conf, 2)
            box, var = fluid.layers.prior_box(
                input,
                self.image,
                min_sizes=[min_sizes[i]],
                steps=[steps[i]] * 2,
                aspect_ratios=[1.],
411 412
                clip=False,
                flip=True,
Q
qingqing01 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425
                offset=0.5)
            box = fluid.layers.reshape(box, shape=[-1, 4])
            var = fluid.layers.reshape(var, shape=[-1, 4])

            locs.append(loc)
            confs.append(conf)
            boxes.append(box)
            vars.append(var)

        self.face_mbox_loc = fluid.layers.concat(locs, axis=1)
        self.face_mbox_conf = fluid.layers.concat(confs, axis=1)
        self.prior_boxes = fluid.layers.concat(boxes)
        self.box_vars = fluid.layers.concat(vars)
Q
qingqing01 已提交
426 427 428 429 430 431 432 433 434 435 436

    def vgg_ssd_loss(self):
        loss = fluid.layers.ssd_loss(
            self.face_mbox_loc,
            self.face_mbox_conf,
            self.face_box,
            self.gt_label,
            self.prior_boxes,
            self.box_vars,
            overlap_threshold=0.35,
            neg_overlap=0.35)
437
        loss = fluid.layers.reduce_sum(loss)
438
        loss.persistable = True
439 440
        return loss

441 442
    def train(self):
        face_loss = fluid.layers.ssd_loss(
Q
qingqing01 已提交
443 444 445 446 447 448 449 450
            self.face_mbox_loc,
            self.face_mbox_conf,
            self.face_box,
            self.gt_label,
            self.prior_boxes,
            self.box_vars,
            overlap_threshold=0.35,
            neg_overlap=0.35)
451
        face_loss.persistable = True
452
        head_loss = fluid.layers.ssd_loss(
Q
qingqing01 已提交
453 454 455 456 457 458 459 460
            self.head_mbox_loc,
            self.head_mbox_conf,
            self.head_box,
            self.gt_label,
            self.prior_boxes,
            self.box_vars,
            overlap_threshold=0.35,
            neg_overlap=0.35)
461
        head_loss.persistable = True
462
        face_loss = fluid.layers.reduce_sum(face_loss)
463
        face_loss.persistable = True
464
        head_loss = fluid.layers.reduce_sum(head_loss)
465
        head_loss.persistable = True
466
        total_loss = face_loss + head_loss
467
        total_loss.persistable = True
468
        return face_loss, head_loss, total_loss
469

B
baiyfbupt 已提交
470 471 472 473 474
    def infer(self, main_program=None):
        if main_program is None:
            test_program = fluid.default_main_program().clone(for_test=True)
        else:
            test_program = main_program.clone(for_test=True)
475 476 477 478 479 480
        with fluid.program_guard(test_program):
            face_nmsed_out = fluid.layers.detection_output(
                self.face_mbox_loc,
                self.face_mbox_conf,
                self.prior_boxes,
                self.box_vars,
481 482 483
                nms_threshold=0.3,
                nms_top_k=5000,
                keep_top_k=750,
Q
qingqing01 已提交
484
                score_threshold=0.01)
Q
qingqing01 已提交
485
        return test_program, face_nmsed_out