quanter.py 28.0 KB
Newer Older
F
ftian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import os
F
ftian 已提交
16
import copy
17
import json
18 19
import logging

F
ftian 已提交
20 21 22 23 24 25
import paddle
from paddle.fluid.framework import IrGraph
from paddle.fluid.contrib.slim.quantization import QuantizationTransformPass
from paddle.fluid.contrib.slim.quantization import QuantizationFreezePass
from paddle.fluid.contrib.slim.quantization import ConvertToInt8Pass
from paddle.fluid.contrib.slim.quantization import TransformForMobilePass
S
slf12 已提交
26
from paddle.fluid.contrib.slim.quantization import PostTrainingQuantization
S
slf12 已提交
27
from paddle.fluid.contrib.slim.quantization import AddQuantDequantPass
28 29
from paddle.fluid.contrib.slim.quantization import OutScaleForTrainingPass
from paddle.fluid.contrib.slim.quantization import OutScaleForInferencePass
F
ftian 已提交
30
from paddle.fluid import core
L
Liufang Sang 已提交
31
from paddle.fluid.contrib.slim.quantization import WeightQuantization
F
ftian 已提交
32

33 34 35
from ..common import get_logger
_logger = get_logger(__name__, level=logging.INFO)

S
slf12 已提交
36
WEIGHT_QUANTIZATION_TYPES = [
37
    'abs_max', 'channel_wise_abs_max', 'range_abs_max', 'moving_average_abs_max'
S
slf12 已提交
38
]
39 40
WEIGHT_QUANTIZATION_TYPES_TENSORRT = ['channel_wise_abs_max']

S
slf12 已提交
41 42 43
ACTIVATION_QUANTIZATION_TYPES = [
    'abs_max', 'range_abs_max', 'moving_average_abs_max'
]
44 45 46 47 48

ACTIVATION_QUANTIZATION_TYPES_TENSORRT = [
    'range_abs_max', 'moving_average_abs_max'
]

F
ftian 已提交
49
VALID_DTYPES = ['int8']
50
TRANSFORM_PASS_OP_TYPES = QuantizationTransformPass._supported_quantizable_op_type
51 52
QUANT_DEQUANT_PASS_OP_TYPES = AddQuantDequantPass._supported_quantizable_op_type

53 54 55 56
TENSORRT_OP_TYPES = [
    'mul', 'conv2d', 'pool2d', 'depthwise_conv2d', 'elementwise_add',
    'leaky_relu'
]
F
ftian 已提交
57

58 59
VARS_MAPPING_TABLE = './mapping_table_for_saving_inference_model'

F
ftian 已提交
60
_quant_config_default = {
61 62 63 64
    # weight quantize type, default is 'channel_wise_abs_max'
    'weight_quantize_type': 'channel_wise_abs_max',
    # activation quantize type, default is 'moving_average_abs_max'
    'activation_quantize_type': 'moving_average_abs_max',
F
ftian 已提交
65 66 67 68 69 70 71
    # weight quantize bit num, default is 8
    'weight_bits': 8,
    # activation quantize bit num, default is 8
    'activation_bits': 8,
    # ops of name_scope in not_quant_pattern list, will not be quantized
    'not_quant_pattern': ['skip_quant'],
    # ops of type in quantize_op_types, will be quantized
72
    'quantize_op_types': ['conv2d', 'depthwise_conv2d', 'mul'],
F
ftian 已提交
73 74 75 76 77 78
    # data type after quantization, such as 'uint8', 'int8', etc. default is 'int8'
    'dtype': 'int8',
    # window size for 'range_abs_max' quantization. defaulf is 10000
    'window_size': 10000,
    # The decay coefficient of moving average, default is 0.9
    'moving_rate': 0.9,
79 80 81
    # if True, 'quantize_op_types' will be TENSORRT_OP_TYPES
    'for_tensorrt': False,
    # if True, 'quantoze_op_types' will be TRANSFORM_PASS_OP_TYPES + QUANT_DEQUANT_PASS_OP_TYPES 
82
    'is_full_quantize': False
F
ftian 已提交
83 84 85
}


86 87 88 89 90 91 92 93 94 95 96 97
def load_dict():
    with open(VARS_MAPPING_TABLE, 'r') as file:
        data = file.read()
        data = json.loads(data)
        return data


def save_dict(table):
    with open(VARS_MAPPING_TABLE, 'w') as file:
        file.write(json.dumps(table))


F
ftian 已提交
98 99
def _parse_configs(user_config):
    """
100
    check if user's configs are valid.
F
ftian 已提交
101
    Args:
102
        user_config(dict): user's config.
F
ftian 已提交
103 104 105 106 107 108 109
    Return:
        configs(dict): final configs will be used.
    """

    configs = copy.deepcopy(_quant_config_default)
    configs.update(user_config)

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    assert isinstance(configs['for_tensorrt'], bool) and isinstance(
        configs['is_full_quantize'],
        bool), "'for_tensorrt' and 'is_full_quantize' must both be bool'"

    # check if configs is valid
    if configs['for_tensorrt']:
        weight_types = WEIGHT_QUANTIZATION_TYPES_TENSORRT
        activation_types = ACTIVATION_QUANTIZATION_TYPES_TENSORRT
        platform = 'TensorRT'
    else:
        weight_types = WEIGHT_QUANTIZATION_TYPES
        activation_types = WEIGHT_QUANTIZATION_TYPES
        platform = 'PaddleLite'
    assert configs['weight_quantize_type'] in weight_types, \
        "Unknown weight_quantize_type: {}. {} only supports {} ".format(configs['weight_quantize_type'],
                platform, weight_types)
F
ftian 已提交
126

127 128 129
    assert configs['activation_quantize_type'] in activation_types, \
        "Unknown activation_quantize_type: {}. {} only supports {}".format(configs['activation_quantize_type'],
                platform, activation_types)
F
ftian 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142

    assert isinstance(configs['weight_bits'], int), \
        "weight_bits must be int value."

    assert (configs['weight_bits'] >= 1 and configs['weight_bits'] <= 16), \
        "weight_bits should be between 1 and 16."

    assert isinstance(configs['activation_bits'], int), \
        "activation_bits must be int value."

    assert (configs['activation_bits'] >= 1 and configs['activation_bits'] <= 16), \
        "activation_bits should be between 1 and 16."

143 144
    assert isinstance(configs['not_quant_pattern'], (list, str)), \
        "not_quant_pattern must be list or str"
F
ftian 已提交
145 146 147 148

    assert isinstance(configs['quantize_op_types'], list), \
        "quantize_op_types must be a list"

149 150 151 152 153 154 155 156 157 158 159 160
    if configs['for_tensorrt']:
        configs['quantize_op_types'] = TENSORRT_OP_TYPES
    elif configs['is_full_quantize']:
        configs[
            'quantize_op_types'] = TRANSFORM_PASS_OP_TYPES + QUANT_DEQUANT_PASS_OP_TYPES
    else:
        for op_type in configs['quantize_op_types']:
            assert (op_type in QUANT_DEQUANT_PASS_OP_TYPES) or (
                op_type in TRANSFORM_PASS_OP_TYPES), "{} is not support, \
                        now support op types are {}".format(
                    op_type,
                    TRANSFORM_PASS_OP_TYPES + QUANT_DEQUANT_PASS_OP_TYPES)
S
slf12 已提交
161

F
ftian 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175
    assert isinstance(configs['dtype'], str), \
        "dtype must be a str."

    assert (configs['dtype'] in VALID_DTYPES), \
        "dtype can only be " + " ".join(VALID_DTYPES)

    assert isinstance(configs['window_size'], int), \
        "window_size must be int value, window size for 'range_abs_max' quantization, default is 10000."

    assert isinstance(configs['moving_rate'], float), \
        "moving_rate must be float value, The decay coefficient of moving average, default is 0.9."

    return configs

W
wanghaoshuang 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
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
        for n in filter(lambda node: node.node not in all_used_vars,
                        graph.all_var_nodes())
    }
    graph.safe_remove_nodes(all_unused_vars)
    return graph

def _apply_pass(scope, graph, pass_name, attrs=None,
                attr_values=None, debug=False):
    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(
            attr_values
        ), "Different number of pass attributes and their values."
        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
F
ftian 已提交
212

213 214 215 216 217 218 219 220 221 222
def quant_aware(program,
                place,
                config=None,
                scope=None,
                for_test=False,
                weight_quantize_func=None,
                act_quantize_func=None,
                weight_preprocess_func=None,
                act_preprocess_func=None,
                optimizer_func=None,
Y
yukavio 已提交
223 224
                executor=None,
                return_program=False):
225 226 227
    """Add quantization  and dequantization operators to "program" 
    for quantization training or testing.

F
ftian 已提交
228
    Args:
B
Bai Yifan 已提交
229 230
        program(paddle.static.Program): training or testing ``program``.
        place(paddle.CPUPlace or paddle.CUDAPlace): This parameter represents 
231 232 233
            the executor run on which device.
        config(dict, optional): configs for quantization. if None, will use default config. 
            Default: None.
B
Bai Yifan 已提交
234
        scope(paddle.static.Scope): Scope records the mapping between variable names and variables, 
235
            similar to brackets in programming languages. Usually users can use 
B
Bai Yifan 已提交
236
            `paddle.static.global_scope <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_.              When ``None`` will use `paddle.static.global_scope() <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_ . Default: ``None``.
237 238
        for_test(bool): If the 'program' parameter is a test program, this parameter should be set to ``True``. 
            Otherwise, set to ``False``.Default: False
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
       weight_quantize_func(function): Function that defines how to quantize weight. Using this
                can quickly test if user's quantization method works or not. In this function, user should
                both define quantization function and dequantization function, that is, the function's input
                is non-quantized weight and function returns dequantized weight. If None, will use
                quantization op defined by 'weight_quantize_type'.
                Default is None.
        act_quantize_func(function): Function that defines how to quantize activation. Using this
                can quickly test if user's quantization method works or not. In this function, user should
                both define quantization and dequantization process, that is, the function's input
                is non-quantized activation and function returns dequantized activation. If None, will use 
                quantization op defined by 'activation_quantize_type'.
                Default is None.
        weight_preprocess_func(function): Function that defines how to preprocess weight before quantization. Using this
                can quickly test if user's preprocess method works or not. The function's input
                is non-quantized weight and function returns processed weight to be quantized. If None, the weight will
                be quantized directly.
                Default is None.
        act_preprocess_func(function): Function that defines how to preprocess activation before quantization. Using this
                can quickly test if user's preprocess method works or not. The function's input
                is non-quantized activation and function returns processed activation to be quantized. If None, the activation will
                be quantized directly.
                Default is None.
        optimizer_func(function): Fuction return a optimizer. When 'is_test' is False and user want to use self-defined 
            quantization function and preprocess function, this function must be set. Default is None.
B
Bai Yifan 已提交
263
        exe(paddle.static.Executor): If user want to use self-defined quantization function and preprocess function, exe must be set for
264
                initialization. Default is None.
Y
yukavio 已提交
265 266
        return_program(bool): If user want return value is a Program rather than Compiled Program, This argument should be set True.
                Default is False.
267
    Returns:
B
Bai Yifan 已提交
268
        paddle.static.CompiledProgram | paddle.static.Program: Program with quantization and dequantization ``operators``
F
ftian 已提交
269 270
    """

B
Bai Yifan 已提交
271
    scope = paddle.static.global_scope() if not scope else scope
272 273 274 275 276 277
    if config is None:
        config = _quant_config_default
    else:
        assert isinstance(config, dict), "config must be dict"
        config = _parse_configs(config)
    _logger.info("quant_aware config {}".format(config))
F
ftian 已提交
278 279 280

    main_graph = IrGraph(core.Graph(program.desc), for_test=for_test)

W
wanghaoshuang 已提交
281 282 283 284 285 286

    graph = _apply_pass(scope, main_graph, 'conv_bn_fuse_pass')
    graph = _apply_pass(scope, main_graph, 'depthwise_conv_bn_fuse_pass')
    graph = _apply_pass(scope, main_graph, 'conv_eltwiseadd_bn_fuse_pass')
    graph = _apply_pass(scope, main_graph, 'depthwise_conv_eltwiseadd_bn_fuse_pass')

S
slf12 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    transform_pass_ops = []
    quant_dequant_ops = []
    for op_type in config['quantize_op_types']:
        if op_type in TRANSFORM_PASS_OP_TYPES:
            transform_pass_ops.append(op_type)
        elif op_type in QUANT_DEQUANT_PASS_OP_TYPES:
            quant_dequant_ops.append(op_type)
    if len(transform_pass_ops) > 0:
        transform_pass = QuantizationTransformPass(
            scope=scope,
            place=place,
            weight_bits=config['weight_bits'],
            activation_bits=config['activation_bits'],
            activation_quantize_type=config['activation_quantize_type'],
            weight_quantize_type=config['weight_quantize_type'],
            window_size=config['window_size'],
            moving_rate=config['moving_rate'],
            quantizable_op_type=transform_pass_ops,
305 306 307 308 309 310 311
            skip_pattern=config['not_quant_pattern'],
            weight_quantize_func=weight_quantize_func,
            act_quantize_func=act_quantize_func,
            weight_preprocess_func=weight_preprocess_func,
            act_preprocess_func=act_preprocess_func,
            optimizer_func=optimizer_func,
            executor=executor)
S
slf12 已提交
312 313 314 315 316 317 318 319 320 321 322 323

        transform_pass.apply(main_graph)

    if len(quant_dequant_ops) > 0:
        quant_dequant_pass = AddQuantDequantPass(
            scope=scope,
            place=place,
            moving_rate=config['moving_rate'],
            quant_bits=config['activation_bits'],
            skip_pattern=config['not_quant_pattern'],
            quantizable_op_type=quant_dequant_ops)
        quant_dequant_pass.apply(main_graph)
F
ftian 已提交
324

325 326 327 328
    out_scale_training_pass = OutScaleForTrainingPass(
        scope=scope, place=place, moving_rate=config['moving_rate'])
    out_scale_training_pass.apply(main_graph)

329 330 331 332 333 334 335 336 337
    if (weight_preprocess_func is not None or
            act_preprocess_func is not None) and not for_test:
        _logger.info(
            "When a preprocess_func is used in quant_aware, Need to save a mapping table to match variable names in the convert phase."
        )
        _logger.info("The mapping table is saved as '{}'.".format(
            VARS_MAPPING_TABLE))
        save_dict(main_graph.out_node_mapping_table)

Y
yukavio 已提交
338
    if for_test or return_program:
F
ftian 已提交
339 340
        quant_program = main_graph.to_program()
    else:
B
Bai Yifan 已提交
341
        quant_program = paddle.static.CompiledProgram(main_graph.graph)
F
ftian 已提交
342 343 344
    return quant_program


345 346 347 348 349 350 351 352 353 354 355 356 357
def quant_post_static(
        executor,
        model_dir,
        quantize_model_path,
        batch_generator=None,
        sample_generator=None,
        model_filename=None,
        params_filename=None,
        save_model_filename='__model__',
        save_params_filename='__params__',
        batch_size=16,
        batch_nums=None,
        scope=None,
X
XGZhang 已提交
358 359 360
        algo='hist',
        hist_percent=0.9999,
        bias_correction=False,
361 362 363 364 365 366
        quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"],
        is_full_quantize=False,
        weight_bits=8,
        activation_bits=8,
        activation_quantize_type='range_abs_max',
        weight_quantize_type='channel_wise_abs_max',
367
        optimize_model=False,
368 369
        is_use_cache_file=False,
        cache_dir="./temp_post_training"):
F
ftian 已提交
370
    """
371 372 373 374
    The function utilizes static post training quantization method to
    quantize the fp32 model. It uses calibrate data to calculate the
    scale factor of quantized variables, and inserts fake quantization
    and dequantization operators to obtain the quantized model.
S
slf12 已提交
375

F
ftian 已提交
376
    Args:
B
Bai Yifan 已提交
377
        executor(paddle.static.Executor): The executor to load, run and save the 
S
slf12 已提交
378
            quantized model.
S
slf12 已提交
379
        model_dir(str): The path of fp32 model that will be quantized, and 
B
Bai Yifan 已提交
380
            the model and params that saved by ``paddle.static.io.save_inference_model`` 
S
slf12 已提交
381 382
            are under the path.
        quantize_model_path(str): The path to save quantized model using api
B
Bai Yifan 已提交
383
            ``paddle.static.io.save_inference_model``.
384 385 386 387
        batch_generator(Python Generator): The batch generator provides 
                calibrate data for DataLoader, and it returns a batch every
                time. For sample_generator and batch_generator, only one
                can be set. Beisdes, batch_generator supports lod tensor.
S
slf12 已提交
388 389
        sample_generator(Python Generator): The sample generator provides 
            calibrate data for DataLoader, and it only returns a sample every time.
S
slf12 已提交
390
        model_filename(str, optional): The name of model file. If parameters 
391
            are saved in separate files, set it as 'None'. Default: 'None'.
S
slf12 已提交
392
        params_filename(str, optional): The name of params file.
S
slf12 已提交
393 394
                When all parameters are saved in a single file, set it 
                as filename. If parameters are saved in separate files, 
395
                set it as 'None'. Default : 'None'.
396 397 398
        save_model_filename(str): The name of model file to save the quantized inference program.  Default: '__model__'.
        save_params_filename(str): The name of file to save all related parameters. 
                If it is set None, parameters will be saved in separate files. Default: '__params__'.
S
slf12 已提交
399
        batch_size(int, optional): The batch size of DataLoader, default is 16.
S
slf12 已提交
400
        batch_nums(int, optional): If batch_nums is not None, the number of calibrate 
S
slf12 已提交
401 402
                        data is 'batch_size*batch_nums'. If batch_nums is None, use all data
                        generated by sample_generator  as calibrate data.
B
Bai Yifan 已提交
403 404
        scope(paddle.static.Scope, optional): The scope to run program, use it to load 
                        and save variables. If scope is None, will use paddle.static.global_scope().
X
XGZhang 已提交
405 406 407 408 409 410 411 412 413
        algo(str, optional): If algo='KL', use KL-divergenc method to 
                        get the scale factor. If algo='hist', use the hist_percent of histogram 
                        to get the scale factor. If algo='mse', search for the best scale factor which
                        makes the mse loss minimal. Use one batch of data for mse is enough. If 
                        algo='avg', use the average of abs_max values  to get the scale factor. If 
                        algo='abs_max', use abs_max method to get the scale factor. Default: 'hist'.
        hist_percent(float, optional): The percentile of histogram for algo hist.Default:0.9999.
        bias_correction(bool, optional): Bias correction method of https://arxiv.org/abs/1810.05723.
                        Default: False.
S
slf12 已提交
414
        quantizable_op_type(list[str], optional): The list of op types
415
                        that will be quantized. Default: ["conv2d", "depthwise_conv2d", 
S
slf12 已提交
416
                        "mul"].
L
Liufang Sang 已提交
417 418
        weight_bits(int, optional): quantization bit number for weights.
        activation_bits(int): quantization bit number for activation.
419 420 421 422 423 424 425 426 427
	activation_quantize_type(str): quantization type for activation,
                now support 'range_abs_max', 'moving_average_abs_max' and 'abs_max'.
                This parameter only specifies the fake ops in 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. 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'. Compared to 'abs_max',
                the model accuracy is usually higher when using 'channel_wise_abs_max'.
428 429
        is_full_quantize(bool): if True, apply quantization to all supported quantizable op type.
                        If False, only apply quantization to the input quantizable_op_type. Default is False.
430 431 432 433 434
        optimize_model(bool, optional): If set optimize_model as True, it applies some 
                passes to optimize the model before quantization. So far, the place of
                executor must be cpu it supports fusing batch_norm into convs.
        is_use_cache_file(bool): This param is deprecated.
        cache_dir(str): This param is deprecated.
435
    
S
slf12 已提交
436 437
    Returns:
        None
F
ftian 已提交
438
    """
S
slf12 已提交
439
    post_training_quantization = PostTrainingQuantization(
S
slf12 已提交
440 441
        executor=executor,
        sample_generator=sample_generator,
442
        batch_generator=batch_generator,
S
slf12 已提交
443 444 445 446 447 448 449
        model_dir=model_dir,
        model_filename=model_filename,
        params_filename=params_filename,
        batch_size=batch_size,
        batch_nums=batch_nums,
        scope=scope,
        algo=algo,
X
XGZhang 已提交
450 451
        hist_percent=hist_percent,
        bias_correction=bias_correction,
S
slf12 已提交
452
        quantizable_op_type=quantizable_op_type,
453
        is_full_quantize=is_full_quantize,
L
Liufang Sang 已提交
454 455
        weight_bits=weight_bits,
        activation_bits=activation_bits,
456 457
        activation_quantize_type=activation_quantize_type,
        weight_quantize_type=weight_quantize_type,
458
        optimize_model=optimize_model)
S
slf12 已提交
459
    post_training_quantization.quantize()
460 461 462 463
    post_training_quantization.save_quantized_model(
        quantize_model_path,
        model_filename=save_model_filename,
        params_filename=save_params_filename)
F
ftian 已提交
464

465

466 467 468 469 470
# We have changed the quant_post to quant_post_static.
# For compatibility, we keep quant_post api for now, and it will be
# deprecated in the future.
quant_post = quant_post_static

F
ftian 已提交
471

472
def convert(program, place, config=None, scope=None, save_int8=False):
F
ftian 已提交
473
    """
474 475
    convert quantized and well-trained ``program`` to final  quantized
    ``program``that can be used to  save ``inference model``.
476
    
F
ftian 已提交
477
    Args:
B
Bai Yifan 已提交
478 479
        program(paddle.static.Program): quantized and well-trained ``test program``.
        place(paddle.CPUPlace or paddle.CUDAPlace): This parameter represents
480 481 482 483
                the executor run on which device.
        config(dict, optional): configs for convert. if set None, will use
                default config. It must be same with config that used in
                'quant_aware'. Default is None.
B
Bai Yifan 已提交
484
        scope(paddle.static.Scope, optional):  Scope records the mapping between
485 486
                variable names and variables, similar to brackets in
                programming languages. Usually users can use
B
Bai Yifan 已提交
487
                `paddle.static.global_scope <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_.
488
                When ``None`` will use 
B
Bai Yifan 已提交
489
                `paddle.static.global_scope() <https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/api_cn/executor_cn/global_scope_cn.html>`_
490 491 492 493
                . Default: ``None``.
        save_int8: Whether to return ``program`` which model parameters'
                dtype is ``int8``. This parameter can only be used to
                get model size. Default: ``False``.
494 495 496

    Returns:
        Tuple : freezed program which can be used for inference.
B
Bai Yifan 已提交
497 498 499
                when ``save_int8`` is False, return ``freezed_program(paddle.static.Program)``.
                when ``save_int8`` is True, return ``freezed_program(paddle.static.Program)``
                and ``freezed_program_int8(paddle.static.Program)``
F
ftian 已提交
500
    """
B
Bai Yifan 已提交
501
    scope = paddle.static.global_scope() if not scope else scope
502 503 504 505 506 507 508

    if config is None:
        config = _quant_config_default
    else:
        assert isinstance(config, dict), "config must be dict"
        config = _parse_configs(config)
    _logger.info("convert config {}".format(config))
F
ftian 已提交
509 510
    test_graph = IrGraph(core.Graph(program.desc), for_test=True)

511 512 513
    out_scale_infer_pass = OutScaleForInferencePass(scope=scope)
    out_scale_infer_pass.apply(test_graph)

F
ftian 已提交
514 515 516 517 518
    # Freeze the graph after training by adjusting the quantize
    # operators' order for the inference.
    freeze_pass = QuantizationFreezePass(
        scope=scope,
        place=place,
519 520
        weight_bits=config['weight_bits'],
        activation_bits=config['activation_bits'],
521 522
        weight_quantize_type=config['weight_quantize_type'])

523 524 525
    if os.path.exists(VARS_MAPPING_TABLE):
        test_graph.out_node_mapping_table = load_dict()

F
ftian 已提交
526 527 528 529
    freeze_pass.apply(test_graph)
    freezed_program = test_graph.to_program()

    if save_int8:
530
        convert_int8_pass = ConvertToInt8Pass(scope=scope, place=place)
F
ftian 已提交
531 532 533 534 535
        convert_int8_pass.apply(test_graph)
        freezed_program_int8 = test_graph.to_program()
        return freezed_program, freezed_program_int8
    else:
        return freezed_program
L
Liufang Sang 已提交
536 537


538
def quant_post_dynamic(model_dir,
539 540 541 542 543 544 545 546
                       save_model_dir,
                       model_filename=None,
                       params_filename=None,
                       save_model_filename=None,
                       save_params_filename=None,
                       quantizable_op_type=["conv2d", "mul"],
                       weight_bits=8,
                       generate_test_model=False):
L
Liufang Sang 已提交
547
    '''
548 549 550 551 552 553 554
    The function utilizes static post training quantization method to
    quantize the fp32 model. In details, it quantizes the weight of some
    ops from float32 to int8/16. For the quantized model, there are two
    kinds of calculation method in the reference stage. Firstly, the
    quantized weight will be dequantized to float32, and then apply the
    float32 calculation. Secondly, collect the quantized scales of the
    inputs, and then apply the int8 calculation.
L
Liufang Sang 已提交
555 556 557
        
    Args:
        model_dir(str): The path of the fp32 model that will be quantized,
558
                and the model and params files are under the path.
L
Liufang Sang 已提交
559
        save_model_dir(str): The path to save the quantized model.
560 561 562 563 564 565 566 567
        model_filename(str, optional): The name of file used 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 used 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'.
L
Liufang Sang 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
        save_model_dir(str): The path used 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", "depthwise_conv2d", "mul"].
        weight_bits(int, optional): The bits for the quantized weight, 
                and it should be 8 or 16. Default is 8.
        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 
                the fake quantized model and test the accuracy on GPU or CPU.
    '''

    weight_quant = WeightQuantization(
        model_dir=model_dir,
        model_filename=model_filename,
        params_filename=params_filename)
592

L
Liufang Sang 已提交
593 594 595 596 597 598 599
    weight_quant.quantize_weight_to_int(
        save_model_dir=save_model_dir,
        save_model_filename=save_model_filename,
        save_params_filename=save_params_filename,
        quantizable_op_type=quantizable_op_type,
        weight_bits=weight_bits,
        generate_test_model=generate_test_model)
600 601 602 603 604


# We have changed the quant_post_only_weight to quant_post_dynamic.
# For compatibility, we keep quant_post_only_weight api for now,
# and it will be deprecated in the future.
605
quant_post_only_weight = quant_post_dynamic