test_mobile_net.py 21.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

15
import os
16
import sys
17
import tempfile
18
import time
19 20
import unittest

21
import numpy as np
22 23
from predictor_utils import PredictorTools

L
Leo Chen 已提交
24
import paddle
25
from paddle import fluid
26
from paddle.fluid.param_attr import ParamAttr
H
hjyp 已提交
27
from paddle.jit.api import to_static
28
from paddle.jit.translated_layer import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX
29
from paddle.nn import BatchNorm, Linear
30

31 32 33 34 35 36 37 38 39
# Note: Set True to eliminate randomness.
#     1. For one operation, cuDNN has several algorithms,
#        some algorithm results are non-deterministic, like convolution algorithms.
if fluid.is_compiled_with_cuda():
    fluid.set_flags({'FLAGS_cudnn_deterministic': True})

SEED = 2020


40
class ConvBNLayer(paddle.nn.Layer):
41 42 43 44 45 46 47 48 49 50 51 52 53
    def __init__(
        self,
        num_channels,
        filter_size,
        num_filters,
        stride,
        padding,
        channels=None,
        num_groups=1,
        act='relu',
        use_cudnn=True,
        name=None,
    ):
54
        super().__init__()
55

56 57 58 59
        self._conv = paddle.nn.Conv2D(
            in_channels=num_channels,
            out_channels=num_filters,
            kernel_size=filter_size,
60 61 62
            stride=stride,
            padding=padding,
            groups=num_groups,
63
            weight_attr=ParamAttr(
64 65
                initializer=paddle.nn.initializer.KaimingUniform(),
                name=self.full_name() + "_weights",
66 67 68
            ),
            bias_attr=False,
        )
69 70 71 72 73 74 75

        self._batch_norm = BatchNorm(
            num_filters,
            act=act,
            param_attr=ParamAttr(name=self.full_name() + "_bn" + "_scale"),
            bias_attr=ParamAttr(name=self.full_name() + "_bn" + "_offset"),
            moving_mean_name=self.full_name() + "_bn" + '_mean',
76 77
            moving_variance_name=self.full_name() + "_bn" + '_variance',
        )
78 79 80 81 82

    def forward(self, inputs, if_act=False):
        y = self._conv(inputs)
        y = self._batch_norm(y)
        if if_act:
83
            y = paddle.nn.functional.relu6(y)
84 85 86
        return y


87
class DepthwiseSeparable(paddle.nn.Layer):
88 89 90 91 92 93 94 95 96 97
    def __init__(
        self,
        num_channels,
        num_filters1,
        num_filters2,
        num_groups,
        stride,
        scale,
        name=None,
    ):
98
        super().__init__()
99

100 101 102 103 104 105 106 107 108
        self._depthwise_conv = ConvBNLayer(
            num_channels=num_channels,
            num_filters=int(num_filters1 * scale),
            filter_size=3,
            stride=stride,
            padding=1,
            num_groups=int(num_groups * scale),
            use_cudnn=True,
        )
109 110 111 112 113 114

        self._pointwise_conv = ConvBNLayer(
            num_channels=int(num_filters1 * scale),
            filter_size=1,
            num_filters=int(num_filters2 * scale),
            stride=1,
115 116
            padding=0,
        )
117 118 119 120 121 122 123

    def forward(self, inputs):
        y = self._depthwise_conv(inputs)
        y = self._pointwise_conv(y)
        return y


124
class MobileNetV1(paddle.nn.Layer):
125
    def __init__(self, scale=1.0, class_dim=1000):
126
        super().__init__()
127 128 129
        self.scale = scale
        self.dwsl = []

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        self.conv1 = ConvBNLayer(
            num_channels=3,
            filter_size=3,
            channels=3,
            num_filters=int(32 * scale),
            stride=2,
            padding=1,
        )

        dws21 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
                num_channels=int(32 * scale),
                num_filters1=32,
                num_filters2=64,
                num_groups=32,
                stride=1,
                scale=scale,
            ),
            name="conv2_1",
        )
150 151
        self.dwsl.append(dws21)

152 153 154 155 156 157 158 159 160 161 162
        dws22 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
                num_channels=int(64 * scale),
                num_filters1=64,
                num_filters2=128,
                num_groups=64,
                stride=2,
                scale=scale,
            ),
            name="conv2_2",
        )
163 164
        self.dwsl.append(dws22)

165 166 167 168 169 170 171 172 173 174 175
        dws31 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
                num_channels=int(128 * scale),
                num_filters1=128,
                num_filters2=128,
                num_groups=128,
                stride=1,
                scale=scale,
            ),
            name="conv3_1",
        )
176 177
        self.dwsl.append(dws31)

178 179 180 181 182 183 184 185 186 187 188
        dws32 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
                num_channels=int(128 * scale),
                num_filters1=128,
                num_filters2=256,
                num_groups=128,
                stride=2,
                scale=scale,
            ),
            name="conv3_2",
        )
189 190
        self.dwsl.append(dws32)

191 192 193 194 195 196 197 198 199 200 201
        dws41 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
                num_channels=int(256 * scale),
                num_filters1=256,
                num_filters2=256,
                num_groups=256,
                stride=1,
                scale=scale,
            ),
            name="conv4_1",
        )
202 203
        self.dwsl.append(dws41)

204 205 206 207 208 209 210 211 212 213 214
        dws42 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
                num_channels=int(256 * scale),
                num_filters1=256,
                num_filters2=512,
                num_groups=256,
                stride=2,
                scale=scale,
            ),
            name="conv4_2",
        )
215 216 217
        self.dwsl.append(dws42)

        for i in range(5):
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
            tmp = self.add_sublayer(
                sublayer=DepthwiseSeparable(
                    num_channels=int(512 * scale),
                    num_filters1=512,
                    num_filters2=512,
                    num_groups=512,
                    stride=1,
                    scale=scale,
                ),
                name="conv5_" + str(i + 1),
            )
            self.dwsl.append(tmp)

        dws56 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
233 234
                num_channels=int(512 * scale),
                num_filters1=512,
235
                num_filters2=1024,
236
                num_groups=512,
237 238 239 240 241
                stride=2,
                scale=scale,
            ),
            name="conv5_6",
        )
242 243
        self.dwsl.append(dws56)

244 245 246 247 248 249 250 251 252 253 254
        dws6 = self.add_sublayer(
            sublayer=DepthwiseSeparable(
                num_channels=int(1024 * scale),
                num_filters1=1024,
                num_filters2=1024,
                num_groups=1024,
                stride=1,
                scale=scale,
            ),
            name="conv6",
        )
255 256
        self.dwsl.append(dws6)

W
wangzhen38 已提交
257
        self.pool2d_avg = paddle.nn.AdaptiveAvgPool2D(1)
258

259 260 261
        self.out = Linear(
            int(1024 * scale),
            class_dim,
262
            weight_attr=ParamAttr(
263 264
                initializer=paddle.nn.initializer.KaimingUniform(),
                name=self.full_name() + "fc7_weights",
265 266 267
            ),
            bias_attr=ParamAttr(name="fc7_offset"),
        )
268

H
hjyp 已提交
269
    @to_static
270 271 272 273 274
    def forward(self, inputs):
        y = self.conv1(inputs)
        for dws in self.dwsl:
            y = dws(y)
        y = self.pool2d_avg(y)
275
        y = paddle.reshape(y, shape=[-1, 1024])
276 277 278 279
        y = self.out(y)
        return y


280
class InvertedResidualUnit(paddle.nn.Layer):
281
    def __init__(
282 283 284 285 286 287 288 289 290
        self,
        num_channels,
        num_in_filter,
        num_filters,
        stride,
        filter_size,
        padding,
        expansion_factor,
    ):
291
        super().__init__()
292
        num_expfilter = int(round(num_in_filter * expansion_factor))
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
        self._expand_conv = ConvBNLayer(
            num_channels=num_channels,
            num_filters=num_expfilter,
            filter_size=1,
            stride=1,
            padding=0,
            act=None,
            num_groups=1,
        )

        self._bottleneck_conv = ConvBNLayer(
            num_channels=num_expfilter,
            num_filters=num_expfilter,
            filter_size=filter_size,
            stride=stride,
            padding=padding,
            num_groups=num_expfilter,
            act=None,
            use_cudnn=True,
        )

        self._linear_conv = ConvBNLayer(
            num_channels=num_expfilter,
            num_filters=num_filters,
            filter_size=1,
            stride=1,
            padding=0,
            act=None,
            num_groups=1,
        )
323 324 325 326 327 328

    def forward(self, inputs, ifshortcut):
        y = self._expand_conv(inputs, if_act=True)
        y = self._bottleneck_conv(y, if_act=True)
        y = self._linear_conv(y, if_act=False)
        if ifshortcut:
329
            y = paddle.add(inputs, y)
330 331 332
        return y


333
class InvresiBlocks(paddle.nn.Layer):
334
    def __init__(self, in_c, t, c, n, s):
335
        super().__init__()
336

337 338 339 340 341 342 343 344 345
        self._first_block = InvertedResidualUnit(
            num_channels=in_c,
            num_in_filter=in_c,
            num_filters=c,
            stride=s,
            filter_size=3,
            padding=1,
            expansion_factor=t,
        )
346 347 348

        self._inv_blocks = []
        for i in range(1, n):
349 350 351 352 353 354 355 356 357 358 359 360
            tmp = self.add_sublayer(
                sublayer=InvertedResidualUnit(
                    num_channels=c,
                    num_in_filter=c,
                    num_filters=c,
                    stride=1,
                    filter_size=3,
                    padding=1,
                    expansion_factor=t,
                ),
                name=self.full_name() + "_" + str(i + 1),
            )
361 362 363 364 365 366 367 368 369
            self._inv_blocks.append(tmp)

    def forward(self, inputs):
        y = self._first_block(inputs, ifshortcut=False)
        for inv_block in self._inv_blocks:
            y = inv_block(y, ifshortcut=True)
        return y


370
class MobileNetV2(paddle.nn.Layer):
371
    def __init__(self, class_dim=1000, scale=1.0):
372
        super().__init__()
373 374 375 376 377 378 379 380 381 382 383 384 385
        self.scale = scale
        self.class_dim = class_dim

        bottleneck_params_list = [
            (1, 16, 1, 1),
            (6, 24, 2, 2),
            (6, 32, 3, 2),
            (6, 64, 4, 2),
            (6, 96, 3, 1),
            (6, 160, 3, 2),
            (6, 320, 1, 1),
        ]

386 387 388 389 390 391 392 393 394 395 396
        # 1. conv1
        self._conv1 = ConvBNLayer(
            num_channels=3,
            num_filters=int(32 * scale),
            filter_size=3,
            stride=2,
            act=None,
            padding=1,
        )

        # 2. bottleneck sequences
397 398 399 400 401 402
        self._invl = []
        i = 1
        in_c = int(32 * scale)
        for layer_setting in bottleneck_params_list:
            t, c, n, s = layer_setting
            i += 1
403 404 405 406 407 408
            tmp = self.add_sublayer(
                sublayer=InvresiBlocks(
                    in_c=in_c, t=t, c=int(c * scale), n=n, s=s
                ),
                name='conv' + str(i),
            )
409 410 411
            self._invl.append(tmp)
            in_c = int(c * scale)

412
        # 3. last_conv
413
        self._out_c = int(1280 * scale) if scale > 1.0 else 1280
414 415 416 417 418 419 420 421 422 423
        self._conv9 = ConvBNLayer(
            num_channels=in_c,
            num_filters=self._out_c,
            filter_size=1,
            stride=1,
            act=None,
            padding=0,
        )

        # 4. pool
W
wangzhen38 已提交
424
        self._pool2d_avg = paddle.nn.AdaptiveAvgPool2D(1)
425

426
        # 5. fc
427
        tmp_param = ParamAttr(name=self.full_name() + "fc10_weights")
428 429 430
        self._fc = Linear(
            self._out_c,
            class_dim,
431
            weight_attr=tmp_param,
432 433
            bias_attr=ParamAttr(name="fc10_offset"),
        )
434

H
hjyp 已提交
435
    @to_static
436 437 438 439 440 441
    def forward(self, inputs):
        y = self._conv1(inputs, if_act=True)
        for inv in self._invl:
            y = inv(y)
        y = self._conv9(y, if_act=True)
        y = self._pool2d_avg(y)
442
        y = paddle.reshape(y, shape=[-1, self._out_c])
443 444 445 446 447 448 449 450
        y = self._fc(y)
        return y


def create_optimizer(args, parameter_list):
    optimizer = fluid.optimizer.Momentum(
        learning_rate=args.lr,
        momentum=args.momentum_rate,
451
        regularization=paddle.regularizer.L2Decay(args.l2_decay),
452 453
        parameter_list=parameter_list,
    )
454 455 456 457

    return optimizer


458 459 460
def fake_data_reader(batch_size, label_size):
    local_random = np.random.RandomState(SEED)

461 462 463
    def reader():
        batch_data = []
        while True:
464 465
            img = local_random.random_sample([3, 224, 224]).astype('float32')
            label = local_random.randint(0, label_size, [1]).astype('int64')
466 467 468 469 470 471 472 473
            batch_data.append([img, label])
            if len(batch_data) == batch_size:
                yield batch_data
                batch_data = []

    return reader


474
class Args:
475 476 477 478 479 480 481 482 483
    batch_size = 4
    model = "MobileNetV1"
    lr = 0.001
    momentum_rate = 0.99
    l2_decay = 0.1
    num_epochs = 1
    class_dim = 50
    print_step = 1
    train_step = 10
484 485 486 487 488
    place = (
        fluid.CUDAPlace(0)
        if fluid.is_compiled_with_cuda()
        else fluid.CPUPlace()
    )
489 490 491 492 493
    model_save_dir = None
    model_save_prefix = None
    model_filename = None
    params_filename = None
    dy_state_dict_save_path = None
494 495 496


def train_mobilenet(args, to_static):
R
Ryan 已提交
497
    paddle.jit.enable_to_static(to_static)
498
    with fluid.dygraph.guard(args.place):
499 500

        np.random.seed(SEED)
C
cnn 已提交
501
        paddle.seed(SEED)
L
Leo Chen 已提交
502
        paddle.framework.random._manual_program_seed(SEED)
503 504 505 506 507 508 509 510 511

        if args.model == "MobileNetV1":
            net = MobileNetV1(class_dim=args.class_dim, scale=1.0)
        elif args.model == "MobileNetV2":
            net = MobileNetV2(class_dim=args.class_dim, scale=1.0)
        else:
            print(
                "wrong model name, please try model = MobileNetV1 or MobileNetV2"
            )
512
            sys.exit()
513 514 515 516 517 518

        optimizer = create_optimizer(args=args, parameter_list=net.parameters())

        # 3. reader
        train_reader = fake_data_reader(args.batch_size, args.class_dim)
        train_data_loader = fluid.io.DataLoader.from_generator(capacity=16)
519
        train_data_loader.set_sample_list_generator(train_reader)
520 521 522 523 524 525 526 527 528 529 530 531 532

        # 4. train loop
        loss_data = []
        for eop in range(args.num_epochs):
            net.train()
            batch_id = 0
            t_last = 0
            for img, label in train_data_loader():
                t1 = time.time()
                t_start = time.time()
                out = net(img)

                t_end = time.time()
533
                softmax_out = paddle.nn.functional.softmax(out)
534 535 536 537 538
                loss = paddle.nn.functional.cross_entropy(
                    input=softmax_out,
                    label=label,
                    reduction='none',
                    use_softmax=False,
539
                )
540
                avg_loss = paddle.mean(x=loss)
541 542
                acc_top1 = paddle.static.accuracy(input=out, label=label, k=1)
                acc_top5 = paddle.static.accuracy(input=out, label=label, k=5)
543 544 545 546 547 548 549 550 551 552 553
                t_start_back = time.time()

                loss_data.append(avg_loss.numpy())
                avg_loss.backward()
                t_end_back = time.time()
                optimizer.minimize(avg_loss)
                net.clear_gradients()

                t2 = time.time()
                train_batch_elapse = t2 - t1
                if batch_id % args.print_step == 0:
554 555 556 557 558 559 560 561 562 563 564 565 566 567
                    print(
                        "epoch id: %d, batch step: %d,  avg_loss %0.5f acc_top1 %0.5f acc_top5 %0.5f %2.4f sec net_t:%2.4f back_t:%2.4f read_t:%2.4f"
                        % (
                            eop,
                            batch_id,
                            avg_loss.numpy(),
                            acc_top1.numpy(),
                            acc_top5.numpy(),
                            train_batch_elapse,
                            t_end - t_start,
                            t_end_back - t_start_back,
                            t1 - t_last,
                        )
                    )
568 569 570
                batch_id += 1
                t_last = time.time()
                if batch_id > args.train_step:
571
                    if to_static:
572
                        paddle.jit.save(net, args.model_save_prefix)
573
                    else:
574 575 576
                        paddle.save(
                            net.state_dict(),
                            args.dy_state_dict_save_path + '.pdparams',
577
                        )
578 579 580 581 582
                    break

    return np.array(loss_data)


583
def predict_static(args, data):
584
    paddle.enable_static()
585 586
    exe = fluid.Executor(args.place)
    # load inference model
H
hong 已提交
587

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    [
        inference_program,
        feed_target_names,
        fetch_targets,
    ] = fluid.io.load_inference_model(
        args.model_save_dir,
        executor=exe,
        model_filename=args.model_filename,
        params_filename=args.params_filename,
    )

    pred_res = exe.run(
        inference_program,
        feed={feed_target_names[0]: data},
        fetch_list=fetch_targets,
    )
604 605 606 607
    return pred_res[0]


def predict_dygraph(args, data):
R
Ryan 已提交
608
    paddle.jit.enable_to_static(False)
609 610 611 612 613 614
    with fluid.dygraph.guard(args.place):
        if args.model == "MobileNetV1":
            model = MobileNetV1(class_dim=args.class_dim, scale=1.0)
        elif args.model == "MobileNetV2":
            model = MobileNetV2(class_dim=args.class_dim, scale=1.0)
        # load dygraph trained parameters
615
        model_dict = paddle.load(args.dy_state_dict_save_path + '.pdparams')
616 617 618 619 620 621 622 623 624 625
        model.set_dict(model_dict)
        model.eval()

        pred_res = model(fluid.dygraph.to_variable(data))

        return pred_res.numpy()


def predict_dygraph_jit(args, data):
    with fluid.dygraph.guard(args.place):
626
        model = paddle.jit.load(args.model_save_prefix)
627 628 629 630 631 632 633
        model.eval()

        pred_res = model(data)

        return pred_res.numpy()


634
def predict_analysis_inference(args, data):
635 636 637 638
    output = PredictorTools(
        args.model_save_dir, args.model_filename, args.params_filename, [data]
    )
    (out,) = output()
639 640 641
    return out


642 643 644
class TestMobileNet(unittest.TestCase):
    def setUp(self):
        self.args = Args()
645
        self.temp_dir = tempfile.TemporaryDirectory()
646 647 648
        self.args.model_save_dir = os.path.join(
            self.temp_dir.name, "./inference"
        )
649 650 651

    def tearDown(self):
        self.temp_dir.cleanup()
652 653 654

    def train(self, model_name, to_static):
        self.args.model = model_name
655 656 657
        self.args.model_save_prefix = os.path.join(
            self.temp_dir.name, "./inference/" + model_name
        )
658 659
        self.args.model_filename = model_name + INFER_MODEL_SUFFIX
        self.args.params_filename = model_name + INFER_PARAMS_SUFFIX
660
        self.args.dy_state_dict_save_path = os.path.join(
661 662
            self.temp_dir.name, model_name + ".dygraph"
        )
663 664 665 666 667 668
        out = train_mobilenet(self.args, to_static)
        return out

    def assert_same_loss(self, model_name):
        dy_out = self.train(model_name, to_static=False)
        st_out = self.train(model_name, to_static=True)
669 670 671 672
        np.testing.assert_allclose(
            dy_out,
            st_out,
            rtol=1e-05,
673
            err_msg=f'dy_out: {dy_out}, st_out: {st_out}',
674
        )
675

676 677
    def assert_same_predict(self, model_name):
        self.args.model = model_name
678 679 680
        self.args.model_save_prefix = os.path.join(
            self.temp_dir.name, "./inference/" + model_name
        )
681 682
        self.args.model_filename = model_name + INFER_MODEL_SUFFIX
        self.args.params_filename = model_name + INFER_PARAMS_SUFFIX
683
        self.args.dy_state_dict_save_path = os.path.join(
684 685
            self.temp_dir.name, model_name + ".dygraph"
        )
686 687 688 689 690
        local_random = np.random.RandomState(SEED)
        image = local_random.random_sample([1, 3, 224, 224]).astype('float32')
        dy_pre = predict_dygraph(self.args, image)
        st_pre = predict_static(self.args, image)
        dy_jit_pre = predict_dygraph_jit(self.args, image)
691
        predictor_pre = predict_analysis_inference(self.args, image)
692 693 694 695
        np.testing.assert_allclose(
            dy_pre,
            st_pre,
            rtol=1e-05,
696
            err_msg=f'dy_pre:\n {dy_pre}\n, st_pre: \n{st_pre}.',
697
        )
698 699 700 701 702
        np.testing.assert_allclose(
            dy_jit_pre,
            st_pre,
            rtol=1e-05,
            err_msg='dy_jit_pre:\n {}\n, st_pre: \n{}.'.format(
703 704 705
                dy_jit_pre, st_pre
            ),
        )
706 707 708 709 710 711
        np.testing.assert_allclose(
            predictor_pre,
            st_pre,
            rtol=1e-05,
            atol=1e-05,
            err_msg='inference_pred_res:\n {}\n, st_pre: \n{}.'.format(
712 713 714
                predictor_pre, st_pre
            ),
        )
715 716

    def test_mobile_net(self):
717
        # MobileNet-V1
718
        self.assert_same_loss("MobileNetV1")
719
        # MobileNet-V2
720 721
        self.assert_same_loss("MobileNetV2")

722 723 724 725 726 727 728 729
        self.verify_predict()

    def verify_predict(self):
        # MobileNet-V1
        self.assert_same_predict("MobileNetV1")
        # MobileNet-V2
        self.assert_same_predict("MobileNetV2")

730 731

if __name__ == '__main__':
732
    unittest.main()