quant2_int8_nlp_comparison.py 15.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   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 argparse
import logging
17 18
import os
import sys
19
import time
20 21 22 23
import unittest

import numpy as np

24 25
import paddle
from paddle.fluid.framework import IrGraph
26 27
from paddle.framework import core
from paddle.static.quantization import Quant2Int8MkldnnPass
28

P
pangyoki 已提交
29 30
paddle.enable_static()

31 32 33 34 35 36 37 38 39 40 41 42
logging.basicConfig(format='%(asctime)s-%(levelname)s: %(message)s')
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.INFO)


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--batch_size', type=int, default=1, help='Batch size.')
    parser.add_argument(
        '--skip_batch_num',
        type=int,
        default=0,
43 44 45 46
        help='Number of the first minibatches to skip in performance statistics.',
    )
    parser.add_argument(
        '--quant_model', type=str, default='', help='A path to a Quant model.'
47 48
    )
    parser.add_argument(
49 50 51
        '--fp32_model',
        type=str,
        default='',
52
        help='A path to an FP32 model. If empty, the Quant model will be used for FP32 inference.',
53
    )
54
    parser.add_argument('--infer_data', type=str, default='', help='Data file.')
55 56 57
    parser.add_argument(
        '--labels', type=str, default='', help='File with labels.'
    )
58 59 60
    parser.add_argument(
        '--batch_num',
        type=int,
61
        default=0,
62 63 64 65 66 67 68
        help='Number of batches to process. 0 or less means whole dataset. Default: 0.',
    )
    parser.add_argument(
        '--acc_diff_threshold',
        type=float,
        default=0.01,
        help='Accepted accuracy difference threshold.',
69
    )
70
    parser.add_argument(
71
        '--ops_to_quantize',
72 73
        type=str,
        default='',
74
        help='A comma separated list of operators to quantize. Only quantizable operators are taken into account. If the option is not used, an attempt to quantize all quantizable operators will be made.',
75
    )
76 77 78 79
    parser.add_argument(
        '--op_ids_to_skip',
        type=str,
        default='',
80 81
        help='A comma separated list of operator ids to skip in quantization.',
    )
82 83 84 85
    parser.add_argument(
        '--targets',
        type=str,
        default='quant,int8,fp32',
86 87 88 89 90 91
        help='A comma separated list of inference types to run ("int8", "fp32", "quant"). Default: "quant,int8,fp32"',
    )
    parser.add_argument(
        '--debug',
        action='store_true',
        help='If used, the graph of Quant model is drawn.',
92
    )
93 94 95 96 97 98

    test_args, args = parser.parse_known_args(namespace=unittest)

    return test_args, sys.argv[:1] + args


W
Wojciech Uss 已提交
99
class QuantInt8NLPComparisonTest(unittest.TestCase):
100
    """
W
Wojciech Uss 已提交
101
    Test for accuracy comparison of Quant FP32 and INT8 NLP inference.
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    """

    def _reader_creator(self, data_file=None, labels_file=None):
        assert data_file, "The dataset file is missing."
        assert labels_file, "The labels file is missing."

        def reader():
            with open(data_file, 'r') as df:
                with open(labels_file, 'r') as lf:
                    data_lines = df.readlines()
                    labels_lines = lf.readlines()
                    assert len(data_lines) == len(
                        labels_lines
                    ), "The number of labels does not match the length of the dataset."

                    for i in range(len(data_lines)):
                        data_fields = data_lines[i].split(';')
119 120 121
                        assert (
                            len(data_fields) >= 2
                        ), "The number of data fields in the dataset is less than 2"
122 123 124 125
                        buffers = []
                        shape = []
                        for j in range(2):
                            data = data_fields[j].split(':')
126 127 128
                            assert (
                                len(data) >= 2
                            ), "Size of data in the dataset is less than 2"
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
                            # Shape is stored under index 0, while data under 1
                            shape = data[0].split()
                            shape.pop(0)
                            shape_np = np.array(shape).astype("int64")
                            buffer_i = data[1].split()
                            buffer_np = np.array(buffer_i).astype("int64")
                            buffer_np.shape = tuple(shape_np)
                            buffers.append(buffer_np)
                        label = labels_lines[i]
                        yield buffers[0], buffers[1], int(label)

        return reader

    def _get_batch_correct(self, batch_output=None, labels=None):
        total = len(batch_output)
        assert total > 0, "The batch output is empty."
        correct = 0
        for n, output in enumerate(batch_output[0]):
            max_idx = np.where(output == output.max())
            if max_idx == labels[n]:
                correct += 1
        return correct

152 153 154 155 156 157 158 159 160
    def _predict(
        self,
        test_reader=None,
        model_path=None,
        batch_size=1,
        batch_num=1,
        skip_batch_num=0,
        target='quant',
    ):
W
Wojciech Uss 已提交
161
        assert target in ['quant', 'int8', 'fp32']
162 163 164 165
        place = paddle.CPUPlace()
        exe = paddle.static.Executor(place)
        inference_scope = paddle.static.global_scope()
        with paddle.static.scope_guard(inference_scope):
166
            if os.path.exists(os.path.join(model_path, '__model__')):
167 168 169 170
                [
                    inference_program,
                    feed_target_names,
                    fetch_targets,
171
                ] = paddle.fluid.io.load_inference_model(model_path, exe)
172
            else:
173 174 175 176
                [
                    inference_program,
                    feed_target_names,
                    fetch_targets,
177 178 179 180 181
                ] = paddle.static.load_inference_model(
                    model_path,
                    exe,
                    model_filename='model',
                    params_filename='params',
182
                )
183 184

            graph = IrGraph(core.Graph(inference_program.desc), for_test=True)
185
            if self._debug:
W
Wojciech Uss 已提交
186
                graph.draw('.', 'quant_orig', graph.all_op_nodes())
187
            if target != 'quant':
W
Wojciech Uss 已提交
188
                quant_transform_pass = Quant2Int8MkldnnPass(
189
                    self._quantized_ops,
190
                    _op_ids_to_skip=self._op_ids_to_skip,
191 192 193
                    _scope=inference_scope,
                    _place=place,
                    _core=core,
194 195 196
                    _debug=self._debug,
                )
                if target == 'int8':
W
Wojciech Uss 已提交
197 198 199
                    graph = quant_transform_pass.apply(graph)
                else:  # target == fp32
                    graph = quant_transform_pass.prepare_and_optimize_fp32(
200 201
                        graph
                    )
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

            inference_program = graph.to_program()

            total_correct = 0
            total_samples = 0
            batch_times = []
            ppses = []  # predictions per second
            iters = 0
            infer_start_time = time.time()
            for data in test_reader():
                if batch_num > 0 and iters >= batch_num:
                    break
                if iters == skip_batch_num:
                    total_samples = 0
                    infer_start_time = time.time()
                input0 = np.array([x[0] for x in data]).astype('int64')
                input1 = np.array([x[1] for x in data]).astype('int64')
                labels = np.array([x[2] for x in data]).astype('int64')

                start = time.time()
222 223 224 225 226 227 228 229
                out = exe.run(
                    inference_program,
                    feed={
                        feed_target_names[0]: input0,
                        feed_target_names[1]: input1,
                    },
                    fetch_list=fetch_targets,
                )
230 231 232 233 234 235 236 237 238 239 240 241 242
                batch_time = (time.time() - start) * 1000  # in miliseconds
                batch_times.append(batch_time)
                batch_correct = self._get_batch_correct(out, labels)
                batch_len = len(data)
                total_samples += batch_len
                total_correct += batch_correct
                batch_acc = float(batch_correct) / float(batch_len)
                pps = batch_len / batch_time * 1000
                ppses.append(pps)
                latency = batch_time / batch_len
                iters += 1
                appx = ' (warm-up)' if iters <= skip_batch_num else ''
                _logger.info(
243 244 245 246
                    'batch {0}{4}, acc: {1:.4f}, latency: {2:.4f} ms, predictions per sec: {3:.2f}'.format(
                        iters, batch_acc, latency, pps, appx
                    )
                )
247 248 249 250 251 252 253 254 255

            # Postprocess benchmark data
            infer_total_time = time.time() - infer_start_time
            batch_latencies = batch_times[skip_batch_num:]
            batch_latency_avg = np.average(batch_latencies)
            latency_avg = batch_latency_avg / batch_size
            ppses = ppses[skip_batch_num:]
            pps_avg = np.average(ppses)
            acc_avg = float(np.sum(total_correct)) / float(total_samples)
256
            _logger.info(
257 258
                'Total inference run time: {:.2f} s'.format(infer_total_time)
            )
259 260 261

            return acc_avg, pps_avg, latency_avg

W
Wojciech Uss 已提交
262
    def _print_performance(self, title, pps, lat):
263
        _logger.info(
264 265 266 267
            '{0}: avg predictions per sec: {1:.2f}, avg latency: {2:.4f} ms'.format(
                title, pps, lat
            )
        )
W
Wojciech Uss 已提交
268 269 270 271 272 273 274 275 276

    def _print_accuracy(self, title, acc):
        _logger.info('{0}: avg accuracy: {1:.6f}'.format(title, acc))

    def _summarize_performance(self, int8_pps, int8_lat, fp32_pps, fp32_lat):
        _logger.info('--- Performance summary ---')
        self._print_performance('INT8', int8_pps, int8_lat)
        if fp32_lat >= 0:
            self._print_performance('FP32', fp32_pps, fp32_lat)
277

W
Wojciech Uss 已提交
278
    def _summarize_accuracy(self, quant_acc, int8_acc, fp32_acc):
279
        _logger.info('--- Accuracy summary ---')
W
Wojciech Uss 已提交
280 281 282 283 284 285
        self._print_accuracy('Quant', quant_acc)
        self._print_accuracy('INT8', int8_acc)
        if fp32_acc >= 0:
            self._print_accuracy('FP32', fp32_acc)

    def _compare_accuracy(self, threshold, quant_acc, int8_acc):
286
        _logger.info(
287 288 289 290
            'Accepted accuracy drop threshold: {0}. (condition: (Quant_acc - INT8_acc) <= threshold)'.format(
                threshold
            )
        )
291
        # Random outputs give accuracy about 0.33, we assume valid accuracy to be at least 0.5
W
Wojciech Uss 已提交
292
        assert quant_acc > 0.5
293
        assert int8_acc > 0.5
W
Wojciech Uss 已提交
294
        assert quant_acc - int8_acc <= threshold
295

296 297 298 299 300 301
    def _strings_from_csv(self, string):
        return set(s.strip() for s in string.split(','))

    def _ints_from_csv(self, string):
        return set(map(int, string.split(',')))

302
    def test_graph_transformation(self):
303
        if not core.is_compiled_with_mkldnn():
304 305
            return

W
Wojciech Uss 已提交
306
        quant_model_path = test_case_args.quant_model
307 308 309
        assert (
            quant_model_path
        ), 'The Quant model path cannot be empty. Please, use the --quant_model option.'
310
        data_path = test_case_args.infer_data
311 312 313
        assert (
            data_path
        ), 'The dataset path cannot be empty. Please, use the --infer_data option.'
W
Wojciech Uss 已提交
314
        fp32_model_path = test_case_args.fp32_model
315 316 317 318 319 320
        labels_path = test_case_args.labels
        batch_size = test_case_args.batch_size
        batch_num = test_case_args.batch_num
        skip_batch_num = test_case_args.skip_batch_num
        acc_diff_threshold = test_case_args.acc_diff_threshold
        self._debug = test_case_args.debug
321

322
        self._quantized_ops = set()
323
        if test_case_args.ops_to_quantize:
324
            self._quantized_ops = self._strings_from_csv(
325 326
                test_case_args.ops_to_quantize
            )
327 328 329

        self._op_ids_to_skip = set([-1])
        if test_case_args.op_ids_to_skip:
330
            self._op_ids_to_skip = self._ints_from_csv(
331 332
                test_case_args.op_ids_to_skip
            )
333 334 335 336 337

        self._targets = self._strings_from_csv(test_case_args.targets)
        assert self._targets.intersection(
            {'quant', 'int8', 'fp32'}
        ), 'The --targets option, if used, must contain at least one of the targets: "quant", "int8", "fp32".'
338

W
Wojciech Uss 已提交
339
        _logger.info('Quant & INT8 prediction run.')
W
Wojciech Uss 已提交
340
        _logger.info('Quant model: {}'.format(quant_model_path))
W
Wojciech Uss 已提交
341 342
        if fp32_model_path:
            _logger.info('FP32 model: {}'.format(fp32_model_path))
343 344 345 346 347
        _logger.info('Dataset: {}'.format(data_path))
        _logger.info('Labels: {}'.format(labels_path))
        _logger.info('Batch size: {}'.format(batch_size))
        _logger.info('Batch number: {}'.format(batch_num))
        _logger.info('Accuracy drop threshold: {}.'.format(acc_diff_threshold))
348
        _logger.info(
349 350 351 352 353 354 355 356 357 358 359 360 361
            'Quantized ops: {}.'.format(
                ','.join(self._quantized_ops)
                if self._quantized_ops
                else 'all quantizable'
            )
        )
        _logger.info(
            'Op ids to skip quantization: {}.'.format(
                ','.join(map(str, self._op_ids_to_skip))
                if test_case_args.op_ids_to_skip
                else 'none'
            )
        )
362
        _logger.info('Targets: {}.'.format(','.join(self._targets)))
363

364 365
        if 'quant' in self._targets:
            _logger.info('--- Quant prediction start ---')
366 367 368 369 370 371 372 373 374 375 376 377
            val_reader = paddle.batch(
                self._reader_creator(data_path, labels_path),
                batch_size=batch_size,
            )
            quant_acc, quant_pps, quant_lat = self._predict(
                val_reader,
                quant_model_path,
                batch_size,
                batch_num,
                skip_batch_num,
                target='quant',
            )
378 379
            self._print_performance('Quant', quant_pps, quant_lat)
            self._print_accuracy('Quant', quant_acc)
W
Wojciech Uss 已提交
380

381 382
        if 'int8' in self._targets:
            _logger.info('--- INT8 prediction start ---')
383 384 385 386 387 388 389 390 391 392 393 394
            val_reader = paddle.batch(
                self._reader_creator(data_path, labels_path),
                batch_size=batch_size,
            )
            int8_acc, int8_pps, int8_lat = self._predict(
                val_reader,
                quant_model_path,
                batch_size,
                batch_num,
                skip_batch_num,
                target='int8',
            )
395 396
            self._print_performance('INT8', int8_pps, int8_lat)
            self._print_accuracy('INT8', int8_acc)
W
Wojciech Uss 已提交
397 398

        fp32_acc = fp32_pps = fp32_lat = -1
399
        if 'fp32' in self._targets and fp32_model_path:
W
Wojciech Uss 已提交
400
            _logger.info('--- FP32 prediction start ---')
401 402 403 404 405 406 407 408 409 410 411 412
            val_reader = paddle.batch(
                self._reader_creator(data_path, labels_path),
                batch_size=batch_size,
            )
            fp32_acc, fp32_pps, fp32_lat = self._predict(
                val_reader,
                fp32_model_path,
                batch_size,
                batch_num,
                skip_batch_num,
                target='fp32',
            )
W
Wojciech Uss 已提交
413 414
            self._print_performance('FP32', fp32_pps, fp32_lat)
            self._print_accuracy('FP32', fp32_acc)
415

416 417 418 419 420
        if {'int8', 'fp32'}.issubset(self._targets):
            self._summarize_performance(int8_pps, int8_lat, fp32_pps, fp32_lat)
        if {'int8', 'quant'}.issubset(self._targets):
            self._summarize_accuracy(quant_acc, int8_acc, fp32_acc)
            self._compare_accuracy(acc_diff_threshold, quant_acc, int8_acc)
421 422 423 424 425 426


if __name__ == '__main__':
    global test_case_args
    test_case_args, remaining_args = parse_args()
    unittest.main(argv=remaining_args)