post_training_quantization.py 79.2 KB
Newer Older
1
#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13
#
# 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.
14

15
import logging
16
import os
17
import shutil
18

19
import numpy as np
20

21 22 23 24
try:
    from tqdm import tqdm
except:
    from .utils import tqdm
25

26
from inspect import isgeneratorfunction
27 28 29 30 31 32 33 34 35 36 37

from paddle.fluid.framework import IrGraph, _get_var

from ... import io, static
from ...fluid import reader
from ...framework import core
from ...utils import unique_name
from ..log_helper import get_logger
from . import utils
from .adaround import run_adaround
from .cal_kl_threshold import cal_kl_threshold
38
from .quantization_pass import (
39 40 41
    AddQuantDequantPass,
    AddQuantDequantPassV2,
    QuantizationFreezePass,
42 43 44 45
    QuantizationTransformPass,
    QuantizationTransformPassV2,
    QuantWeightPass,
)
46

47 48 49
_logger = get_logger(
    __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s'
)
50 51


52 53 54 55 56 57 58 59
def _all_persistable_var_names(program):
    persistable_var_names = []
    for var in program.list_vars():
        if var.persistable:
            persistable_var_names.append(var.name)
    return persistable_var_names


60 61 62 63 64 65 66 67 68 69 70 71
def _remove_unused_var_nodes(graph):
    all_used_vars = set()
    ops = graph.all_op_nodes()
    for op_node in ops:
        for input_node in op_node.inputs:
            all_used_vars.add(input_node)
        for output_node in op_node.outputs:
            all_used_vars.add(output_node)

    all_used_vars = {n.node for n in all_used_vars}
    all_unused_vars = {
        n
72 73 74
        for n in filter(
            lambda node: node.node not in all_used_vars, graph.all_var_nodes()
        )
75 76 77 78 79 80 81 82 83 84 85 86 87 88
    }
    graph.safe_remove_nodes(all_unused_vars)
    return graph


def _remove_ctrl_vars(graph):
    remove_ctr_vars = set()
    for node in graph.all_var_nodes():
        if node.is_ctrl_var():
            remove_ctr_vars.add(node)
    graph.safe_remove_nodes(remove_ctr_vars)
    return graph


89 90 91
def _apply_pass(
    scope, graph, pass_name, attrs=None, attr_values=None, debug=False
):
92 93 94 95 96 97
    ir_pass = core.get_pass(pass_name)
    cpp_graph = graph.graph
    if not cpp_graph.has('__param_scope__'):
        cpp_graph.set_not_owned('__param_scope__', scope)
    if attrs:
        assert attr_values and len(attrs) == len(
98 99
            attr_values
        ), "Different number of pass attributes and their values."
100 101 102 103 104 105 106 107 108
        for attr, value in zip(attrs, attr_values):
            ir_pass.set(attr, value)
    ir_pass.apply(cpp_graph)
    if debug:
        graph.draw('.', 'qat_fp32_{}'.format(pass_name), graph.all_op_nodes())
    _remove_unused_var_nodes(graph)
    return graph


109
class PostTrainingQuantization:
110 111
    """
    Utilizing post training quantization methon to quantize the FP32 model,
112
    and it uses calibrate data to get the quantization information for all
113 114 115
    quantized variables.
    """

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    def __init__(
        self,
        executor,
        model_dir,
        scope=None,
        model_filename=None,
        params_filename=None,
        batch_generator=None,
        sample_generator=None,
        data_loader=None,
        batch_size=10,
        batch_nums=None,
        algo="KL",
        hist_percent=0.99999,
        quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"],
        round_type='round',
        learning_rate=0.001,
        is_full_quantize=False,
        bias_correction=False,
        activation_bits=8,
        weight_bits=8,
        activation_quantize_type='range_abs_max',
        weight_quantize_type='channel_wise_abs_max',
        onnx_format=False,
        freeze_model=True,
        optimize_model=False,
        is_use_cache_file=False,
        skip_tensor_list=None,
        same_scale_tensor_list=None,
        cache_dir=None,
        scale_dict=None,
        return_graph=False,
    ):
149
        '''
150
        Constructor.
151 152

        Args:
153
            executor(static.Executor): The executor to load, run and save the
154
                quantized model.
155 156
            scope(static.Scope, optional): The scope of the program, use it to load
                and save variables. If scope=None, get scope by static.global_scope().
157
            model_dir(str): The path of the fp32 model that will be quantized,
158
                and the model and params files are under the path.
159 160
            model_filename(str, optional): The name of file to load the inference
                program. If it is None, the default filename '__model__' will
161 162
                be used. Default is 'None'.
            params_filename(str, optional): The name of file to load all parameters.
163 164
                When all parameters were saved in a single binary file, set it
                as the real filename. If parameters were saved in separate files,
165
                set it as 'None'. Default is 'None'.
166
            batch_generator(Python Generator): The batch generator provides
167 168 169 170 171 172 173
                calibrate data for DataLoader, and it returns a batch every
                time. Note that, sample_generator and batch_generator, only one
                should be set. Beisdes, batch_generator supports lod tensor.
            sample_generator(Python Generator): The sample generator provides
                calibrate data for DataLoader, and it only returns a sample every
                time. Note that, sample_generator and batch_generator, only one
                should be set. Beisdes, sample_generator dose not support lod tensor.
174 175 176
            data_loader(Python Generator, Paddle.io.DataLoader, optional): The
                Generator or Dataloader provides calibrate data, and it could
                return a batch every time.
177
            batch_size(int, optional): The batch size of DataLoader. Default is 10.
178 179
            batch_nums(int, optional): If batch_nums is not None, the number of
                calibrate data is batch_size*batch_nums. If batch_nums is None, use
180
                all data provided by sample_generator as calibrate data.
181 182
            algo(str, optional): If algo='KL', use KL-divergenc method to
                get the KL threshold for quantized activations and get the abs_max
183 184
                value for quantized weights. If algo='abs_max', get the abs max
                value for activations and weights. If algo= 'min_max', get the min
X
XGZhang 已提交
185
                and max value for quantized activations and weights. If algo='avg',
186
                get the average value among the max values for activations. If
X
XGZhang 已提交
187
                algo= 'hist', get the value of 'hist_percent' quantile as the threshold.
188
                If algo='mse', get the value which makes the quantization mse loss
X
XGZhang 已提交
189 190 191
                minimal. Default is KL.
            hist_percent(float, optional): The threshold of algo 'hist' for activations.
                Default is 0.99999.
192 193
            quantizable_op_type(list[str], optional): List the type of ops
                that will be quantized. Default is ["conv2d", "depthwise_conv2d",
194
                "mul"].
195
            round_type(str, optional): The method of converting the quantized weights
196
                value float->int. Currently supports ['round', 'adaround'] methods.
197 198
                Default is `round`, which is rounding nearest to the integer.
                'adaround' is refer to https://arxiv.org/abs/2004.10568.
199
            learning_rate(float, optional): The learning rate of adaround method.
200
            is_full_quantized(bool, optional): If set is_full_quantized as True,
201
                apply quantization to all supported quantizable op type. If set
202
                is_full_quantized as False, only apply quantization to the op type
203
                according to the input quantizable_op_type.
X
XGZhang 已提交
204 205
            bias_correction(bool, optional): If set as True, use the bias correction
                method of https://arxiv.org/abs/1810.05723. Default is False.
206
            activation_bits(int): quantization bit number for activation.
207 208 209 210 211 212 213 214 215 216 217 218
            weight_bits(int, optional): quantization bit number for weights.
            activation_quantize_type(str): quantization type for activation,
                now support 'range_abs_max', 'moving_average_abs_max' and 'abs_max'.
                This param only specifies the fake ops in saving quantized model.
                If it is 'range_abs_max' or 'moving_average_abs_max', we save the scale
                obtained by post training quantization in fake ops. Note that, if it
                is 'abs_max', the scale will not be saved in fake ops.
            weight_quantize_type(str): quantization type for weights,
                support 'abs_max' and 'channel_wise_abs_max'. This param only specifies
                the fake ops in saving quantized model, and we save the scale obtained
                by post training quantization in fake ops. Compared to 'abs_max',
                the model accuracy is usually higher when it is 'channel_wise_abs_max'.
219 220
            onnx_format(bool): Whether to export the quantized model with format of ONNX.
                Default is False.
221
            freeze_model(bool): Whether to convert quantized and trained ``program`` to final
222 223
                quantized ``program``. Default: True.
            skip_tensor_list(list): List of skip quant tensor name. Default: None.
224 225
            same_scale_tensor_list(list(list)): The list of tensor keep same scale in the outermost
                list, the final scale about every list is the max of the scale in the list
226
                of tensor. Default: None.
227 228 229 230 231 232 233 234
            optimize_model(bool, optional): If set optimize_model as True, it applies
                some passes to the model before quantization, and it supports
                `conv2d/depthwise_conv2d + bn` pass so far. Some targets require the
                weights are quantized by tensor-wise method, which means the weights
                scale for all channel are the same. However, if fuse
                `conv2d/depthwise_conv2d + bn`, the weights scale for all channel will
                be different. In address this problem, fuse the pattern before
                quantization. Default False.
235 236
            is_use_cache_file(bool, optional): This param is deprecated.
            cache_dir(str, optional): This param is deprecated.
237 238 239
        Returns:
            None

240 241
        Examples:
        .. code-block:: python
242 243
            import paddle.static as static
            from paddle.static.quantization import PostTrainingQuantization
244

245
            exe = static.Executor(paddle.CPUPlace())
246
            model_dir = path/to/fp32_model_params
247
            # set model_filename as None when the filename is __model__,
248
            # otherwise set it as the real filename
249 250
            model_filename = None
            # set params_filename as None when all parameters were saved in
251 252 253
            # separate files, otherwise set it as the real filename
            params_filename = None
            save_model_path = path/to/save_model_path
254
            # prepare the sample generator according to the model, and the
255
            # sample generator must return a sample every time. The reference
256 257 258
            # document: https://www.paddlepaddle.org.cn/documentation/docs/zh
            # /user_guides/howto/prepare_data/use_py_reader.html
            sample_generator = your_sample_generator
259 260 261
            batch_size = 10
            batch_nums = 10
            algo = "KL"
262
            quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
263 264
            ptq = PostTrainingQuantization(
                        executor=exe,
265 266 267 268
                        sample_generator=sample_generator,
                        model_dir=model_dir,
                        model_filename=model_filename,
                        params_filename=params_filename,
269 270 271 272 273 274 275
                        batch_size=batch_size,
                        batch_nums=batch_nums,
                        algo=algo,
                        quantizable_op_type=quantizable_op_type)
            ptq.quantize()
            ptq.save_quantized_model(save_model_path)
        '''
276

277
        self._support_activation_quantize_type = [
278 279 280
            'range_abs_max',
            'moving_average_abs_max',
            'abs_max',
281 282
        ]
        self._support_weight_quantize_type = ['abs_max', 'channel_wise_abs_max']
X
XGZhang 已提交
283
        self._support_algo_type = [
284 285 286 287 288 289 290 291
            'KL',
            'hist',
            'avg',
            'mse',
            'emd',
            'abs_max',
            'min_max',
            'ptf',
X
XGZhang 已提交
292
        ]
293
        assert round_type in ['adaround', 'round']
294 295
        self._round_type = round_type
        self._learning_rate = learning_rate
296
        self._dynamic_quantize_op_type = ['lstm']
297 298 299 300 301 302 303
        self._support_quantize_op_type = list(
            set(
                utils._weight_supported_quantizable_op_type
                + utils._act_supported_quantizable_op_type
                + self._dynamic_quantize_op_type
            )
        )
304 305

        # Check inputs
306
        assert executor is not None, "The executor cannot be None."
307 308 309 310 311
        assert any(
            [gen is not None]
            for gen in [sample_generator, batch_generator, data_loader]
        ), (
            "The sample_generator, batch_generator "
312
            "and data_loader cannot be None in the same time."
313
        )
314
        if data_loader is not None:
315 316 317 318 319 320 321 322
            assert isinstance(
                data_loader,
                (
                    io.DataLoader,
                    type(isgeneratorfunction),
                    reader.GeneratorLoader,
                ),
            ), "data_loader only accepts `paddle.io.DataLoader` or Generator instance."
323
        assert batch_size > 0, "The batch_size should be greater than 0."
324 325 326 327 328 329 330 331 332 333 334 335 336
        assert (
            algo in self._support_algo_type
        ), "The algo should be KL, hist, mse, avg, abs_max, min_max or ptf."
        assert (
            activation_quantize_type in self._support_activation_quantize_type
        ), "The activation_quantize_type ({}) should in ({}).".format(
            activation_quantize_type, self._support_activation_quantize_type
        )
        assert (
            weight_quantize_type in self._support_weight_quantize_type
        ), "The weight_quantize_type ({}) shoud in ({}).".format(
            weight_quantize_type, self._support_weight_quantize_type
        )
337 338

        # Save input params
X
XGZhang 已提交
339
        self._bias_correction = bias_correction
340
        self._executor = executor
341
        self._scope = static.global_scope() if scope is None else scope
342 343 344
        self._model_dir = model_dir
        self._model_filename = model_filename
        self._params_filename = params_filename
345
        self._sample_generator = sample_generator
346
        self._batch_generator = batch_generator
347 348 349
        self._batch_size = batch_size
        self._batch_nums = batch_nums
        self._algo = algo
X
XGZhang 已提交
350
        self._hist_percent = hist_percent
351 352 353 354
        self._activation_bits = activation_bits
        self._weight_bits = weight_bits
        self._activation_quantize_type = activation_quantize_type
        self._weight_quantize_type = weight_quantize_type
355
        self._onnx_format = onnx_format
G
Guanghua Yu 已提交
356
        self._clip_extra = True if self._onnx_format else False
357
        self._skip_tensor_list = skip_tensor_list
358
        self._is_full_quantize = is_full_quantize
359
        if is_full_quantize:
360
            self._quantizable_op_type = self._support_quantize_op_type
361 362 363
        else:
            self._quantizable_op_type = quantizable_op_type
            for op_type in self._quantizable_op_type:
364
                assert op_type in self._support_quantize_op_type, (
365
                    op_type + " is not supported for quantization."
366
                )
367
        self._optimize_model = optimize_model
368

369
        # Define variables
370 371 372 373
        self._place = self._executor.place
        self._program = None
        self._feed_list = None
        self._fetch_list = None
374
        self._data_loader = data_loader
375

376
        self._out_scale_op_list = utils.QUANT_SUPPORTED_OP_TYPE_LIST
377 378
        self._quantized_weight_var_name = set()
        self._quantized_act_var_name = set()
379
        self._weight_op_pairs = {}
X
XGZhang 已提交
380
        # The vars for alog = KL or hist
381 382
        self._sampling_act_abs_min_max = {}
        self._sampling_act_histogram = {}
383
        self._sampling_data = {}
X
XGZhang 已提交
384
        self._quantized_var_threshold = {}
385 386
        self._histogram_bins = 2048
        # The vars for algo = min_max
387 388
        self._quantized_var_min = {}
        self._quantized_var_max = {}
X
XGZhang 已提交
389 390 391
        # The vars for algo = avg
        self._quantized_var_avg = {}
        # The best loss of algo = mse
392
        self._best_calibration_loss = {}
X
XGZhang 已提交
393 394
        # The threshold for algo = abs_max, mse or avg
        self._quantized_threshold = {}
395 396 397
        # If the tensor is zero-size during any calibration step,
        # it will be stored in self._zero_size_var_names
        self._zero_size_var_names = set()
398 399 400 401
        self._same_scale_tensor_list = same_scale_tensor_list
        self._freeze_model = freeze_model
        self._scale_dict = scale_dict
        self._return_graph = return_graph
402 403 404
        self.FLAG = False
        if self._program is not None:
            self.FLAG = True
405 406 407

    def quantize(self):
        '''
408 409 410
        Load the FP32 model, and use the calibrate data to calculate the forward-stage.
        Based on the sample data, we can get the quantization information, and obtain
        the final quantized model.
411 412 413 414

        Args:
            None
        Returns:
415 416
            the program of quantized model.
        '''
417
        self._load_model_data()
418
        self._collect_target_varnames()
419
        self._set_activation_persistable()
420

X
XGZhang 已提交
421
        if self._algo in ["KL", "hist"]:
422
            batch_id = 0
423
            with tqdm(
424 425 426 427
                total=self._batch_nums,
                bar_format='Preparation stage, Run batch:|{bar}| {n_fmt}/{total_fmt}',
                ncols=80,
            ) as t:
428
                for data in self._data_loader():
429 430 431 432 433 434 435
                    self._executor.run(
                        program=self._program,
                        feed=data,
                        fetch_list=self._fetch_list,
                        return_numpy=False,
                        scope=self._scope,
                    )
436 437 438 439 440 441 442 443
                    self._collect_activation_abs_min_max()
                    batch_id += 1
                    t.update()
                    if self._batch_nums and batch_id >= self._batch_nums:
                        break
            self._init_sampling_act_histogram()

        batch_id = 0
444 445 446 447 448
        with tqdm(
            total=self._batch_nums,
            bar_format='Sampling stage, Run batch:|{bar}| {n_fmt}/{total_fmt}',
            ncols=80,
        ) as t:
449
            for data in self._data_loader():
450 451 452 453 454 455 456
                self._executor.run(
                    program=self._program,
                    feed=data,
                    fetch_list=self._fetch_list,
                    return_numpy=False,
                    scope=self._scope,
                )
457
                self._sampling()
458
                batch_id += 1
459
                t.update()
460 461
                if self._batch_nums and batch_id >= self._batch_nums:
                    break
462

X
XGZhang 已提交
463 464
        if self._algo == 'avg':
            for var_name in self._quantized_act_var_name:
465 466
                if var_name not in self._quantized_var_avg:
                    continue
467 468 469
                self._quantized_threshold[var_name] = np.array(
                    self._quantized_var_avg[var_name]
                ).mean()
470

X
XGZhang 已提交
471 472
        if self._algo in ["KL", "hist"]:
            self._calculate_kl_hist_threshold()
473

474
        if self._round_type == 'adaround':
475 476 477 478
            self._adaround_apply()

        self._reset_activation_persistable()

479
        if self._algo == 'min_max':
480
            self._save_input_threhold()
481 482 483 484
        else:
            self._update_program()

        # save out_threshold for quantized ops.
485 486
        if not self.FLAG:
            self._save_output_threshold()
487

488 489 490 491
        if any(
            op_type in self._quantizable_op_type
            for op_type in self._dynamic_quantize_op_type
        ):
492
            self._collect_dynamic_quantize_op_threshold(
493 494
                self._dynamic_quantize_op_type
            )
495

496
        utils.move_persistable_var_to_global_block(self._program)
497

498 499 500 501 502
        if not self._return_graph:
            return self._program
        else:
            main_graph = IrGraph(core.Graph(self._program.desc), for_test=True)
            return main_graph
503

504
    def _adaround_apply(self):
505
        assert self._algo != "min_max", "The algo should not be min_max."
506 507 508 509
        if self._algo in ["KL", "hist"]:
            scale_dict = self._quantized_var_threshold
        else:
            scale_dict = self._quantized_threshold
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
        run_adaround(
            self._data_loader,
            self._program,
            self._fetch_list,
            self._executor,
            self._scope,
            self._place,
            self._quantized_op_pairs,
            self._weight_op_pairs,
            scale_dict,
            num_iterations=self._batch_nums,
            bias_correction=self._bias_correction,
            lr=self._learning_rate,
        )

    def save_quantized_model(
        self, save_model_path, model_filename=None, params_filename=None
    ):
528 529 530 531
        '''
        Save the quantized model to the disk.

        Args:
532 533
            save_model_path(str): The path to save the quantized model.
            model_filename(str, optional): If the model_filename is None,
534 535
                save the model to 'model.pdmodel' and 'model.pdiparams'. Otherwise, save the model to 'model_name.pdmodel' and
                'model_name.pdiparams". Default: None.
536
        Returns:
537 538
            None
        '''
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        model_name = None
        if model_filename is None:
            model_name = "model"
        elif model_filename.endswith(".pdmodel"):
            model_name = model_filename.rsplit(".", 1)[0]
        else:
            model_name = model_filename

        path_prefix = os.path.join(save_model_path, model_name)
        feed_vars = [
            self._program.global_block().var(name) for name in self._feed_list
        ]
        static.save_inference_model(
            path_prefix,
            feed_vars,
            self._fetch_list,
555
            executor=self._executor,
556
            program=self._program,
557 558
            clip_extra=self._clip_extra,
        )
559
        _logger.info("The quantized model is saved in " + save_model_path)
560

561
    def _load_model_data(self):
562
        '''
563
        Load model and set data loader.
564
        '''
565 566
        if self._program is None:
            _logger.info("Load model and set data loader ...")
567 568 569 570
            [
                self._program,
                self._feed_list,
                self._fetch_list,
571 572
            ] = static.load_inference_model(
                self._model_dir,
573 574 575 576
                executor=self._executor,
                model_filename=self._model_filename,
                params_filename=self._params_filename,
            )
577 578 579 580

        if self._optimize_model:
            self._optimize_fp32_model()

581
        feed_vars = [
582
            _get_var(str(var_name), self._program)
583 584
            for var_name in self._feed_list
        ]
585 586

        if self._data_loader is not None:
587 588 589
            self._batch_nums = (
                self._batch_nums if self._batch_nums else len(self._data_loader)
            )
590
            return
591 592 593
        self._data_loader = io.DataLoader.from_generator(
            feed_list=feed_vars, capacity=3 * self._batch_size, iterable=True
        )
594
        if self._sample_generator is not None:
595 596 597 598 599 600
            self._data_loader.set_sample_generator(
                self._sample_generator,
                batch_size=self._batch_size,
                drop_last=True,
                places=self._place,
            )
601
        elif self._batch_generator is not None:
602 603 604 605 606 607 608 609
            self._data_loader.set_batch_generator(
                self._batch_generator, places=self._place
            )
        self._batch_nums = (
            self._batch_nums
            if self._batch_nums
            else len(list(self._data_loader))
        )
610

611 612 613 614 615 616 617 618
    def _optimize_fp32_model(self):
        '''
        Fuse the `conv2d/depthwise_conv2d + bn` in FP32 model.
        '''
        _logger.info("Optimize FP32 model ...")
        graph = IrGraph(core.Graph(self._program.desc), for_test=True)
        graph = _remove_ctrl_vars(graph)
        graph = _apply_pass(self._scope, graph, 'conv_bn_fuse_pass')
619 620
        graph = _apply_pass(self._scope, graph, 'depthwise_conv_bn_fuse_pass')
        graph = _apply_pass(self._scope, graph, 'conv_transpose_bn_fuse_pass')
621
        graph = _apply_pass(self._scope, graph, 'conv_eltwiseadd_bn_fuse_pass')
622 623 624
        graph = _apply_pass(
            self._scope, graph, 'depthwise_conv_eltwiseadd_bn_fuse_pass'
        )
625

626 627
        self._program = graph.to_program()

628
    def _collect_target_varnames(self):
629 630 631 632
        '''
        Collect the variable names for sampling, and set activation
        variables to be persistable.
        '''
633
        # TODO(juncaipeng), consider the name_scope of skip_quant
634
        _logger.info("Collect quantized variable names ...")
635
        self._quantized_op_pairs = {}
636

637
        def collect_var_name(var_name_list, persistable_var_names, op_type):
638 639 640
            for var_name in var_name_list:
                if var_name in persistable_var_names:
                    self._quantized_weight_var_name.add(var_name)
641
                    self._weight_op_pairs[var_name] = op_type
642 643 644
                else:
                    self._quantized_act_var_name.add(var_name)

645
        persistable_var_names = _all_persistable_var_names(self._program)
646 647
        for block_id in range(len(self._program.blocks)):
            for op in self._program.blocks[block_id].ops:
648 649 650 651 652 653
                # skip quant form self._skip_tensor_list
                if self._skip_tensor_list is not None:
                    for inp_name in utils._get_op_input_var_names(op):
                        if inp_name in self._skip_tensor_list:
                            op._set_attr("op_namescope", "skip_quant")

654
                op_type = op.type
655 656 657 658 659 660 661
                if (
                    self._is_full_quantize
                    and op_type not in self._quantizable_op_type
                ):
                    _logger.warning(
                        op_type + " is not supported for quantization."
                    )
662 663
                # For quantized ops, sample inputs and outputs
                if op_type in self._quantizable_op_type:
664 665 666 667 668 669 670 671 672 673
                    collect_var_name(
                        utils._get_op_input_var_names(op),
                        persistable_var_names,
                        op_type,
                    )
                    collect_var_name(
                        utils._get_op_output_var_names(op),
                        persistable_var_names,
                        op_type,
                    )
674
                    # collect quanted op output var name
675 676
                    for out_var_name in utils._get_op_output_var_names(op):
                        for in_var_name in utils._get_op_input_var_names(op):
677 678
                            if in_var_name in persistable_var_names:
                                self._quantized_op_pairs[
679 680
                                    in_var_name
                                ] = out_var_name
681 682
                # For other op, only sample output scale
                elif op_type in self._out_scale_op_list:
683 684 685 686 687
                    collect_var_name(
                        utils._get_op_output_var_names(op),
                        persistable_var_names,
                        op_type,
                    )
688 689 690

    def _set_activation_persistable(self):
        '''
691
        Set activation variables to be persistable, so can obtain
692 693
        the tensor data in sample_data
        '''
694 695 696 697
        for var in self._program.list_vars():
            if var.name in self._quantized_act_var_name:
                var.persistable = True

698 699 700 701 702 703 704
    def _reset_activation_persistable(self):
        '''
        Reset activations to be not persistable.
        '''
        for var in self._program.list_vars():
            if var.name in self._quantized_act_var_name:
                var.persistable = False
C
ceci3 已提交
705
                self._scope.find_var(var.name).get_tensor()._clear()
706

707
    def _sampling(self):
708
        '''
709
        Sample the min/max, abs_max or histogram in every iterations.
710 711
        '''
        if self._algo == "abs_max":
712
            self._sample_abs_max()
X
XGZhang 已提交
713 714
        elif self._algo == "avg":
            self._sample_avg()
715
        elif self._algo == "min_max":
716
            self._sample_min_max()
X
XGZhang 已提交
717 718
        elif self._algo == "mse":
            self._sample_mse()
719 720
        elif self._algo == "emd":
            self._sample_emd()
H
handiz 已提交
721 722
        elif self._algo == "ptf":
            self._sample_ptf()
X
XGZhang 已提交
723
        elif self._algo in ["KL", "hist"]:
724
            self._sample_histogram()
725

X
XGZhang 已提交
726 727 728
    def _sample_mse(self):
        if self._quantized_threshold == {}:
            for var_name in self._quantized_weight_var_name:
729
                var_tensor = utils.load_variable_data(self._scope, var_name)
X
XGZhang 已提交
730 731 732 733
                if self._weight_quantize_type == "abs_max":
                    abs_max_value = float(np.max(np.abs(var_tensor)))
                elif self._weight_quantize_type == "channel_wise_abs_max":
                    abs_max_value = []
734 735 736 737
                    if (
                        self._weight_op_pairs[var_name]
                        in utils._channelwise_quant_axis1_ops
                    ):
X
XGZhang 已提交
738 739
                        for i in range(var_tensor.shape[1]):
                            abs_max_value.append(
740 741
                                float(np.max(np.abs(var_tensor[:, i])))
                            )
X
XGZhang 已提交
742 743 744
                    else:
                        for i in range(var_tensor.shape[0]):
                            abs_max_value.append(
745 746
                                float(np.max(np.abs(var_tensor[i])))
                            )
X
XGZhang 已提交
747 748 749
                self._quantized_threshold[var_name] = abs_max_value
        _logger.info("MSE searching stage ...")
        for var_name in self._quantized_act_var_name:
750
            var_tensor = utils.load_variable_data(self._scope, var_name)
751 752 753
            if not var_tensor.any():
                self._zero_size_var_names.add(var_name)
                continue
X
XGZhang 已提交
754 755
            var_tensor = var_tensor.flatten()
            abs_max_value = float(np.max(np.abs(var_tensor)))
X
XGZhang 已提交
756
            abs_max_value = 1e-8 if abs_max_value == 0.0 else abs_max_value
X
XGZhang 已提交
757
            s = 0.3
758 759
            if var_name not in self._best_calibration_loss:
                self._best_calibration_loss[var_name] = float('inf')
X
XGZhang 已提交
760 761 762
            while s <= 1.0:
                scale = s * abs_max_value
                s += 0.02
763
                bins = 2 ** (self._activation_bits - 1) - 1
764
                if self._onnx_format:
765 766 767
                    quant_var = np.clip(
                        np.round(var_tensor / scale * bins), -bins - 1, bins
                    )
768 769
                    quant_dequant_var = quant_var / bins * scale
                else:
770 771 772 773 774 775
                    quant_dequant_var = (
                        np.round(np.clip(var_tensor, 0.0, scale) / scale * bins)
                        / bins
                        * scale
                    )
                mse_loss = ((var_tensor - quant_dequant_var) ** 2).mean()
776 777 778 779 780 781 782
                if mse_loss <= self._best_calibration_loss[var_name]:
                    self._best_calibration_loss[var_name] = mse_loss
                    self._quantized_threshold[var_name] = scale

    def _sample_emd(self):
        if self._quantized_threshold == {}:
            for var_name in self._quantized_weight_var_name:
783
                var_tensor = utils.load_variable_data(self._scope, var_name)
784 785 786 787
                if self._weight_quantize_type == "abs_max":
                    abs_max_value = float(np.max(np.abs(var_tensor)))
                elif self._weight_quantize_type == "channel_wise_abs_max":
                    abs_max_value = []
788 789 790 791
                    if (
                        self._weight_op_pairs[var_name]
                        in utils._channelwise_quant_axis1_ops
                    ):
792 793
                        for i in range(var_tensor.shape[1]):
                            abs_max_value.append(
794 795
                                float(np.max(np.abs(var_tensor[:, i])))
                            )
796 797 798
                    else:
                        for i in range(var_tensor.shape[0]):
                            abs_max_value.append(
799 800
                                float(np.max(np.abs(var_tensor[i])))
                            )
801 802 803
                self._quantized_threshold[var_name] = abs_max_value
        _logger.info("EMD searching stage ...")
        for var_name in self._quantized_act_var_name:
804
            var_tensor = utils.load_variable_data(self._scope, var_name)
805 806 807
            if not var_tensor.any():
                self._zero_size_var_names.add(var_name)
                continue
808 809 810 811 812 813 814 815 816
            var_tensor = var_tensor.flatten()
            abs_max_value = float(np.max(np.abs(var_tensor)))
            abs_max_value = 1e-8 if abs_max_value == 0.0 else abs_max_value
            s = 0.3
            if var_name not in self._best_calibration_loss:
                self._best_calibration_loss[var_name] = float('inf')
            while s <= 1.0:
                scale = s * abs_max_value
                s += 0.02
817
                bins = 2 ** (self._activation_bits - 1) - 1
818
                if self._onnx_format:
819 820 821
                    quant_var = np.clip(
                        np.round(var_tensor / scale * bins), -bins - 1, bins
                    )
822 823
                    quant_dequant_var = quant_var / bins * scale
                else:
824 825 826 827 828
                    quant_dequant_var = (
                        np.round(np.clip(var_tensor, 0.0, scale) / scale * bins)
                        / bins
                        * scale
                    )
829
                emd_loss = np.abs(
830 831
                    np.mean(var_tensor) - np.mean(quant_dequant_var)
                ) + np.abs(np.std(var_tensor) - np.std(quant_dequant_var))
832 833
                if emd_loss <= self._best_calibration_loss[var_name]:
                    self._best_calibration_loss[var_name] = emd_loss
X
XGZhang 已提交
834 835 836 837 838
                    self._quantized_threshold[var_name] = scale

    def _sample_avg(self):
        if self._quantized_threshold == {}:
            for var_name in self._quantized_weight_var_name:
839
                var_tensor = utils.load_variable_data(self._scope, var_name)
X
XGZhang 已提交
840 841 842 843
                if self._weight_quantize_type == "abs_max":
                    abs_max_value = float(np.max(np.abs(var_tensor)))
                elif self._weight_quantize_type == "channel_wise_abs_max":
                    abs_max_value = []
844 845 846 847
                    if (
                        self._weight_op_pairs[var_name]
                        in utils._channelwise_quant_axis1_ops
                    ):
X
XGZhang 已提交
848 849
                        for i in range(var_tensor.shape[1]):
                            abs_max_value.append(
850 851
                                float(np.max(np.abs(var_tensor[:, i])))
                            )
X
XGZhang 已提交
852 853 854
                    else:
                        for i in range(var_tensor.shape[0]):
                            abs_max_value.append(
855 856
                                float(np.max(np.abs(var_tensor[i])))
                            )
X
XGZhang 已提交
857 858 859
                self._quantized_threshold[var_name] = abs_max_value

        for var_name in self._quantized_act_var_name:
860
            var_tensor = utils.load_variable_data(self._scope, var_name)
861 862 863
            if not var_tensor.any():
                self._zero_size_var_names.add(var_name)
                continue
X
XGZhang 已提交
864
            abs_max_value = float(np.max(np.abs(var_tensor)))
865
            if var_name not in self._quantized_var_avg:
X
XGZhang 已提交
866
                self._quantized_var_avg[var_name] = []
867 868 869 870 871 872 873 874
            abs_avg_value = float(
                np.mean(
                    np.max(
                        np.abs(var_tensor.reshape(var_tensor.shape[0], -1)),
                        axis=(1),
                    )
                )
            )
X
XGZhang 已提交
875 876
            self._quantized_var_avg[var_name].append(abs_avg_value)

877
    def _sample_abs_max(self):
X
XGZhang 已提交
878
        if self._quantized_threshold == {}:
879
            for var_name in self._quantized_weight_var_name:
880
                var_tensor = utils.load_variable_data(self._scope, var_name)
881 882 883 884
                if self._weight_quantize_type == "abs_max":
                    abs_max_value = float(np.max(np.abs(var_tensor)))
                elif self._weight_quantize_type == "channel_wise_abs_max":
                    abs_max_value = []
885 886 887 888
                    if (
                        self._weight_op_pairs[var_name]
                        in utils._channelwise_quant_axis1_ops
                    ):
889 890
                        for i in range(var_tensor.shape[1]):
                            abs_max_value.append(
891 892
                                float(np.max(np.abs(var_tensor[:, i])))
                            )
893 894 895
                    else:
                        for i in range(var_tensor.shape[0]):
                            abs_max_value.append(
896 897
                                float(np.max(np.abs(var_tensor[i])))
                            )
X
XGZhang 已提交
898
                self._quantized_threshold[var_name] = abs_max_value
899 900

        for var_name in self._quantized_act_var_name:
901
            var_tensor = utils.load_variable_data(self._scope, var_name)
902 903 904
            if not var_tensor.any():
                self._zero_size_var_names.add(var_name)
                continue
905
            abs_max_value = float(np.max(np.abs(var_tensor)))
906 907 908
            if (var_name not in self._quantized_threshold) or (
                abs_max_value > self._quantized_threshold[var_name]
            ):
X
XGZhang 已提交
909
                self._quantized_threshold[var_name] = abs_max_value
910

911
    def _sample_min_max(self):
912 913
        if self._quantized_var_min == {} and self._quantized_var_max == {}:
            for var_name in self._quantized_weight_var_name:
914
                var_tensor = utils.load_variable_data(self._scope, var_name)
915 916 917 918 919 920
                if self._weight_quantize_type == "abs_max":
                    min_value = float(np.min(var_tensor))
                    max_value = float(np.max(var_tensor))
                elif self._weight_quantize_type == "channel_wise_abs_max":
                    min_value = []
                    max_value = []
921 922 923 924
                    if (
                        self._weight_op_pairs[var_name]
                        in utils._channelwise_quant_axis1_ops
                    ):
925 926 927 928 929 930 931 932 933 934 935
                        for i in range(var_tensor.shape[1]):
                            min_value.append(float(np.min(var_tensor[:, i])))
                            max_value.append(float(np.max(var_tensor[:, i])))
                    else:
                        for i in range(var_tensor.shape[0]):
                            min_value.append(float(np.min(var_tensor[i])))
                            max_value.append(float(np.max(var_tensor[i])))
                self._quantized_var_min[var_name] = min_value
                self._quantized_var_max[var_name] = max_value

        for var_name in self._quantized_act_var_name:
936
            var_tensor = utils.load_variable_data(self._scope, var_name)
937 938 939
            if not var_tensor.any():
                self._zero_size_var_names.add(var_name)
                continue
940 941
            min_value = float(np.min(var_tensor))
            max_value = float(np.max(var_tensor))
942 943 944
            if (var_name not in self._quantized_var_min) or (
                min_value < self._quantized_var_min[var_name]
            ):
945
                self._quantized_var_min[var_name] = min_value
946 947 948
            if (var_name not in self._quantized_var_max) or (
                max_value > self._quantized_var_max[var_name]
            ):
949
                self._quantized_var_max[var_name] = max_value
950

951 952
    def _sample_histogram(self):
        for var_name in self._quantized_act_var_name:
953
            var_tensor = utils.load_variable_data(self._scope, var_name)
954 955 956 957 958
            if (not var_tensor.any()) or (
                var_name not in self._sampling_act_histogram
            ):
                self._zero_size_var_names.add(var_name)
                continue
959 960 961 962 963
            var_tensor_abs = np.abs(var_tensor)
            bins = self._sampling_act_histogram[var_name][1]
            hist, _ = np.histogram(var_tensor_abs, bins=bins)
            self._sampling_act_histogram[var_name][0] += hist

H
handiz 已提交
964 965 966 967 968 969 970 971 972 973 974 975
    def _sample_ptf(self):
        """
        The following code are modified from:
        https://github.com/megvii-research/FQ-ViT/
        """
        if self._quantized_threshold == {}:
            for var_name in self._quantized_weight_var_name:
                var_tensor = utils.load_variable_data(self._scope, var_name)
                if self._weight_quantize_type == "abs_max":
                    abs_max_value = float(np.max(np.abs(var_tensor)))
                elif self._weight_quantize_type == "channel_wise_abs_max":
                    abs_max_value = []
976 977 978 979
                    if (
                        self._weight_op_pairs[var_name]
                        in utils._channelwise_quant_axis1_ops
                    ):
H
handiz 已提交
980 981
                        for i in range(var_tensor.shape[1]):
                            abs_max_value.append(
982 983
                                float(np.max(np.abs(var_tensor[:, i])))
                            )
H
handiz 已提交
984 985 986
                    else:
                        for i in range(var_tensor.shape[0]):
                            abs_max_value.append(
987 988
                                float(np.max(np.abs(var_tensor[i])))
                            )
H
handiz 已提交
989 990 991 992
                self._quantized_threshold[var_name] = abs_max_value

        for var_name in self._quantized_act_var_name:
            var_tensor = utils.load_variable_data(self._scope, var_name)
993 994 995
            if not var_tensor.any():
                self._zero_size_var_names.add(var_name)
                continue
H
handiz 已提交
996
            abs_max_value = float(np.max(np.abs(var_tensor)))
997
            q_max = 2 ** (self._activation_bits - 1) - 1
H
handiz 已提交
998 999 1000 1001
            scale8 = abs_max_value / q_max
            scale4 = scale8 / 2
            scale2 = scale4 / 2
            scale1 = scale2 / 2
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
            quant_dequant_var_scale1 = (
                np.clip(np.round(var_tensor / scale1), 0, q_max) * scale1
            )
            quant_dequant_var_scale2 = (
                np.clip(np.round(var_tensor / scale2), 0, q_max) * scale2
            )
            quant_dequant_var_scale4 = (
                np.clip(np.round(var_tensor / scale4), 0, q_max) * scale4
            )
            quant_dequant_var_scale8 = (
                np.clip(np.round(var_tensor / scale8), 0, q_max) * scale8
            )
1014 1015 1016 1017
            score1 = utils.l2_loss(var_tensor, quant_dequant_var_scale1)
            score2 = utils.l2_loss(var_tensor, quant_dequant_var_scale2)
            score4 = utils.l2_loss(var_tensor, quant_dequant_var_scale4)
            score8 = utils.l2_loss(var_tensor, quant_dequant_var_scale8)
H
handiz 已提交
1018
            score = [score1, score2, score4, score8]
1019
            mask = 2 ** score.index(min(score))
H
handiz 已提交
1020 1021 1022 1023
            scale = scale1 * mask
            threshold = q_max * scale
            self._quantized_threshold[var_name] = threshold

1024 1025 1026 1027
    def _save_input_threhold(self):
        '''
        Save input threshold to the quantized op.
        '''
1028 1029 1030
        assert (
            self._algo == "min_max"
        ), "The algo should be min_max to save input threshold."
1031 1032 1033
        for block_id in range(len(self._program.blocks)):
            for op in self._program.blocks[block_id].ops:
                if op.type in self._quantizable_op_type:
1034
                    for var_name in utils._get_op_input_var_names(op):
1035 1036
                        assert var_name in self._quantized_var_min
                        assert var_name in self._quantized_var_max
1037 1038 1039 1040 1041 1042
                        op._set_attr(
                            var_name + ".min", self._quantized_var_min[var_name]
                        )
                        op._set_attr(
                            var_name + ".max", self._quantized_var_max[var_name]
                        )
1043
                        op._set_attr("with_quant_attr", True)
1044

1045
    def _collect_activation_abs_min_max(self):
1046
        '''
1047 1048
        Collect the abs_min and abs_max for all activation. When algo = KL,
        get the min and max value, and then calculate the threshold.
1049
        '''
1050
        for var_name in self._quantized_act_var_name:
1051
            var_tensor = utils.load_variable_data(self._scope, var_name)
1052 1053 1054
            if not var_tensor.any():
                self._zero_size_var_names.add(var_name)
                continue
1055 1056 1057 1058
            var_tensor = np.abs(var_tensor)
            min_value = float(np.min(var_tensor))
            max_value = float(np.max(var_tensor))
            if var_name not in self._sampling_act_abs_min_max:
1059
                self._sampling_act_abs_min_max[var_name] = [
1060 1061
                    min_value,
                    max_value,
1062
                ]
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
            else:
                if min_value < self._sampling_act_abs_min_max[var_name][0]:
                    self._sampling_act_abs_min_max[var_name][0] = min_value
                if max_value > self._sampling_act_abs_min_max[var_name][1]:
                    self._sampling_act_abs_min_max[var_name][1] = max_value

    def _init_sampling_act_histogram(self):
        '''
        Based on the min/max value, init the sampling_act_histogram.
        '''
        for var_name in self._quantized_act_var_name:
1074 1075 1076 1077
            if (var_name in self._zero_size_var_names) and (
                var_name not in self._sampling_act_abs_min_max
            ):
                continue
1078 1079 1080
            if var_name not in self._sampling_act_histogram:
                min_val = self._sampling_act_abs_min_max[var_name][0]
                max_val = self._sampling_act_abs_min_max[var_name][1]
1081 1082 1083
                hist, hist_edeges = np.histogram(
                    [], bins=self._histogram_bins, range=(min_val, max_val)
                )
1084
                self._sampling_act_histogram[var_name] = [hist, hist_edeges]
1085

X
XGZhang 已提交
1086
    def _calculate_kl_hist_threshold(self):
1087
        '''
X
XGZhang 已提交
1088
        Calculate the KL or hist threshold of quantized variables.
1089
        '''
X
XGZhang 已提交
1090 1091
        _logger.info("Calculate {} threshold ...".format(self._algo))
        assert self._algo in ["KL", "hist"], "The algo should be KL or hist."
1092 1093

        # Abs_max threshold for weights
1094
        for var_name in self._quantized_weight_var_name:
1095
            weight_data = utils.load_variable_data(self._scope, var_name)
1096
            if self._weight_quantize_type == "abs_max":
1097
                weight_threshold = float(np.max(np.abs(weight_data)))
1098 1099
            elif self._weight_quantize_type == "channel_wise_abs_max":
                weight_threshold = []
1100 1101 1102 1103
                if (
                    self._weight_op_pairs[var_name]
                    in utils._channelwise_quant_axis1_ops
                ):
1104 1105
                    for i in range(weight_data.shape[1]):
                        weight_threshold.append(
1106 1107
                            float(np.max(np.abs(weight_data[:, i])))
                        )
1108 1109 1110
                else:
                    for i in range(weight_data.shape[0]):
                        weight_threshold.append(
1111 1112
                            float(np.max(np.abs(weight_data[i])))
                        )
X
XGZhang 已提交
1113
            self._quantized_var_threshold[var_name] = weight_threshold
1114

1115
        for var_name in self._quantized_act_var_name:
1116 1117 1118 1119
            if (var_name in self._zero_size_var_names) and (
                var_name not in self._sampling_act_histogram
            ):
                continue
1120
            hist, hist_edeges = self._sampling_act_histogram[var_name]
X
XGZhang 已提交
1121
            if self._algo == "KL":
1122
                bin_width = hist_edeges[1] - hist_edeges[0]
1123 1124 1125
                self._quantized_var_threshold[var_name] = cal_kl_threshold(
                    hist, bin_width, self._activation_bits
                )
X
XGZhang 已提交
1126
            elif self._algo == "hist":
1127 1128 1129
                self._quantized_var_threshold[
                    var_name
                ] = self._get_hist_scaling_factor(hist, hist_edeges)
1130 1131 1132

    def _update_program(self):
        '''
1133 1134
        Use QuantizationTransformPass and AddQuantDequantPass to insert
        fake_quantize, fake_dequantize and fake_quant_dequant op.
X
XGZhang 已提交
1135
        Besides, save all threshold to the scale var node.
1136
        '''
1137
        _logger.info("Update the program ...")
1138 1139
        graph = IrGraph(core.Graph(self._program.desc), for_test=True)

1140
        # use QuantizationTransformPass to insert fake_quant/fake_dequantize op
1141
        major_quantizable_op_types = []
1142
        for op_type in utils._weight_supported_quantizable_op_type:
1143
            if op_type in self._quantizable_op_type:
1144
                major_quantizable_op_types.append(op_type)
1145 1146 1147 1148 1149 1150 1151 1152
        if not self._onnx_format:
            transform_pass = QuantizationTransformPass(
                scope=self._scope,
                place=self._place,
                weight_bits=self._weight_bits,
                activation_bits=self._activation_bits,
                activation_quantize_type=self._activation_quantize_type,
                weight_quantize_type=self._weight_quantize_type,
1153 1154
                quantizable_op_type=major_quantizable_op_types,
            )
1155 1156 1157 1158 1159 1160 1161 1162
        else:
            transform_pass = QuantizationTransformPassV2(
                scope=self._scope,
                place=self._place,
                weight_bits=self._weight_bits,
                activation_bits=self._activation_bits,
                activation_quantize_type=self._activation_quantize_type,
                weight_quantize_type=self._weight_quantize_type,
1163 1164
                quantizable_op_type=major_quantizable_op_types,
            )
1165 1166 1167 1168 1169 1170

        for sub_graph in graph.all_sub_graphs():
            # Insert fake_quant/fake_dequantize op must in test graph, so
            # set per graph's _for_test is True.
            sub_graph._for_test = True
            transform_pass.apply(sub_graph)
1171 1172

        # use AddQuantDequantPass to insert fake_quant_dequant op
1173
        minor_quantizable_op_types = []
1174
        for op_type in utils._act_supported_quantizable_op_type:
1175
            if op_type in self._quantizable_op_type:
1176
                minor_quantizable_op_types.append(op_type)
1177 1178 1179 1180
        if not self._onnx_format:
            add_quant_dequant_pass = AddQuantDequantPass(
                scope=self._scope,
                place=self._place,
1181 1182
                quantizable_op_type=minor_quantizable_op_types,
            )
1183 1184 1185 1186 1187
        else:
            add_quant_dequant_pass = AddQuantDequantPassV2(
                scope=self._scope,
                place=self._place,
                quantizable_op_type=minor_quantizable_op_types,
1188 1189
                is_full_quantized=True,
            )
1190 1191 1192 1193

        for sub_graph in graph.all_sub_graphs():
            sub_graph._for_test = True
            add_quant_dequant_pass.apply(sub_graph)
1194

X
XGZhang 已提交
1195
        # save threshold to scale var node
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        if self._scale_dict is None:
            if self._algo in ["KL", "hist"]:
                scale_dict = self._quantized_var_threshold
            else:
                scale_dict = self._quantized_threshold

            if self._same_scale_tensor_list is not None:
                for tensor_list in self._same_scale_tensor_list:
                    max_scale = None
                    for tensor_name in tensor_list:
                        if '#' in tensor_name:
                            real_tensor_name, opera, scalar = tensor_name.split(
1208 1209
                                '#'
                            )
1210 1211
                            if real_tensor_name not in scale_dict.keys():
                                continue
1212 1213
                            if opera == '*':
                                scale_dict[real_tensor_name] = float(
1214 1215
                                    scale_dict[real_tensor_name]
                                ) * float(scalar)
1216 1217
                            elif opera == '/':
                                scale_dict[real_tensor_name] = float(
1218 1219 1220 1221 1222 1223 1224 1225 1226
                                    scale_dict[real_tensor_name]
                                ) / float(scalar)
                            max_scale = (
                                scale_dict[real_tensor_name]
                                if max_scale is None
                                else max(
                                    max_scale, scale_dict[real_tensor_name]
                                )
                            )
1227
                        else:
1228 1229
                            if tensor_name not in scale_dict.keys():
                                continue
1230 1231 1232 1233 1234
                            max_scale = (
                                scale_dict[tensor_name]
                                if max_scale is None
                                else max(max_scale, scale_dict[tensor_name])
                            )
1235 1236 1237 1238

                    for tensor_name in tensor_list:
                        if '#' in tensor_name:
                            real_tensor_name, opera, scalar = tensor_name.split(
1239 1240
                                '#'
                            )
1241 1242
                            if real_tensor_name not in scale_dict.keys():
                                continue
1243 1244
                            if opera == '*':
                                scale_dict[
1245 1246
                                    real_tensor_name
                                ] = max_scale / float(scalar)
1247 1248
                            elif opera == '/':
                                scale_dict[
1249 1250
                                    real_tensor_name
                                ] = max_scale * float(scalar)
1251
                        else:
1252 1253
                            if tensor_name not in scale_dict.keys():
                                continue
1254 1255 1256 1257
                            scale_dict[tensor_name] = max_scale
            self._scale_dict = scale_dict

        for key, val in self._scale_dict.items():
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
            utils.set_variable_data(
                self._scope,
                self._place,
                key + "@scale",
                np.array([val], dtype=np.float32),
            )
            utils.set_variable_data(
                self._scope,
                self._place,
                key + ".quant_dequant@scale",
                np.array([val], dtype=np.float32),
            )
1270

1271 1272
        if not self._onnx_format:
            # apply QuantizationFreezePass, and obtain the final quant model
1273 1274 1275 1276 1277 1278 1279 1280 1281
            if self._freeze_model:
                freeze_pass = QuantizationFreezePass(
                    scope=self._scope,
                    place=self._place,
                    bias_correction=self._bias_correction,
                    weight_bits=self._weight_bits,
                    round_type=self._round_type,
                    activation_bits=self._activation_bits,
                    weight_quantize_type=self._weight_quantize_type,
1282 1283
                    quantizable_op_type=major_quantizable_op_types,
                )
1284 1285 1286 1287

                for sub_graph in graph.all_sub_graphs():
                    sub_graph._for_test = True
                    freeze_pass.apply(sub_graph)
1288 1289 1290 1291 1292
        else:
            quant_weight_pass = QuantWeightPass(self._scope, self._place)
            for sub_graph in graph.all_sub_graphs():
                sub_graph._for_test = True
                quant_weight_pass.apply(sub_graph)
1293

1294 1295
        self._program = graph.to_program()

1296
    def _save_output_threshold(self):
1297
        '''
1298
        Save output threshold to the quantized op.
1299
        '''
1300
        self._calibration_scales = {}
1301

1302
        def save_info(
1303 1304 1305 1306 1307 1308
            op_node,
            out_var_name,
            threshold_map,
            out_info_name,
            argname_index,
            quantized_type,
1309
        ):
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
            if (out_var_name in self._zero_size_var_names) and (
                out_var_name not in threshold_map
            ):
                _logger.warning(
                    "{} is zero-size tensor and unable to calibrate, so skip quant it.".format(
                        out_var_name
                    )
                )
                return
            else:
                assert (
                    out_var_name in threshold_map
                ), "The output ({}) of {} node does not have threshold.".format(
                    out_var_name, op_node.type
                )
1325 1326
            if self._onnx_format:
                # For easy extension, every var_node set a dict to save parameters of quant.
1327 1328 1329
                self._calibration_scales[out_var_name] = {}
                self._calibration_scales[out_var_name]['scale'] = threshold_map[
                    out_var_name
1330
                ]
1331
            else:
1332 1333 1334 1335 1336
                op_node._set_attr(out_info_name, threshold_map[out_var_name])
                op_node._set_attr(
                    argname_index[0] + str(argname_index[1]) + "_threshold",
                    threshold_map[out_var_name],
                )
1337 1338 1339
                op_node._set_attr("with_quant_attr", True)
                if op_node.type in self._quantizable_op_type:
                    op._set_attr("quantization_type", quantized_type)
1340 1341

        def analysis_and_save_info(op_node, out_var_name):
1342
            argname_index = utils._get_output_name_index(op_node, out_var_name)
1343
            assert argname_index is not None, (
1344
                out_var_name + " is not the output of the op"
1345
            )
1346
            if self._algo in ["KL", "hist"]:
X
XGZhang 已提交
1347
                # For compatibility, we save output threshold by two methods.
1348
                save_info(
1349 1350 1351 1352
                    op_node,
                    out_var_name,
                    self._quantized_var_threshold,
                    "out_threshold",
1353 1354
                    argname_index,
                    "post_" + str(self._algo).lower(),
1355
                )
H
handiz 已提交
1356
            elif self._algo in ["avg", "abs_max", "mse", "emd", "ptf"]:
X
XGZhang 已提交
1357
                save_info(
1358 1359 1360 1361
                    op_node,
                    out_var_name,
                    self._quantized_threshold,
                    "out_threshold",
1362
                    argname_index,
1363 1364
                    "post_" + str(self._algo),
                )
1365
            elif self._algo == "min_max":
1366 1367 1368 1369 1370
                save_info(
                    op_node,
                    out_var_name,
                    self._quantized_var_min,
                    "out_min",
1371
                    argname_index,
1372 1373 1374 1375 1376 1377 1378
                    "post_min_max",
                )
                save_info(
                    op_node,
                    out_var_name,
                    self._quantized_var_max,
                    "out_max",
1379
                    argname_index,
1380 1381
                    "post_min_max",
                )
1382

1383 1384
        for block_id in range(len(self._program.blocks)):
            for op in self._program.blocks[block_id].ops:
1385 1386 1387
                if op.type in (
                    self._quantizable_op_type + self._out_scale_op_list
                ):
1388
                    out_var_names = utils._get_op_output_var_names(op)
1389 1390
                    for var_name in out_var_names:
                        analysis_and_save_info(op, var_name)
1391

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
    def _collect_dynamic_quantize_op_threshold(self, target_ops_type):
        """
        Collect and save the weight threshold for dynamic quantize ops,
        such as lstm and gru.
        Args:
            target_ops_type(list): the op type of target ops
        Returns:
            None
        """

        target_ops = []
        for index in range(self._program.num_blocks):
            for op in self._program.block(index).ops:
                if op.type in target_ops_type:
                    target_ops.append(op)

        quantization_type = str("post_" + self._algo).lower()
        persistable_var_names = _all_persistable_var_names(self._program)
        for op in target_ops:
1411
            for var_name in utils._get_op_input_var_names(op):
1412
                if var_name in persistable_var_names:
1413
                    var_data = utils.load_variable_data(self._scope, var_name)
1414
                    threshold = float(np.max(np.abs(var_data)))
1415
                    argname, index = utils._get_input_name_index(op, var_name)
1416 1417 1418
                    op._set_attr(argname + str(index) + "_threshold", threshold)
                    op._set_attr("quantization_type", quantization_type)
                    op._set_attr("bit_length", self._weight_bits)
1419
                    op._set_attr("with_quant_attr", True)
1420

X
XGZhang 已提交
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    def _get_hist_scaling_factor(self, hist, hist_edges):
        '''
        Using the hist method to get the scaling factor.
        '''
        threshold_rate = self._hist_percent
        hist = hist / float(sum(hist))
        hist_sum = 0
        hist_index = 0
        for i in range(len(hist)):
            hist_sum += hist[i]
            if hist_sum >= threshold_rate:
                hist_index = i + 1
                break
        bin_width = hist_edges[1] - hist_edges[0]
        return (hist_index - 0.5) * bin_width

1437

1438
class PostTrainingQuantizationProgram(PostTrainingQuantization):
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
    def __init__(
        self,
        executor,
        program,
        feed_list=None,
        fetch_list=None,
        scope=None,
        batch_generator=None,
        sample_generator=None,
        data_loader=None,
        batch_size=10,
        batch_nums=None,
        algo="KL",
        hist_percent=0.99999,
        quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"],
        round_type='round',
        learning_rate=0.001,
        is_full_quantize=False,
        bias_correction=False,
        activation_bits=8,
        weight_bits=8,
        activation_quantize_type='range_abs_max',
        weight_quantize_type='channel_wise_abs_max',
        onnx_format=False,
        freeze_model=True,
        optimize_model=False,
        is_use_cache_file=False,
        skip_tensor_list=None,
        same_scale_tensor_list=None,
        cache_dir=None,
        scale_dict=None,
        return_graph=True,
    ):
        super().__init__(
            executor,
            scope,
            None,
            None,
            None,
            batch_generator,
            sample_generator,
            data_loader,
            batch_size,
            batch_nums,
            algo,
            hist_percent,
            quantizable_op_type,
            round_type,
            learning_rate,
            is_full_quantize,
            bias_correction,
            activation_bits,
            weight_bits,
            activation_quantize_type,
            weight_quantize_type,
            onnx_format,
            freeze_model,
            optimize_model,
            is_use_cache_file,
            skip_tensor_list,
            same_scale_tensor_list,
            cache_dir,
            scale_dict,
            return_graph,
        )
1504
        self.FLAG = False
1505
        self._program = program
1506 1507
        if self._program is not None:
            self.FLAG = True
1508 1509
        assert feed_list is not None, "Feed list should not be None."
        assert fetch_list is not None, "Fetch list should not be None."
1510 1511 1512 1513
        self._feed_list = feed_list
        self._fetch_list = fetch_list


1514
class WeightQuantization:
1515
    _supported_quantizable_op_type = ['conv2d', 'depthwise_conv2d', 'mul']
1516
    _supported_weight_quantize_type = ['channel_wise_abs_max', 'abs_max']
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537

    def __init__(self, model_dir, model_filename=None, params_filename=None):
        '''
        This class quantizes the weight of some ops to reduce the size of model
        or improve the perforemace.

        Args:
            model_dir(str): The path of the fp32 model that will be quantized,
                and the model and params files are under the path.
            model_filename(str, optional): The name of file to load the inference
                program. If it is None, the default filename '__model__' will
                be used. Default is 'None'.
            params_filename(str, optional): The name of file to load all parameters.
                When all parameters were saved in a single binary file, set it
                as the real filename. If parameters were saved in separate files,
                set it as 'None'. Default is 'None'.
        '''
        self._model_dir = model_dir
        self._model_filename = model_filename
        self._params_filename = params_filename

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
    def quantize_weight_to_int(
        self,
        save_model_dir,
        save_model_filename=None,
        save_params_filename=None,
        quantizable_op_type=["conv2d", "mul"],
        weight_bits=8,
        weight_quantize_type="channel_wise_abs_max",
        generate_test_model=False,
        threshold_rate=0.0,
    ):
1549 1550
        '''
        In order to reduce the size of model, this api quantizes the weight
1551
        of some ops from float32 to int8/16. In the inference stage, the
1552
        quantized weight will be dequantized to float32 again.
1553

1554 1555
        Args:
            save_model_dir(str): The path to save the quantized model.
1556 1557
            save_model_filename(str, optional): The name of file to
                save the inference program. If it is None, the default
1558
                filename '__model__' will be used. Default is 'None'.
1559 1560 1561
            save_params_filename(str, optional): The name of file to
                save all parameters. If it is None, parameters were
                saved in separate files. If it is not None, all
1562
                parameters were saved in a single binary file.
1563
            quantizable_op_type(list[str], optional): The list of ops
1564
                that will be quantized, and the quantized ops should be
1565
                contained in ["conv2d", "depthwise_conv2d", "mul"].
1566
                Default is ["conv2d","mul"].
1567
            weight_bits(int, optional): The bits for the quantized weight,
1568
                and it should be 8 or 16. Default is 8.
1569 1570 1571
            weight_quantize_type(str, optional): quantization type for weights,
                support 'channel_wise_abs_max' and 'abs_max'. Set it as
                'channel_wise_abs_max', the accuracy performs better.
1572 1573 1574
            generate_test_model(bool, optional): If set generate_test_model
                as True, it saves a fake quantized model, in which the weights
                are quantized and dequantized. We can use PaddlePaddle to load
1575
                the fake quantized model and test the accuracy on GPU or CPU.
1576 1577 1578 1579 1580
            threshold_rate(float, optional): This api uses abs_max methd to
                quantize the weight from float32 to int8/16, and the abs max
                value is important for quantization diff. When the abs_max
                value is far away from the center of the numerical distribution,
                we can set threshold_rate between 1e-6 and 1e-8, so the abs max
1581 1582 1583
                value will be optimized. Default is 0.0.
        '''
        for op_type in quantizable_op_type:
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
            assert op_type in self._supported_quantizable_op_type, (
                "Input error:"
                + op_type
                + " is not supported for weight quantization."
            )
        assert weight_bits in [
            8,
            16,
        ], "Input error: weight_bits should be 8 or 16."
        assert (
            weight_quantize_type in self._supported_weight_quantize_type
        ), "Input error: weight_quantize_type should in {}".format(
            self._supported_weight_quantize_type
        )
1598 1599

        quantized_model_dir = os.path.join(save_model_dir, "quantized_model")
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
        self._quantize_weight_to_int(
            quantized_model_dir,
            save_model_filename,
            save_params_filename,
            quantizable_op_type,
            weight_bits,
            weight_quantize_type,
            False,
            threshold_rate,
        )
1610 1611 1612

        if generate_test_model:
            test_model_dir = os.path.join(save_model_dir, "test_model")
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
            self._quantize_weight_to_int(
                test_model_dir,
                save_model_filename,
                save_params_filename,
                quantizable_op_type,
                weight_bits,
                weight_quantize_type,
                True,
                threshold_rate,
            )
1623

1624 1625 1626 1627
    def convert_weight_to_fp16(self, save_model_dir):
        """
        Convert all presistable vars from fp32 to fp16.
        Note that, this api only changes the data type of variables in
1628
        __params__ file, and the __model__ file remains unchanged.
1629 1630 1631 1632 1633 1634 1635

        Args:
            save_model_dir(str): The path to save the fp16 model.
        """

        # Load model
        place = core.CPUPlace()
1636 1637 1638 1639
        exe = static.Executor(place)
        scope = static.global_scope()
        [infer_program, feed_list, fetch_list] = static.load_inference_model(
            self._model_dir,
1640 1641 1642 1643
            executor=exe,
            model_filename=self._model_filename,
            params_filename=self._params_filename,
        )
1644 1645

        # Clone and save fp16 weights
1646
        save_program = static.Program()
1647 1648 1649 1650
        save_block = save_program.global_block()
        save_var_map = {}

        for var in infer_program.list_vars():
1651 1652 1653 1654 1655 1656
            if (
                (var.type == core.VarDesc.VarType.RAW)
                or (not var.persistable)
                or (var.name in ['feed', 'fetch'])
                or (var.dtype != core.VarDesc.VarType.FP32)
            ):
1657 1658
                continue

1659
            # new_var = _clone_var_to_block_(var, save_block)
1660 1661 1662 1663
            new_var = save_block._clone_variable(var)
            if self._params_filename is not None:
                save_var_map[new_var.name] = new_var
            else:
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
                save_file_path = os.path.join(
                    os.path.normpath(save_model_dir), new_var.name
                )
                save_block.append_op(
                    type='save',
                    inputs={'X': [new_var]},
                    outputs={},
                    attrs={
                        'file_path': os.path.normpath(save_file_path),
                        'save_as_fp16': True,
                    },
                )
1676 1677 1678 1679 1680 1681 1682 1683

        if self._params_filename is not None:
            save_var_list = []
            for name in sorted(save_var_map.keys()):
                save_var_list.append(save_var_map[name])

            saved_params_var = save_block.create_var(
                type=core.VarDesc.VarType.RAW,
1684 1685
                name=unique_name.generate("saved_params"),
            )
1686 1687
            saved_params_var.desc.set_persistable(True)

1688 1689 1690 1691 1692 1693 1694 1695 1696
            save_path = os.path.join(
                os.path.normpath(save_model_dir), self._params_filename
            )
            save_block.append_op(
                type='save_combine',
                inputs={'X': save_var_list},
                outputs={'Y': saved_params_var},
                attrs={'file_path': save_path, 'save_as_fp16': True},
            )
1697 1698 1699 1700 1701

        save_program._sync_with_cpp()
        exe.run(save_program)

        # Copy model
1702 1703 1704 1705 1706
        model_filename = (
            "__model__"
            if self._model_filename is None
            else self._model_filename
        )
1707 1708 1709 1710
        src_model = os.path.join(self._model_dir, model_filename)
        dest_model = os.path.join(save_model_dir, model_filename)
        shutil.copyfile(src_model, dest_model)

1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
    def _quantize_weight_to_int(
        self,
        save_model_dir,
        save_model_filename,
        save_params_filename,
        quantizable_op_type,
        weight_bits,
        weight_quantize_type,
        for_test,
        threshold_rate,
    ):
1722 1723 1724 1725
        """
        Generate quantized model or fake quantized model.
        """
        # Load model
1726
        place = core.CPUPlace()
1727 1728 1729 1730
        exe = static.Executor(place)
        scope = static.global_scope()
        [program, feed_list, fetch_list] = static.load_inference_model(
            self._model_dir,
1731 1732 1733 1734
            executor=exe,
            model_filename=self._model_filename,
            params_filename=self._params_filename,
        )
1735

1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
        quantized_ops = []
        for index in range(program.num_blocks):
            block = program.block(index)
            for op in block.ops:
                if op.type in quantizable_op_type:
                    quantized_ops.append(op)

        # Quantize weights
        persistable_var_names = _all_persistable_var_names(program)
        for op in quantized_ops:
            for var_name in op.input_arg_names:
                if var_name in persistable_var_names:
                    if weight_quantize_type == "abs_max":
                        self._weight_abs_max_quantization(
1750 1751 1752 1753 1754 1755 1756 1757
                            scope,
                            place,
                            weight_bits,
                            threshold_rate,
                            op,
                            var_name,
                            for_test,
                        )
1758 1759
                    elif weight_quantize_type == "channel_wise_abs_max":
                        self._weight_channel_wise_abs_max_quantization(
1760 1761
                            scope, place, weight_bits, op, var_name, for_test
                        )
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
        model_name = None
        if save_model_filename is None:
            model_name = "model"
        elif save_model_filename.endswith(".pdmodel"):
            model_name = save_model_filename.rsplit(".", 1)[0]
        else:
            model_name = save_model_filename

        path_prefix = os.path.join(save_model_dir, model_name)
        feed_vars = [program.global_block().var(name) for name in feed_list]
        static.save_inference_model(
            path_prefix,
            feed_vars,
            fetch_list,
1776
            executor=exe,
1777
            program=program,
1778 1779 1780 1781 1782
        )

    def _weight_abs_max_quantization(
        self, scope, place, weight_bits, threshold_rate, op, var_name, for_test
    ):
1783 1784 1785 1786 1787 1788 1789
        '''
        Use abs_max method to quantize weight.
        '''
        quantize_range = (1 << (weight_bits - 1)) - 1
        save_weight_dtype = np.int8 if weight_bits == 8 else np.int16

        # Get quantized scale and weight data
1790
        weight_data = utils.load_variable_data(scope, var_name)
1791 1792 1793
        if abs(threshold_rate) < 1e-10:
            threshold_value = np.max(np.abs(weight_data))
        else:
1794 1795 1796
            threshold_value = self._calculate_threshold(
                weight_data, threshold_rate
            )
1797 1798 1799
            weight_data[weight_data > threshold_value] = threshold_value
            weight_data[weight_data < -threshold_value] = -threshold_value
        scale = threshold_value / quantize_range
1800 1801 1802
        quantized_weight_data = np.around(weight_data / scale).astype(
            save_weight_dtype
        )
1803 1804 1805

        # Set weight data
        if not for_test:
1806 1807 1808
            utils.set_variable_data(
                scope, place, var_name, quantized_weight_data
            )
1809
        else:
1810 1811 1812 1813 1814 1815
            dequantized_weight_data = (quantized_weight_data * scale).astype(
                np.float32
            )
            utils.set_variable_data(
                scope, place, var_name, dequantized_weight_data
            )
1816 1817 1818 1819 1820

        # Save info
        op._set_attr('quantization_type', 'post_weight_abs_max')
        op._set_attr('quantize_weight_bits', weight_bits)
        op._set_attr(var_name + "_quant_scale", [scale])  # Save as list
1821
        op._set_attr("with_quant_attr", True)
1822

1823 1824 1825
    def _weight_channel_wise_abs_max_quantization(
        self, scope, place, weight_bits, op, var_name, for_test
    ):
1826
        '''
1827 1828 1829 1830 1831 1832
        Use channel_wise_abs_max method to quantize weight.
        '''
        quantize_range = (1 << (weight_bits - 1)) - 1
        save_weight_dtype = np.int8 if weight_bits == 8 else np.int16

        # Get quantized scale and weight data
1833
        weight_data = utils.load_variable_data(scope, var_name)
1834
        if op.type == "mul":
1835 1836 1837
            scales, quantized_weight_data = self._mul_channel_wise_quantization(
                weight_data, quantize_range, save_weight_dtype
            )
1838
        elif op.type in ["conv2d", "depthwise_conv2d"]:
1839 1840 1841 1842 1843 1844
            (
                scales,
                quantized_weight_data,
            ) = self._conv_channel_wise_quantization(
                weight_data, quantize_range, save_weight_dtype
            )
1845 1846 1847 1848 1849
        else:
            _logger.error(op.type + " is not supported by weight quantization")

        # Set weight data
        if not for_test:
1850 1851 1852
            utils.set_variable_data(
                scope, place, var_name, quantized_weight_data
            )
1853 1854
        else:
            if op.type == "mul":
1855 1856 1857
                dequantized_weight_data = self._mul_channel_wise_dequantization(
                    quantized_weight_data, scales
                )
1858
            elif op.type in ["conv2d", "depthwise_conv2d"]:
1859 1860 1861 1862 1863
                dequantized_weight_data = (
                    self._conv_channel_wise_dequantization(
                        quantized_weight_data, scales
                    )
                )
1864
            else:
1865 1866 1867 1868 1869 1870
                _logger.error(
                    op.type + " is not supported by weight quantization"
                )
            utils.set_variable_data(
                scope, place, var_name, dequantized_weight_data
            )
1871 1872 1873 1874 1875

        # Save info
        op._set_attr('quantization_type', 'post_weight_channel_wise_abs_max')
        op._set_attr('quantize_weight_bits', weight_bits)
        op._set_attr(var_name + "_quant_scale", scales)
1876
        op._set_attr("with_quant_attr", True)
1877

1878 1879 1880
    def _conv_channel_wise_quantization(
        self, weight_data, quantize_range, save_weight_dtype
    ):
1881 1882 1883 1884 1885
        '''
        Get channel wise scale for the weights of conv2d and depthwise_conv2d,
        and quantize the weights.
        '''
        scales = []
1886 1887 1888
        quantized_weight_data = np.zeros_like(
            weight_data, dtype=save_weight_dtype
        )
1889 1890 1891 1892
        channel_num = weight_data.shape[0]
        for i in range(channel_num):
            scale = np.max(np.abs(weight_data[i])) / quantize_range
            scales.append(scale)
1893 1894 1895
            quantized_weight_data[i] = np.around(weight_data[i] / scale).astype(
                save_weight_dtype
            )
1896 1897 1898 1899 1900 1901
        return scales, quantized_weight_data

    def _conv_channel_wise_dequantization(self, quantized_weight_data, scales):
        '''
        For conv2d and depthwise_conv2d, dequantize the weights to fp32.
        '''
1902 1903 1904
        dequantized_weight_data = np.zeros_like(
            quantized_weight_data, dtype=np.float32
        )
1905
        for i in range(len(scales)):
1906 1907 1908
            dequantized_weight_data[i] = (
                quantized_weight_data[i] * scales[i]
            ).astype(np.float32)
1909 1910
        return dequantized_weight_data

1911 1912 1913
    def _mul_channel_wise_quantization(
        self, weight_data, quantize_range, save_weight_dtype
    ):
1914 1915 1916 1917 1918
        '''
        Get channel wise scale for the weights of conv2d and depthwise_conv2d,
        and quantize the weights.
        '''
        scales = []
1919 1920 1921
        quantized_weight_data = np.zeros_like(
            weight_data, dtype=save_weight_dtype
        )
1922 1923 1924 1925
        channel_num = weight_data.shape[-1]
        for i in range(channel_num):
            scale = np.max(np.abs(weight_data[:, i])) / quantize_range
            scales.append(scale)
1926 1927 1928
            quantized_weight_data[:, i] = np.around(
                weight_data[:, i] / scale
            ).astype(save_weight_dtype)
1929 1930 1931 1932 1933 1934
        return scales, quantized_weight_data

    def _mul_channel_wise_dequantization(self, quantized_weight_data, scales):
        '''
        For mul, dequantize the weights to fp32.
        '''
1935 1936 1937
        dequantized_weight_data = np.zeros_like(
            quantized_weight_data, dtype=np.float32
        )
1938
        for i in range(len(scales)):
1939 1940 1941
            dequantized_weight_data[:, i] = (
                quantized_weight_data[:, i] * scales[i]
            ).astype(np.float32)
1942 1943
        return dequantized_weight_data

1944 1945
    def _calculate_threshold(self, input, threshold_rate, histogram_bins=5000):
        input_abs = np.abs(input)
1946 1947 1948
        hist, hist_edeges = np.histogram(
            input_abs, bins=histogram_bins, range=(0, np.max(input_abs))
        )
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
        hist = hist / float(sum(hist))
        hist_sum = 0
        hist_index = 0
        for i in range(len(hist)):
            hist_sum += hist[i]
            if hist_sum >= 1.0 - threshold_rate:
                hist_index = i + 1
                break
        bin_width = hist_edeges[1] - hist_edeges[0]
        return hist_index * bin_width