quanter.py 8.5 KB
Newer Older
I
itminner 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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.

import copy
I
itminner 已提交
16 17 18 19 20 21 22 23 24
import paddle
import paddle.fluid as fluid
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
from paddle.fluid import core

I
itminner 已提交
25 26 27 28 29 30 31 32 33
QUANTIZATION_TYPES=['abs_max', 'channel_wise_abs_max', 'range_abs_max', 'moving_average_abs_max']

quant_config_default = {
        # weight quantize type, default is 'abs_max'
        'weight_quantize_type': 'abs_max',
        # activation quantize type, default is 'abs_max'
        'activation_quantize_type': 'abs_max',
        # weight quantize bit num, default is 8
        'weight_bits': 8,
Y
yangfukui 已提交
34
        # activation quantize bit num, default is 8
I
itminner 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        '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
        'quantize_op_types': ['conv2d', 'depthwise_conv2d', 'mul'],
        # 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,
        # if set quant_weight_only True, then only quantize parameters of layers which need to be quantized,
        # and activations will not be quantized.
        'quant_weight_only': False
    }

def _parse_configs(user_config):
    """
    check user configs is valid, and set default value if user not config.
    Args:
        user_config(dict):the config of user.
    Return:
        configs(dict): final configs will be used.
    """

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

    # check configs is valid
    assert configs['weight_quantize_type'] in QUANTIZATION_TYPES, \
        "Unknown weight_quantize_type: '%s'. It can only be " \
        "'abs_max' or 'channel_wise_abs_max' or 'range_abs_max' or 'moving_average_abs_max'."

    assert configs['activation_quantize_type'] in QUANTIZATION_TYPES, \
        "Unknown activation_quantize_type: '%s'. It can only be " \
        "'abs_max' or 'channel_wise_abs_max' or 'range_abs_max' or 'moving_average_abs_max'."

    assert isinstance(configs['weight_bits'], int), \
        "weight_bits must be int value, such as 8, 16, 32, etc"

    assert isinstance(configs['activation_bits'], int), \
        "activation_bits must be int value, such as 8, 16, 32, etc"

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

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

    assert isinstance(configs['dtype'], str), \
        "dtype must be a str, it can be config as 'int8', 'uint8', 'int16', etc."

    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."

    assert isinstance(configs['quant_weight_only'], bool), \
        "quant_weight_only must be bool value, if set quant_weight_only True, " \
        "then only quantize parameters of layers which need to be quantized, " \
        " and activations will not be quantized."

    return configs



def quant_aware(program, scope, place, config, for_test=False):
    """
    add trainable quantization ops in program.
    Args:
        program(fluid.Program): program
        scope(fluid.Scope): the scope to store var, when is None will use fluid.global_scope()
        place(fluid.CPUPlace or fluid.CUDAPlace): place
        config(dict): configs for quantization, default values are in quant_config_default dict.
        for_test: is for test program.
    Return:
        fluid.Program: user can finetune this quantization program to enhance the accuracy.
    """

    scope = fluid.global_scope() if not scope else scope
    assert isinstance(config, dict), "config must be dict"

Y
yangfukui 已提交
118 119
    assert 'weight_quantize_type' in config.keys(), 'weight_quantize_type must be configured'
    assert 'activation_quantize_type' in config.keys(), 'activation_quantize_type must be configured'
I
itminner 已提交
120 121

    config = _parse_configs(config)
I
itminner 已提交
122 123 124 125
    main_graph = IrGraph(core.Graph(program.desc), for_test=for_test)

    transform_pass = QuantizationTransformPass(
        scope=scope, place=place,
I
itminner 已提交
126 127
        weight_bits=config['weight_bits'],
        activation_bits=config['activation_bits'],
Y
yangfukui 已提交
128 129
        activation_quantize_type=config['activation_quantize_type'],
        weight_quantize_type=config['weight_quantize_type'],
I
itminner 已提交
130 131
        window_size=config['window_size'],
        moving_rate=config['moving_rate'],
I
itminner 已提交
132 133 134 135
        skip_pattern=''#not_quant_pattern
    )


I
itminner 已提交
136 137 138 139 140
    transform_pass.apply(main_graph)

    if for_test:
        quant_program = main_graph.to_program()
    else:
I
itminner 已提交
141
        quant_program = fluid.CompiledProgram(main_graph.graph)
I
itminner 已提交
142 143 144
    return quant_program

def quant_post(program, scope, place, config):
I
itminner 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158
    """
    add quantization ops in program. the program returned is not trainable.
    Args:
        program(fluid.Program): program
        scope(fluid.Scope): the scope to store var, when is None will use fluid.global_scope()
        place(fluid.CPUPlace or fluid.CUDAPlace): place
        config(dict): configs for quantization, default values are in quant_config_default dict.
        for_test: is for test program.
    Return:
        fluid.Program: the quantization program is not trainable.
    """

    scope = fluid.global_scope() if not scope else scope
    assert isinstance(config, dict), "config must be dict"
Y
yangfukui 已提交
159 160
    assert 'weight_quantize_type' in config.keys(), 'weight_quantize_type must be configured'
    assert 'activation_quantize_type' in config.keys(), 'activation_quantize_type must be configured'
I
itminner 已提交
161 162

    config = _parse_configs(config)
I
itminner 已提交
163

I
itminner 已提交
164
    main_graph = IrGraph(core.Graph(program.desc), for_test=True)
I
itminner 已提交
165 166 167

    transform_pass = QuantizationTransformPass(
        scope=scope, place=place,
Y
yangfukui 已提交
168 169
        activation_quantize_type=config['activation_quantize_type'],
        weight_quantize_type=config['weight_quantize_type'])
I
itminner 已提交
170 171 172 173 174 175 176
    transform_pass.apply(main_graph)


    quant_program = main_graph.to_program()
    return quant_program

def convert(program, scope, place, config, save_int8=False):
I
itminner 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190
    """
    add quantization ops in program. the program returned is not trainable.
    Args:
        program(fluid.Program): program
        scope(fluid.Scope): the scope to store var, when is None will use fluid.global_scope()
        place(fluid.CPUPlace or fluid.CUDAPlace): place
        config(dict): configs for quantization, default values are in quant_config_default dict.
        save_int8: is export int8 freezed program.
    Return:
        fluid.Program: freezed program which can be used for inference.
                       parameters is float32 type, but it's value in int8 range.
        fluid.Program: freezed int8 program which can be used for inference.
    """

I
itminner 已提交
191 192
    test_graph = IrGraph(core.Graph(program.desc), for_test=True)

I
itminner 已提交
193
    # Freeze the graph after training by adjusting the quantize
I
itminner 已提交
194 195 196 197
    # operators' order for the inference.
    freeze_pass = QuantizationFreezePass(
        scope=scope,
        place=place,
Y
yangfukui 已提交
198
        weight_quantize_type=config['weight_quantize_type'])
I
itminner 已提交
199 200 201 202 203 204 205 206 207 208 209 210
    freeze_pass.apply(test_graph)
    freezed_program = test_graph.to_program()
    freezed_program_int8 = None

    if save_int8:
        convert_int8_pass = ConvertToInt8Pass(scope=fluid.global_scope(), place=place)
        convert_int8_pass.apply(test_graph)
        freezed_program_int8 = test_graph.to_program()

    return freezed_program, freezed_program_int8