test_post_training_quantization_mnist.py 22.3 KB
Newer Older
1
#   copyright (c) 2022 paddlepaddle authors. all rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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 os
import random
16
import sys
17
import tempfile
18 19 20
import time
import unittest

21
import numpy as np
22

23
import paddle
24 25
from paddle.dataset.common import md5file
from paddle.static.quantization import PostTrainingQuantization
26

P
pangyoki 已提交
27 28
paddle.enable_static()

29 30 31 32 33 34
random.seed(0)
np.random.seed(0)


class TestPostTrainingQuantization(unittest.TestCase):
    def setUp(self):
35
        self.root_path = tempfile.TemporaryDirectory()
36 37 38
        self.int8_model_path = os.path.join(
            self.root_path.name, "post_training_quantization"
        )
39 40 41
        self.download_path = f'download_model_{time.time()}'
        self.cache_folder = os.path.join(
            self.root_path.name, self.download_path
42
        )
43 44
        try:
            os.system("mkdir -p " + self.int8_model_path)
45
            os.system("mkdir -p " + self.cache_folder)
46
        except Exception as e:
47 48 49 50 51
            print(
                "Failed to create {} due to {}".format(
                    self.int8_model_path, str(e)
                )
            )
52 53 54
            sys.exit(-1)

    def tearDown(self):
55
        self.root_path.cleanup()
56 57 58

    def cache_unzipping(self, target_folder, zip_path):
        if not os.path.exists(target_folder):
59
            cmd = 'mkdir {0} && tar xf {1} -C {0}'.format(
60 61
                target_folder, zip_path
            )
62 63
            os.system(cmd)

64 65 66
    def download(self, url, dirname, md5sum, save_name=None):
        import shutil

67
        import httpx
68 69 70 71 72 73 74 75 76 77 78 79

        filename = os.path.join(
            dirname, url.split('/')[-1] if save_name is None else save_name
        )

        if os.path.exists(filename) and md5file(filename) == md5sum:
            return filename

        retry = 0
        retry_limit = 3
        while not (os.path.exists(filename) and md5file(filename) == md5sum):
            if os.path.exists(filename):
80
                sys.stderr.write(f"file {md5file(filename)}  md5 {md5sum}\n")
81 82 83 84
            if retry < retry_limit:
                retry += 1
            else:
                raise RuntimeError(
85
                    "Cannot download {} within retry limit {}".format(
86 87 88 89
                        url, retry_limit
                    )
                )
            sys.stderr.write(
90
                f"Cache file {filename} not found, downloading {url} \n"
91 92 93
            )
            sys.stderr.write("Begin to download\n")
            try:
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
                with httpx.stream("GET", url) as r:
                    total_length = r.headers.get('content-length')

                    if total_length is None:
                        with open(filename, 'wb') as f:
                            shutil.copyfileobj(r.raw, f)
                    else:
                        with open(filename, 'wb') as f:
                            chunk_size = 4096
                            total_length = int(total_length)
                            total_iter = total_length / chunk_size + 1
                            log_interval = (
                                total_iter // 20 if total_iter > 20 else 1
                            )
                            log_index = 0
                            bar = paddle.hapi.progressbar.ProgressBar(
                                total_iter, name='item'
                            )
                            for data in r.iter_bytes(chunk_size=chunk_size):
                                f.write(data)
                                log_index += 1
                                bar.update(log_index, {})
                                if log_index % log_interval == 0:
                                    bar.update(log_index)
118 119 120 121 122 123 124 125

            except Exception as e:
                # re-try
                continue
        sys.stderr.write("\nDownload finished\n")
        sys.stdout.flush()
        return filename

126
    def download_model(self, data_url, data_md5, folder_name):
127 128
        self.download(data_url, self.cache_folder, data_md5)
        os.system(f'wget -q {data_url}')
129 130
        file_name = data_url.split('/')[-1]
        zip_path = os.path.join(self.cache_folder, file_name)
131
        print(
132
            'Data is downloaded at {}. File exists: {}'.format(
133 134 135
                zip_path, os.path.exists(zip_path)
            )
        )
136 137 138 139 140

        data_cache_folder = os.path.join(self.cache_folder, folder_name)
        self.cache_unzipping(data_cache_folder, zip_path)
        return data_cache_folder

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    def run_program(
        self,
        model_path,
        model_filename,
        params_filename,
        batch_size,
        infer_iterations,
    ):
        print(
            "test model path: {}. File exists: {}".format(
                model_path, os.path.exists(model_path)
            )
        )
        place = paddle.CPUPlace()
        exe = paddle.static.Executor(place)
156 157 158 159
        [
            infer_program,
            feed_dict,
            fetch_targets,
160 161 162 163 164 165
        ] = paddle.static.load_inference_model(
            model_path,
            exe,
            model_filename=model_filename,
            params_filename=params_filename,
        )
166 167 168 169 170 171 172
        val_reader = paddle.batch(paddle.dataset.mnist.test(), batch_size)

        img_shape = [1, 28, 28]
        test_info = []
        cnt = 0
        periods = []
        for batch_id, data in enumerate(val_reader()):
173 174 175
            image = np.array([x[0].reshape(img_shape) for x in data]).astype(
                "float32"
            )
176 177 178
            input_label = np.array([x[1] for x in data]).astype("int64")

            t1 = time.time()
179 180 181 182 183
            out = exe.run(
                infer_program,
                feed={feed_dict[0]: image},
                fetch_list=fetch_targets,
            )
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            t2 = time.time()
            period = t2 - t1
            periods.append(period)

            out_label = np.argmax(np.array(out[0]), axis=1)
            top1_num = sum(input_label == out_label)
            test_info.append(top1_num)
            cnt += len(data)

            if (batch_id + 1) == infer_iterations:
                break

        throughput = cnt / np.sum(periods)
        latency = np.average(periods)
        acc1 = np.sum(test_info) / cnt
        return (throughput, latency, acc1)

201 202 203
    def generate_quantized_model(
        self,
        model_path,
204 205
        model_filename,
        params_filename,
206 207 208 209 210 211 212 213 214 215 216 217
        algo="KL",
        round_type="round",
        quantizable_op_type=["conv2d"],
        is_full_quantize=False,
        is_use_cache_file=False,
        is_optimize_model=False,
        batch_size=10,
        batch_nums=10,
        onnx_format=False,
        skip_tensor_list=None,
        bias_correction=False,
    ):
218

219 220
        place = paddle.CPUPlace()
        exe = paddle.static.Executor(place)
221 222
        val_reader = paddle.dataset.mnist.train()

223 224 225
        ptq = PostTrainingQuantization(
            executor=exe,
            model_dir=model_path,
226 227
            model_filename=model_filename,
            params_filename=params_filename,
228 229 230 231 232 233 234 235 236 237 238 239 240
            sample_generator=val_reader,
            batch_size=batch_size,
            batch_nums=batch_nums,
            algo=algo,
            quantizable_op_type=quantizable_op_type,
            round_type=round_type,
            is_full_quantize=is_full_quantize,
            optimize_model=is_optimize_model,
            bias_correction=bias_correction,
            onnx_format=onnx_format,
            skip_tensor_list=skip_tensor_list,
            is_use_cache_file=is_use_cache_file,
        )
241 242 243
        ptq.quantize()
        ptq.save_quantized_model(self.int8_model_path)

244 245 246
    def run_test(
        self,
        model_name,
247 248
        model_filename,
        params_filename,
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        data_url,
        data_md5,
        algo,
        round_type,
        quantizable_op_type,
        is_full_quantize,
        is_use_cache_file,
        is_optimize_model,
        diff_threshold,
        batch_size=10,
        infer_iterations=10,
        quant_iterations=5,
        bias_correction=False,
        onnx_format=False,
        skip_tensor_list=None,
    ):
265 266 267 268

        origin_model_path = self.download_model(data_url, data_md5, model_name)
        origin_model_path = os.path.join(origin_model_path, model_name)

269
        print(
270
            "Start FP32 inference for {} on {} images ...".format(
271 272 273
                model_name, infer_iterations * batch_size
            )
        )
274

275
        (fp32_throughput, fp32_latency, fp32_acc1) = self.run_program(
276 277 278 279 280
            origin_model_path,
            model_filename,
            params_filename,
            batch_size,
            infer_iterations,
281 282 283
        )

        print(
284
            "Start INT8 post training quantization for {} on {} images ...".format(
285 286 287 288 289
                model_name, quant_iterations * batch_size
            )
        )
        self.generate_quantized_model(
            origin_model_path,
290 291
            model_filename,
            params_filename,
292 293 294 295 296 297 298 299 300 301 302 303 304 305
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            batch_size,
            quant_iterations,
            onnx_format,
            skip_tensor_list,
            bias_correction,
        )

        print(
306
            "Start INT8 inference for {} on {} images ...".format(
307 308 309 310
                model_name, infer_iterations * batch_size
            )
        )
        (int8_throughput, int8_latency, int8_acc1) = self.run_program(
311 312 313 314 315
            self.int8_model_path,
            'model.pdmodel',
            'model.pdiparams',
            batch_size,
            infer_iterations,
316
        )
317

318
        print(f"---Post training quantization of {algo} method---")
319
        print(
320
            "FP32 {}: batch_size {}, throughput {} img/s, latency {} s, acc1 {}.".format(
321 322 323
                model_name, batch_size, fp32_throughput, fp32_latency, fp32_acc1
            )
        )
324
        print(
325
            "INT8 {}: batch_size {}, throughput {} img/s, latency {} s, acc1 {}.\n".format(
326 327 328
                model_name, batch_size, int8_throughput, int8_latency, int8_acc1
            )
        )
329 330 331 332 333 334 335 336 337
        sys.stdout.flush()

        delta_value = fp32_acc1 - int8_acc1
        self.assertLess(delta_value, diff_threshold)


class TestPostTrainingKLForMnist(TestPostTrainingQuantization):
    def test_post_training_kl(self):
        model_name = "mnist_model"
338 339
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
340
        algo = "KL"
341
        round_type = "round"
342 343 344 345 346 347 348 349
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
350 351
        self.run_test(
            model_name,
352 353
            'model.pdmodel',
            'model.pdiparams',
354 355 356 357 358 359 360 361 362 363 364 365 366
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
        )
X
XGZhang 已提交
367 368 369 370 371


class TestPostTraininghistForMnist(TestPostTrainingQuantization):
    def test_post_training_hist(self):
        model_name = "mnist_model"
372 373
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
X
XGZhang 已提交
374
        algo = "hist"
375
        round_type = "round"
X
XGZhang 已提交
376 377 378 379 380 381 382 383
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
384 385
        self.run_test(
            model_name,
386 387
            'model.pdmodel',
            'model.pdiparams',
388 389 390 391 392 393 394 395 396 397 398 399 400
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
        )
X
XGZhang 已提交
401 402 403 404 405


class TestPostTrainingmseForMnist(TestPostTrainingQuantization):
    def test_post_training_mse(self):
        model_name = "mnist_model"
406 407
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
X
XGZhang 已提交
408
        algo = "mse"
409
        round_type = "round"
X
XGZhang 已提交
410 411 412 413 414 415 416
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
417
        quant_iterations = 5
418 419
        self.run_test(
            model_name,
420 421
            'model.pdmodel',
            'model.pdiparams',
422 423 424 425 426 427 428 429 430 431 432 433 434
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
        )
435 436 437 438 439


class TestPostTrainingemdForMnist(TestPostTrainingQuantization):
    def test_post_training_mse(self):
        model_name = "mnist_model"
440 441
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
442
        algo = "emd"
443
        round_type = "round"
444 445 446 447 448 449 450
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
X
XGZhang 已提交
451
        quant_iterations = 5
452 453
        self.run_test(
            model_name,
454 455
            'model.pdmodel',
            'model.pdiparams',
456 457 458 459 460 461 462 463 464 465 466 467 468
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
        )
X
XGZhang 已提交
469 470 471 472 473


class TestPostTrainingavgForMnist(TestPostTrainingQuantization):
    def test_post_training_avg(self):
        model_name = "mnist_model"
474 475
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
X
XGZhang 已提交
476
        algo = "avg"
477
        round_type = "round"
X
XGZhang 已提交
478 479 480 481 482 483 484 485
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
486 487
        self.run_test(
            model_name,
488 489
            'model.pdmodel',
            'model.pdiparams',
490 491 492 493 494 495 496 497 498 499 500 501 502
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
        )
503 504 505 506 507


class TestPostTrainingAbsMaxForMnist(TestPostTrainingQuantization):
    def test_post_training_abs_max(self):
        model_name = "mnist_model"
508 509
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
510
        algo = "abs_max"
511
        round_type = "round"
512 513 514 515 516 517 518 519
        quantizable_op_type = ["conv2d", "mul"]
        is_full_quantize = True
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 10
520 521
        self.run_test(
            model_name,
522 523
            'model.pdmodel',
            'model.pdiparams',
524 525 526 527 528 529 530 531 532 533 534 535 536
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
        )
537 538 539 540 541


class TestPostTrainingmseAdaroundForMnist(TestPostTrainingQuantization):
    def test_post_training_mse(self):
        model_name = "mnist_model"
542 543
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
544
        algo = "mse"
545
        round_type = "adaround"
546 547 548 549 550 551 552 553
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
554
        bias_correction = True
555 556
        self.run_test(
            model_name,
557 558
            'model.pdmodel',
            'model.pdiparams',
559 560 561 562 563 564 565 566 567 568 569 570 571 572
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
            bias_correction=bias_correction,
        )
573 574


G
Guanghua Yu 已提交
575 576 577
class TestPostTrainingKLAdaroundForMnist(TestPostTrainingQuantization):
    def test_post_training_kl(self):
        model_name = "mnist_model"
578 579
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
G
Guanghua Yu 已提交
580
        algo = "KL"
581
        round_type = "adaround"
G
Guanghua Yu 已提交
582 583 584 585 586 587 588 589
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
590 591
        self.run_test(
            model_name,
592 593
            'model.pdmodel',
            'model.pdiparams',
594 595 596 597 598 599 600 601 602 603 604 605 606
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
        )
G
Guanghua Yu 已提交
607 608


609 610 611
class TestPostTrainingmseForMnistONNXFormat(TestPostTrainingQuantization):
    def test_post_training_mse_onnx_format(self):
        model_name = "mnist_model"
612 613
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
614
        algo = "mse"
615
        round_type = "round"
616 617 618 619 620 621 622 623 624
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        onnx_format = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
625 626
        self.run_test(
            model_name,
627 628
            'model.pdmodel',
            'model.pdiparams',
629 630 631 632 633 634 635 636 637 638 639 640 641 642
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
            onnx_format=onnx_format,
        )
643 644 645


class TestPostTrainingmseForMnistONNXFormatFullQuant(
646 647
    TestPostTrainingQuantization
):
648 649
    def test_post_training_mse_onnx_format_full_quant(self):
        model_name = "mnist_model"
650 651
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
652
        algo = "mse"
653
        round_type = "round"
654 655 656 657 658 659 660 661 662
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = True
        is_use_cache_file = False
        is_optimize_model = False
        onnx_format = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
663 664
        self.run_test(
            model_name,
665 666
            'model.pdmodel',
            'model.pdiparams',
667 668 669 670 671 672 673 674 675 676 677 678 679 680
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
            onnx_format=onnx_format,
        )
681 682


683 684 685
class TestPostTrainingavgForMnistSkipOP(TestPostTrainingQuantization):
    def test_post_training_avg_skip_op(self):
        model_name = "mnist_model"
686 687
        data_url = "http://paddle-inference-dist.bj.bcebos.com/int8/mnist_model_combined.tar.gz"
        data_md5 = "a49251d3f555695473941e5a725c6014"
688
        algo = "avg"
689
        round_type = "round"
690 691 692 693 694 695 696 697 698
        quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
        is_full_quantize = False
        is_use_cache_file = False
        is_optimize_model = True
        diff_threshold = 0.01
        batch_size = 10
        infer_iterations = 50
        quant_iterations = 5
        skip_tensor_list = ["fc_0.w_0"]
699 700
        self.run_test(
            model_name,
701 702
            'model.pdmodel',
            'model.pdiparams',
703 704 705 706 707 708 709 710 711 712 713 714 715 716
            data_url,
            data_md5,
            algo,
            round_type,
            quantizable_op_type,
            is_full_quantize,
            is_use_cache_file,
            is_optimize_model,
            diff_threshold,
            batch_size,
            infer_iterations,
            quant_iterations,
            skip_tensor_list=skip_tensor_list,
        )
717 718


719 720
if __name__ == '__main__':
    unittest.main()