post_training_quantization.py 35.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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 math
15 16
import os
import re
17 18 19 20 21
import logging
import numpy as np
from .... import io
from .... import core
from .... import framework
22
from ....executor import global_scope, Executor
23 24 25 26 27
from ....framework import IrGraph
from ....log_helper import get_logger
from .quantization_pass import QuantizationTransformPass
from .quantization_pass import QuantizationFreezePass
from .quantization_pass import AddQuantDequantPass
28
from .quantization_pass import _op_real_in_out_name
29

30
__all__ = ['PostTrainingQuantization', 'WeightQuantization']
31 32 33 34 35

_logger = get_logger(
    __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s')


36 37 38 39
def _load_variable_data(scope, var_name):
    '''
    Load variable value from scope
    '''
40 41 42 43
    var_node = scope.find_var(var_name)
    assert var_node is not None, \
        "Cannot find " + var_name + " in scope."
    return np.array(var_node.get_tensor())
44 45 46 47 48 49 50 51 52 53 54 55 56 57


def _set_variable_data(scope, place, var_name, np_value):
    '''
    Set the value of var node by name, if the node exits,
    '''
    assert isinstance(np_value, np.ndarray), \
        'The type of value should be numpy array.'
    var_node = scope.find_var(var_name)
    if var_node != None:
        tensor = var_node.get_tensor()
        tensor.set(np_value, place)


58
class PostTrainingQuantization(object):
59 60 61 62 63 64
    """
    Utilizing post training quantization methon to quantize the FP32 model,
    and it uses calibrate data to get the quantization information for all 
    quantized variables.
    """

65
    def __init__(self,
66 67 68
                 executor=None,
                 scope=None,
                 model_dir=None,
69 70
                 model_filename=None,
                 params_filename=None,
71
                 sample_generator=None,
72 73 74
                 batch_size=10,
                 batch_nums=None,
                 algo="KL",
75
                 quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"],
76
                 is_full_quantize=False,
77 78
                 weight_bits=8,
                 activation_bits=8,
79 80
                 is_use_cache_file=False,
                 cache_dir="./temp_post_training"):
81
        '''
82
        Constructor.
83 84

        Args:
85
            executor(fluid.Executor): The executor to load, run and save the
86
                quantized model.
87 88
            scope(fluid.Scope, optional): The scope of the program, use it to load 
                and save variables. If scope=None, get scope by global_scope(). 
89 90 91 92 93 94 95 96 97
            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'.
98 99 100
            sample_generator(Python Generator): The sample generator provides 
                calibrate data for DataLoader, and it only returns a sample every 
                time.
101 102 103 104
            batch_size(int, optional): The batch size of DataLoader. Default is 10.
            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 
                all data provided by sample_generator as calibrate data.
105 106 107 108 109
            algo(str, optional): If algo='KL', use KL-divergenc method to
                get the KL threshold for quantized activations and get the abs_max
                value for quantized weights. If algo='abs_max', get the abs max 
                value for activations and weights. If algo= 'min_max', get the min 
                and max value for quantized activations and weights. Default is KL.
110 111
            quantizable_op_type(list[str], optional): List the type of ops 
                that will be quantized. Default is ["conv2d", "depthwise_conv2d", 
112 113
                "mul"].
            is_full_quantized(bool, optional): If set is_full_quantized as True, 
114
                apply quantization to all supported quantizable op type. If set
115 116
                is_full_quantized as False, only apply quantization to the op type 
                according to the input quantizable_op_type.
117 118
            weight_bits(int, optional): quantization bit number for weights.
            activation_bits(int): quantization bit number for activation.
119 120 121 122 123 124 125
            is_use_cache_file(bool, optional): If set is_use_cache_file as False,
                all temp data will be saved in memory. If set is_use_cache_file as True,
                it will save temp data to disk. When the fp32 model is complex or
                the number of calibrate data is large, we should set is_use_cache_file
                as True. Defalut is False.
            cache_dir(str, optional): When is_use_cache_file is True, set cache_dir as
                the directory for saving temp data. Default is ./temp_post_training.
126 127 128
        Returns:
            None

129 130 131 132 133 134
        Examples:
        .. code-block:: python
            import paddle.fluid as fluid
            from paddle.fluid.contrib.slim.quantization import PostTrainingQuantization
            
            exe = fluid.Executor(fluid.CPUPlace())
135 136 137 138 139 140 141 142 143
            model_dir = path/to/fp32_model_params
            # set model_filename as None when the filename is __model__, 
            # otherwise set it as the real filename
            model_filename = None 
            # set params_filename as None when all parameters were saved in 
            # separate files, otherwise set it as the real filename
            params_filename = None
            save_model_path = path/to/save_model_path
            # prepare the sample generator according to the model, and the 
144
            # sample generator must return a sample every time. The reference
145 146 147
            # document: https://www.paddlepaddle.org.cn/documentation/docs/zh
            # /user_guides/howto/prepare_data/use_py_reader.html
            sample_generator = your_sample_generator
148 149 150
            batch_size = 10
            batch_nums = 10
            algo = "KL"
151
            quantizable_op_type = ["conv2d", "depthwise_conv2d", "mul"]
152 153
            ptq = PostTrainingQuantization(
                        executor=exe,
154 155 156 157
                        sample_generator=sample_generator,
                        model_dir=model_dir,
                        model_filename=model_filename,
                        params_filename=params_filename,
158 159 160 161 162 163 164
                        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)
        '''
165 166 167 168

        assert executor is not None, "The executor cannot be None."
        assert model_dir is not None, "The model_dir cannot be None."
        assert sample_generator is not None, \
169 170 171
            "The sample_generator cannot be None."
        assert algo in ['KL', 'abs_max', 'min_max'], \
            "The algo should be KL, abs_max or min_max."
172

173
        self._executor = executor
174
        self._scope = global_scope() if scope == None else scope
175 176 177
        self._model_dir = model_dir
        self._model_filename = model_filename
        self._params_filename = params_filename
178
        self._sample_generator = sample_generator
179 180 181
        self._batch_size = batch_size
        self._batch_nums = batch_nums
        self._algo = algo
182 183 184 185
        self._is_use_cache_file = is_use_cache_file
        self._cache_dir = cache_dir
        if self._is_use_cache_file and not os.path.exists(self._cache_dir):
            os.mkdir(self._cache_dir)
186 187 188 189 190 191 192 193 194

        supported_quantizable_op_type = \
            QuantizationTransformPass._supported_quantizable_op_type + \
            AddQuantDequantPass._supported_quantizable_op_type
        if is_full_quantize:
            self._quantizable_op_type = supported_quantizable_op_type
        else:
            self._quantizable_op_type = quantizable_op_type
            for op_type in self._quantizable_op_type:
195
                assert op_type in supported_quantizable_op_type, \
196
                    op_type + " is not supported for quantization."
197 198 199 200 201 202 203

        self._place = self._executor.place
        self._program = None
        self._feed_list = None
        self._fetch_list = None
        self._data_loader = None

204
        self._op_real_in_out_name = _op_real_in_out_name
205
        self._bit_length = 8
206 207
        self._quantized_weight_var_name = set()
        self._quantized_act_var_name = set()
208
        self._sampling_data = {}
209 210 211 212
        self._quantized_var_kl_threshold = {}
        self._quantized_var_min = {}
        self._quantized_var_max = {}
        self._quantized_var_abs_max = {}
213 214 215

    def quantize(self):
        '''
216 217 218
        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.
219 220 221 222

        Args:
            None
        Returns:
223 224
            the program of quantized model.
        '''
225 226 227
        self._load_model_data()
        self._collect_quantized_varnames()
        self._set_activation_persistable()
228 229 230 231 232

        batch_id = 0
        for data in self._data_loader():
            self._executor.run(program=self._program,
                               feed=data,
233 234
                               fetch_list=self._fetch_list,
                               return_numpy=False)
235 236 237 238
            if self._algo == "KL":
                self._sample_data(batch_id)
            else:
                self._sample_threshold()
239

240
            if batch_id % 5 == 0:
241
                _logger.info("Run batch: " + str(batch_id))
242 243 244
            batch_id += 1
            if self._batch_nums and batch_id >= self._batch_nums:
                break
245
        _logger.info("Finish all batch: " + str(batch_id))
246

247
        self._reset_activation_persistable()
248

249 250
        if self._algo == "KL":
            self._calculate_kl_threshold()
251

252 253 254 255 256 257
        if self._algo in ["KL", "abs_max"]:
            self._update_program()
        else:
            self._save_input_threhold()

        self._save_output_threshold()
258 259 260 261 262 263 264 265
        return self._program

    def save_quantized_model(self, save_model_path):
        '''
        Save the quantized model to the disk.

        Args:
            save_model_path(str): The path to save the quantized model
266
        Returns:
267 268 269 270 271 272 273 274 275
            None
        '''
        io.save_inference_model(
            dirname=save_model_path,
            feeded_var_names=self._feed_list,
            target_vars=self._fetch_list,
            executor=self._executor,
            main_program=self._program)

276
    def _load_model_data(self):
277
        '''
278
        Load model and set data loader.
279
        '''
280
        _logger.info("Load model and set data loader ...")
281
        [self._program, self._feed_list, self._fetch_list] = \
282 283 284 285
            io.load_inference_model(dirname=self._model_dir,
                                    executor=self._executor,
                                    model_filename=self._model_filename,
                                    params_filename=self._params_filename)
286 287 288 289 290
        feed_vars = [framework._get_var(str(var_name), self._program) \
            for var_name in self._feed_list]
        self._data_loader = io.DataLoader.from_generator(
            feed_list=feed_vars, capacity=3 * self._batch_size, iterable=True)
        self._data_loader.set_sample_generator(
291
            self._sample_generator,
292 293 294 295
            batch_size=self._batch_size,
            drop_last=True,
            places=self._place)

296 297 298 299 300 301
    def _collect_quantized_varnames(self):
        '''
        Collect the variable names for sampling, and set activation
        variables to be persistable.
        '''
        _logger.info("Collect quantized variable names ...")
302 303
        # TODO(juncaipeng), consider the name_scope of skip_quant and
        # reduce the variables for sampling
304 305 306 307 308
        persistable_var_names = []
        for var in self._program.list_vars():
            if var.persistable:
                persistable_var_names.append(var.name)

309
        for op in self._program.global_block().ops:
310 311
            op_type = op.type
            if op_type in self._quantizable_op_type:
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
                name_list = self._op_real_in_out_name[op_type]
                for input_name in name_list[0]:
                    for var_name in op.input(input_name):
                        if var_name in persistable_var_names:
                            self._quantized_weight_var_name.add(var_name)
                        else:
                            self._quantized_act_var_name.add(var_name)
                for output_name in name_list[1]:
                    for var_name in op.output(output_name):
                        if var_name in persistable_var_names:
                            self._quantized_weight_var_name.add(var_name)
                        else:
                            self._quantized_act_var_name.add(var_name)

    def _set_activation_persistable(self):
        '''
        Set activation variables to be persistable, so can obtain 
        the tensor data in sample_data
        '''
        persistable_var_names = []
        for var in self._program.list_vars():
            if var.persistable:
                persistable_var_names.append(var.name)
335 336 337 338
        for var in self._program.list_vars():
            if var.name in self._quantized_act_var_name:
                var.persistable = True

339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    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

    def _sample_threshold(self):
        '''
        Sample the input threshold(min, max, or abs_max) in every iterations.
        '''
        assert self._algo in ["abs_max", "min_max"], \
            "The algo should be abs_max or min_max to sample min max value."
        if self._algo == "abs_max":
            # Only calculate abs_max value for weight for once
            if self._quantized_var_abs_max == {}:
                for var_name in self._quantized_weight_var_name:
                    var_tensor = _load_variable_data(self._scope, var_name)
                    abs_max_per_channel = []
                    for i in range(var_tensor.shape[0]):
                        abs_max_per_channel.append(
                            float(np.max(np.abs(var_tensor[i]))))
                    self._quantized_var_abs_max[var_name] = abs_max_per_channel
            for var_name in self._quantized_act_var_name:
                var_tensor = _load_variable_data(self._scope, var_name)
                abs_max_value = float(np.max(np.abs(var_tensor)))
                if (var_name not in self._quantized_var_abs_max) or \
                    (abs_max_value > self._quantized_var_abs_max[var_name]):
                    self._quantized_var_abs_max[var_name] = abs_max_value
        elif self._algo == "min_max":
            if self._quantized_var_min == {} and self._quantized_var_max == {}:
                for var_name in self._quantized_weight_var_name:
                    var_tensor = _load_variable_data(self._scope, var_name)
                    min_per_channel = []
                    max_per_channle = []
                    for i in range(var_tensor.shape[0]):
                        min_per_channel.append(float(np.min(var_tensor[i])))
                        max_per_channle.append(float(np.max(var_tensor[i])))
                    self._quantized_var_min[var_name] = min_per_channel
                    self._quantized_var_max[var_name] = max_per_channle
            for var_name in self._quantized_act_var_name:
                var_tensor = _load_variable_data(self._scope, var_name)
                min_value = float(np.min(var_tensor))
                max_value = float(np.max(var_tensor))
                if (var_name not in self._quantized_var_min) or \
                    (min_value < self._quantized_var_min[var_name]):
                    self._quantized_var_min[var_name] = min_value
                if (var_name not in self._quantized_var_max) or \
                    (max_value > self._quantized_var_max[var_name]):
                    self._quantized_var_max[var_name] = max_value

    def _save_input_threhold(self):
        '''
        Save input threshold to the quantized op.
        '''
        assert self._algo == "min_max", \
            "The algo should be min_max to save input threshold."
        for op in self._program.global_block().ops:
            if op.type in self._quantizable_op_type:
                input_name_list = self._op_real_in_out_name[op.type][0]
                for input_name in input_name_list:
                    for var_name in op.input(input_name):
                        assert var_name in self._quantized_var_min
                        assert var_name in self._quantized_var_max
                        op._set_attr(var_name + ".min",
                                     self._quantized_var_min[var_name])
                        op._set_attr(var_name + ".max",
                                     self._quantized_var_max[var_name])

409
    def _sample_data(self, iter):
410 411 412 413
        '''
        Sample the tensor data of quantized variables, 
        applied in every iteration.
        '''
414
        assert self._algo == "KL", "The algo should be KL to sample data."
415 416
        for var_name in self._quantized_weight_var_name:
            if var_name not in self._sampling_data:
417
                var_tensor = _load_variable_data(self._scope, var_name)
418 419
                self._sampling_data[var_name] = var_tensor

420 421
        if self._is_use_cache_file:
            for var_name in self._quantized_act_var_name:
422
                var_tensor = _load_variable_data(self._scope, var_name)
423 424 425 426 427 428 429 430
                var_tensor = var_tensor.ravel()
                save_path = os.path.join(self._cache_dir,
                                         var_name + "_" + str(iter) + ".npy")
                np.save(save_path, var_tensor)
        else:
            for var_name in self._quantized_act_var_name:
                if var_name not in self._sampling_data:
                    self._sampling_data[var_name] = []
431
                var_tensor = _load_variable_data(self._scope, var_name)
432 433
                var_tensor = var_tensor.ravel()
                self._sampling_data[var_name].append(var_tensor)
434

435
    def _calculate_kl_threshold(self):
436
        '''
437
        Calculate the KL threshold of quantized variables.
438
        '''
439 440
        _logger.info("Calculate KL threshold ...")
        assert self._algo == "KL", "The algo should be KL to calculate kl threshold."
441
        # apply channel_wise_abs_max quantization for weights
442 443
        for var_name in self._quantized_weight_var_name:
            data = self._sampling_data[var_name]
444
            threshold_per_channel = []
445 446
            for i in range(data.shape[0]):
                abs_max_value = np.max(np.abs(data[i]))
447 448
                threshold_per_channel.append(abs_max_value)
            self._quantized_var_kl_threshold[var_name] = threshold_per_channel
449

450
        # apply kl quantization for activation
451 452 453 454 455 456 457 458 459 460
        if self._is_use_cache_file:
            for var_name in self._quantized_act_var_name:
                sampling_data = []
                filenames = [f for f in os.listdir(self._cache_dir) \
                    if re.match(var_name + '_[0-9]+.npy', f)]
                for filename in filenames:
                    file_path = os.path.join(self._cache_dir, filename)
                    sampling_data.append(np.load(file_path))
                    os.remove(file_path)
                sampling_data = np.concatenate(sampling_data)
461 462
                self._quantized_var_kl_threshold[var_name] = \
                    self._get_kl_scaling_factor(np.abs(sampling_data))
463 464 465 466
        else:
            for var_name in self._quantized_act_var_name:
                self._sampling_data[var_name] = np.concatenate(
                    self._sampling_data[var_name])
467 468
                self._quantized_var_kl_threshold[var_name] = \
                    self._get_kl_scaling_factor(np.abs(self._sampling_data[var_name]))
469 470 471

    def _update_program(self):
        '''
472 473 474
        Use QuantizationTransformPass and AddQuantDequantPass to insert 
        fake_quantize, fake_dequantize and fake_quant_dequant op. 
        Besides, save all kl threshold to the scale var node.
475
        '''
476
        _logger.info("Update the program ...")
477 478
        graph = IrGraph(core.Graph(self._program.desc), for_test=True)

479
        # use QuantizationTransformPass to insert fake_quant/fake_dequantize op
480 481
        major_quantizable_op_types = []
        for op_type in QuantizationTransformPass._supported_quantizable_op_type:
482
            if op_type in self._quantizable_op_type:
483
                major_quantizable_op_types.append(op_type)
484 485 486 487 488 489 490
        transform_pass = QuantizationTransformPass(
            scope=self._scope,
            place=self._place,
            weight_bits=self._bit_length,
            activation_bits=self._bit_length,
            activation_quantize_type='moving_average_abs_max',
            weight_quantize_type='channel_wise_abs_max',
491
            quantizable_op_type=major_quantizable_op_types)
492 493 494
        transform_pass.apply(graph)

        # use AddQuantDequantPass to insert fake_quant_dequant op
495 496
        minor_quantizable_op_types = []
        for op_type in AddQuantDequantPass._supported_quantizable_op_type:
497
            if op_type in self._quantizable_op_type:
498
                minor_quantizable_op_types.append(op_type)
499 500 501
        add_quant_dequant_pass = AddQuantDequantPass(
            scope=self._scope,
            place=self._place,
502
            quantizable_op_type=minor_quantizable_op_types)
503 504
        add_quant_dequant_pass.apply(graph)

505 506 507 508 509 510
        # save abs_max or KL threshold to scale var node
        if self._algo == "KL":
            scale_dict = self._quantized_var_kl_threshold
        else:
            scale_dict = self._quantized_var_abs_max
        for key, val in scale_dict.items():
511 512 513 514 515
            _set_variable_data(
                self._scope,
                self._place,
                key + ".scale",
                np.array(
516
                    [val], dtype=np.float32))
517 518 519 520 521
            _set_variable_data(
                self._scope,
                self._place,
                key + ".quant_dequant.scale",
                np.array(
522 523 524 525 526 527 528 529 530
                    [val], dtype=np.float32))

        # apply QuantizationFreezePass, and obtain the final quant model
        freeze_pass = QuantizationFreezePass(
            scope=self._scope,
            place=self._place,
            weight_bits=self._bit_length,
            activation_bits=self._bit_length,
            weight_quantize_type='channel_wise_abs_max',
531
            quantizable_op_type=major_quantizable_op_types)
532 533 534
        freeze_pass.apply(graph)
        self._program = graph.to_program()

535
    def _save_output_threshold(self):
536
        '''
537
        Save output threshold to the quantized op.
538 539 540 541 542
        '''
        for op in self._program.global_block().ops:
            if op.type in self._quantizable_op_type:
                output_name_list = self._op_real_in_out_name[op.type][1]
                for output_name in output_name_list:
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
                    for var_name in op.output(output_name):
                        if self._algo == "KL":
                            assert var_name in self._quantized_var_kl_threshold
                            op._set_attr(
                                var_name + ".threshold",
                                self._quantized_var_kl_threshold[var_name])
                            op._set_attr("quantization_type", "post_kl")
                        elif self._algo == "abs_max":
                            assert var_name in self._quantized_var_abs_max
                            op._set_attr(var_name + ".threshold",
                                         self._quantized_var_abs_max[var_name])
                            op._set_attr("quantization_type", "post_abs_max")
                        elif self._algo == "min_max":
                            assert var_name in self._quantized_var_min
                            assert var_name in self._quantized_var_max
                            op._set_attr(var_name + ".min",
                                         self._quantized_var_min[var_name])
                            op._set_attr(var_name + ".max",
                                         self._quantized_var_max[var_name])
                            op._set_attr("quantization_type", "post_min_max")
563

564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    def _get_kl_scaling_factor(self, activation_blob, num_quantized_bins=255):
        '''
        Using the KL-divergenc method to get the more precise scaling factor.
        '''
        max_val = np.max(activation_blob)
        min_val = np.min(activation_blob)
        if min_val >= 0:
            hist, hist_edeges = np.histogram(
                activation_blob, bins=2048, range=(min_val, max_val))
            ending_iter = 2047
            starting_iter = int(ending_iter * 0.7)
        else:
            _logger.error("Please first apply abs to activation_blob.")
        bin_width = hist_edeges[1] - hist_edeges[0]

        P_sum = len(np.array(activation_blob).ravel())
        min_kl_divergence = 0
        min_kl_index = 0
        kl_inited = False
        for i in range(starting_iter, ending_iter + 1):
            reference_distr_P = hist[0:i].tolist()
            outliers_count = sum(hist[i:2048])
            if reference_distr_P[i - 1] == 0:
                continue
            reference_distr_P[i - 1] += outliers_count
            reference_distr_bins = reference_distr_P[:]
            candidate_distr_Q = hist[0:i].tolist()
            num_merged_bins = int(i / num_quantized_bins)
            candidate_distr_Q_quantized = [0] * num_quantized_bins
            j_start = 0
            j_end = num_merged_bins
            for idx in range(num_quantized_bins):
                candidate_distr_Q_quantized[idx] = sum(candidate_distr_Q[
                    j_start:j_end])
                j_start += num_merged_bins
                j_end += num_merged_bins
                if (idx + 1) == num_quantized_bins - 1:
                    j_end = i
            candidate_distr_Q = self._expand_quantized_bins(
                candidate_distr_Q_quantized, reference_distr_bins)
            Q_sum = sum(candidate_distr_Q)
            kl_divergence = self._safe_entropy(reference_distr_P, P_sum,
                                               candidate_distr_Q, Q_sum)
            if not kl_inited:
                min_kl_divergence = kl_divergence
                min_kl_index = i
                kl_inited = True
            elif kl_divergence < min_kl_divergence:
                min_kl_divergence = kl_divergence
                min_kl_index = i
            else:
                pass
        if min_kl_index == 0:
            while starting_iter > 0:
                if hist[starting_iter] == 0:
                    starting_iter -= 1
                    continue
                else:
                    break
            min_kl_index = starting_iter
        return (min_kl_index + 0.5) * bin_width

    def _expand_quantized_bins(self, quantized_bins, reference_bins):
        '''
        '''
        expanded_quantized_bins = [0] * len(reference_bins)
        num_merged_bins = int(len(reference_bins) / len(quantized_bins))
        j_start = 0
        j_end = num_merged_bins
        for idx in range(len(quantized_bins)):
            zero_count = reference_bins[j_start:j_end].count(0)
            num_merged_bins = j_end - j_start
            if zero_count == num_merged_bins:
                avg_bin_ele = 0
            else:
                avg_bin_ele = quantized_bins[idx] / (
                    num_merged_bins - zero_count + 0.0)
            for idx1 in range(j_start, j_end):
                expanded_quantized_bins[idx1] = (0 if reference_bins[idx1] == 0
                                                 else avg_bin_ele)
            j_start += num_merged_bins
            j_end += num_merged_bins
            if (idx + 1) == len(quantized_bins) - 1:
                j_end = len(reference_bins)
        return expanded_quantized_bins

    def _safe_entropy(self, reference_distr_P, P_sum, candidate_distr_Q, Q_sum):
        '''
        Calculate the entropy.
        '''
        assert len(reference_distr_P) == len(candidate_distr_Q)
        tmp_sum1 = 0
        tmp_sum2 = 0
        for idx in range(len(reference_distr_P)):
            p_idx = reference_distr_P[idx]
            q_idx = candidate_distr_Q[idx]
            if p_idx == 0:
                tmp_sum1 += 0
                tmp_sum2 += 0
            else:
                if q_idx == 0:
665 666
                    _logger.error("Fatal error!, idx = " + str(idx) +
                                  " qindex = 0! p_idx = " + str(p_idx))
667 668 669
                tmp_sum1 += p_idx * (math.log(Q_sum * p_idx))
                tmp_sum2 += p_idx * (math.log(P_sum * q_idx))
        return (tmp_sum1 - tmp_sum2) / P_sum
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699


class WeightQuantization(object):
    _supported_quantizable_op_type = ['conv2d', 'depthwise_conv2d', 'mul']

    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

    def quantize_weight_to_int(self,
                               save_model_dir,
                               save_model_filename=None,
                               save_params_filename=None,
                               quantizable_op_type=["conv2d", "mul"],
700
                               weight_bits=8,
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
                               threshold_rate=0.0):
        '''
        In order to reduce the size of model, this api quantizes the weight
        of some ops from float32 to int8/16. In the inference stage, the 
        quantized weight will be dequantized to float32 again.
        
        Args:
            save_model_dir(str): The path to save the quantized model.
            save_model_filename(str, optional): The name of file to 
                save the inference program. If it is None, the default 
                filename '__model__' will be used. Default is 'None'.
            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 
                parameters were saved in a single binary file.
            quantizable_op_type(list[str], optional): The list of ops 
                that will be quantized, and the quantized ops should be
                contained in ["conv2d", "depthwise_conv2d", "mul"]. 
                Default is ["conv2d","mul"].
720 721
            weight_bits(int, optional): The bits for the quantized weight, 
                and it should be 8 or 16. Default is 8.
722 723 724 725 726 727 728 729 730 731 732
            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 
                value will be optimized. Default is 0.0.
        '''
        for op_type in quantizable_op_type:
            assert op_type in self._supported_quantizable_op_type, \
                "input error:" + op_type + \
                " is not supported for weight quantization."
733 734 735 736
        assert weight_bits in [8, 16], \
            "input error: weight_bits should be 8 or 16."
        quantize_range = (1 << (weight_bits - 1)) - 1
        save_weight_dtype = np.int8 if weight_bits == 8 else np.int16
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772

        place = core.CPUPlace()
        exe = Executor(place)
        scope = global_scope()
        [program, feed_list, fetch_list] = \
            io.load_inference_model(dirname=self._model_dir,
                                    executor=exe,
                                    model_filename=self._model_filename,
                                    params_filename=self._params_filename)

        persistable_var_names = []
        for var in program.list_vars():
            if var.persistable:
                persistable_var_names.append(var.name)
        for op in program.global_block().ops:
            if op.type in quantizable_op_type:
                for var_name in op.input_arg_names:
                    if var_name in persistable_var_names:
                        var_tensor_data = _load_variable_data(scope, var_name)
                        if abs(threshold_rate) < 1e-10:
                            threshold_value = np.max(np.abs(var_tensor_data))
                        else:
                            threshold_value = self._calculate_threshold(\
                                var_tensor_data, threshold_rate)
                            var_tensor_data[var_tensor_data >
                                            threshold_value] = threshold_value
                            var_tensor_data[var_tensor_data <
                                            -threshold_value] = -threshold_value
                        scale = threshold_value / quantize_range
                        quantized_var_tensor_data = \
                            np.around(var_tensor_data / scale)
                        quantized_var_tensor_data = \
                            quantized_var_tensor_data.astype(save_weight_dtype)
                        _set_variable_data(scope, place, var_name,
                                           quantized_var_tensor_data)
                        op._set_attr(var_name + "_quant_scale", [scale])
773
                        op._set_attr('quantize_weight_bits', weight_bits)
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797

        io.save_inference_model(
            dirname=save_model_dir,
            feeded_var_names=feed_list,
            target_vars=fetch_list,
            executor=exe,
            main_program=program,
            model_filename=save_model_filename,
            params_filename=save_params_filename)

    def _calculate_threshold(self, input, threshold_rate, histogram_bins=5000):
        input_abs = np.abs(input)
        hist, hist_edeges = np.histogram(
            input_abs, bins=histogram_bins, range=(0, np.max(input_abs)))
        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