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

import collections
import logging
import numpy as np
from .... import core
from ....framework import Program, Operator, Variable, program_guard
20
from ....executor import global_scope
C
cc 已提交
21 22 23 24 25 26 27 28 29 30
from .... import unique_name
from ....layer_helper import LayerHelper
from ....param_attr import ParamAttr
from ....initializer import Constant
from ....log_helper import get_logger

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


31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
def find_next_ops(block, var_name):
    """
    Find all followed ops for the input variable.
    """
    res_ops = []
    for op in block.ops:
        if var_name in op.input_arg_names:
            res_ops.append(op)
    return res_ops


def load_variable_data(scope, var_name):
    '''
    Load variable value from scope
    '''
    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())


C
cc 已提交
52 53 54 55 56
class QuantizeTranspilerV2(object):
    def __init__(self,
                 weight_bits=8,
                 activation_bits=8,
                 weight_quantize_type='abs_max',
57 58 59 60 61 62
                 activation_quantize_type='moving_average_abs_max',
                 quantizable_op_type=[
                     'conv2d',
                     'depthwise_conv2d',
                     'mul',
                 ],
C
cc 已提交
63 64
                 skip_pattern=['skip_quant']):
        """
65
        Apply fake quant for the quantized ops. 
C
cc 已提交
66 67 68 69 70

        Args:
            weight_bits(int): the bit of quantized weight.
            activation_bits(int): the bit of quantized activation.
            weight_quantize_type(str): the quantization type for weight.
71
                Only support to be 'abs_max' and 'channel_wise_abs_max'.
C
cc 已提交
72
            activation_quantize_type(str): the quantization type for activation.
73
                Only support to be 'abs_max' and 'moving_average_abs_max'.
C
cc 已提交
74 75 76 77 78 79 80 81
            quantizable_op_type(str): set the op type for quantization.
            skip_pattern(str|list): The user-defined quantization skip pattern, which
                will be presented in the name scope of an op. When the skip pattern is
                detected in an op's name scope, the corresponding op will not be quantized.
        """
        self._weight_bits = weight_bits
        self._activation_bits = activation_bits

82 83 84 85 86 87
        assert activation_quantize_type in \
            ["abs_max", "moving_average_abs_max"], \
            "activation_quantize_type should be abs_max " \
            "or moving_average_abs_max for now."
        assert weight_quantize_type in ["abs_max", "channel_wise_abs_max"], \
            "weight_quantize_type should be abs_max or channel_wise_abs_max."
C
cc 已提交
88 89 90
        self._activation_quantize_type = activation_quantize_type
        self._weight_quantize_type = weight_quantize_type

91 92 93
        for op_type in quantizable_op_type:
            assert op_type in ['conv2d', 'depthwise_conv2d', 'mul'], \
                "Quantize op should be ['conv2d', 'depthwise_conv2d', 'mul']"
C
cc 已提交
94 95 96 97 98 99
        self._quantizable_ops = quantizable_op_type
        self._quantizable_grad_ops = [
            '%s_grad' % (op) for op in self._quantizable_ops
        ]

        self._skip_pattern = skip_pattern
100
        self._helper = LayerHelper(self.__class__.__name__)
C
cc 已提交
101

102 103 104 105
        self._moving_rate = 0.9
        self._out_ch_axis1_ops = ['conv2d_transpose', 'mul', 'matmul']

    def apply(self, program, startup_program, is_test=False):
C
cc 已提交
106 107 108 109 110 111
        """
        Apply quantization to fluid Program.

        Args:
            program(Program): the train or test program to be quantized.
            startup_program(Program): the corresponding startup_program.
112
            is_test(bool): Whethe the program is used for test.
C
cc 已提交
113 114 115 116 117 118 119 120
        Returns:
            None
        """
        assert isinstance(program, Program), \
            "program must be the instance of Program"
        assert isinstance(startup_program, Program), \
            "startup_program must be the instance of Program"

121
        var_rename_map = [
C
cc 已提交
122 123 124 125 126 127 128 129
            collections.OrderedDict() for _ in range(len(program.blocks))
        ]
        with program_guard(program, startup_program):
            for block in program.blocks:
                ops = list(block.ops)
                for op in ops:
                    if op.type in self._quantizable_ops and \
                        (not self._is_skip_quant(op)):
130 131 132
                        self._transform_forward(block, op, var_rename_map,
                                                is_test)

C
cc 已提交
133 134 135 136 137
            for block in program.blocks:
                ops = list(block.ops)
                for op in ops:
                    if op.type in self._quantizable_grad_ops and \
                        (not self._is_skip_quant(op)):
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
                        self._transform_backward(block, op, var_rename_map)

    def convert(self, test_program, scope=None):
        """
        Convert the test program. 
        Get the out scale from the moving_average_abs_max_scale op and save the
        out scale into the quantized op. 
        Args:
            test_program(Program): the test program to be converted.
            scope(fluid.Scope, optional): The scope of the program, use it to load 
                and save variables. If scope=None, get scope by global_scope(). 
        """
        scope = global_scope() if scope == None else scope

        for block in test_program.blocks:
            for op in block.ops:
                if op.has_attr("quantization_type") \
                    and op.attr("quantization_type") == "qat_with_weight":
                    # quant op -> var1 -> fake op -> var2
                    assert len(op.output_arg_names) == 1
                    var1_name = op.output_arg_names[0]

                    fake_ops = find_next_ops(block, var1_name)
                    assert len(fake_ops) == 1
                    fake_op = fake_ops[0]
                    assert fake_op.type == "moving_average_abs_max_scale"

                    out_scale_name = fake_op.output("OutScale")
                    out_threshold = load_variable_data(scope, out_scale_name[0])
                    op._set_attr("out_threshold", float(out_threshold))

                    var2_name = fake_op.output("Out")[0]
                    op._rename_output(var1_name, var2_name)
                    fake_op._rename_output(var2_name, var1_name)

    def _transform_forward(self, block, op, var_rename_map, is_test):
        """
        Insert fake quant op before the target ops.
        """
        op._set_attr("quantization_type", "qat_with_weight")

        # insert fake quant op before the quantized op
        for in_name in op.input_arg_names:
            block_id = block.idx
            idx = block.ops.index(op)

            if in_name in var_rename_map[block_id]:
                new_in_name = var_rename_map[block_id][in_name]
            else:
                in_var = block.var(in_name)
                if in_var.dtype != core.VarDesc.VarType.FP32:
                    continue

                quant_bits = self._weight_bits if in_var.persistable \
                        else self._activation_bits
                quant_type = self._weight_quantize_type if in_var.persistable \
                        else self._activation_quantize_type

                if quant_type == "abs_max":
                    new_var = self._insert_abs_max_fq_op(block, idx, in_var,
                                                         quant_bits)
                elif quant_type == "moving_average_abs_max":
                    new_var = self._insert_ma_abs_max_fq_op(block, idx, in_var,
                                                            quant_bits, is_test)
                elif quant_type == "channel_wise_abs_max":
                    ch_axis = 1 if op.type in self._out_ch_axis1_ops else 0
                    new_var = self._insert_pc_abs_max_fq_op(block, idx, in_var,
                                                            quant_bits, ch_axis)
                else:
                    _logger.error("Don't support the quant_type: %s" %
                                  quant_type)
                    continue

                new_in_name = new_var.name
                var_rename_map[block_id][in_name] = new_in_name

            op._rename_input(in_name, new_in_name)

        # insert out scale op followed the quantized op
        for out_name in op.output_arg_names:
            next_ops = find_next_ops(block, out_name)

            idx = block.ops.index(op)
            out_var = block.var(out_name)
            new_out_var = self._insert_ma_abs_max_scale_op(
                block, idx + 1, out_var, is_test, True)

            for next_op in next_ops:
                if "_grad" not in next_op.type:
                    next_op._rename_input(out_name, new_out_var.name)
C
cc 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

    def _is_skip_quant(self, op):
        """
        Analyse whether the op should skip quantization or not.
        """
        user_skipped = False
        if isinstance(self._skip_pattern, list):
            user_skipped = op.has_attr("op_namescope") and \
                            any(pattern in op.attr("op_namescope") \
                                for pattern in self._skip_pattern)
        elif isinstance(self._skip_pattern, str):
            user_skipped = op.has_attr("op_namescope") and \
                            op.attr("op_namescope").find(
                                self._skip_pattern) != -1
        return user_skipped

244 245 246 247 248
    def _transform_backward(self, block, op, var_rename_map):
        """
        Update the backword of the target ops.
        Note: for the grad ops, only rename the input, skip rename the output.
        """
C
cc 已提交
249 250 251
        block_id = block.idx
        no_dequanted_input_vars = True
        for name in op.input_arg_names:
252 253 254
            if name in var_rename_map[block_id]:
                new_var_name = var_rename_map[block_id][name]
                op._rename_input(name, new_var_name)
C
cc 已提交
255 256 257 258 259
                no_dequanted_input_vars = False
        if no_dequanted_input_vars:
            raise ValueError("There is no dequanted inputs for op %s." %
                             (op.type))

260 261 262 263
    def _insert_abs_max_fq_op(self, block, idx, in_var, quant_bits):
        """
        Inset abs max fake quant op.
        """
C
cc 已提交
264 265 266 267 268
        quant_dequant_var = block.create_var(
            type=in_var.type,
            name="{}.quant_dequant".format(in_var.name),
            shape=in_var.shape,
            dtype=in_var.dtype)
269
        scale_var = self._helper.create_parameter(
C
cc 已提交
270 271
            attr=ParamAttr(
                name="{}.quant_dequant.scale".format(in_var.name),
272
                initializer=Constant(0.),
C
cc 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
                trainable=False),
            shape=[1],
            dtype=in_var.dtype)
        scale_var.stop_gradient = True

        inputs = {'X': in_var}
        outputs = {'Out': quant_dequant_var, 'OutScale': scale_var}
        attrs = {'bit_length': quant_bits}
        block._insert_op(
            idx,
            type='fake_quantize_dequantize_abs_max',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs)
        return quant_dequant_var
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

    def _insert_ma_abs_max_fq_op(self, block, idx, in_var, quant_bits, is_test):
        """
        Insert moving average abs max fake quant op.
        """
        quant_dequant_var = block.create_var(
            type=in_var.type,
            name="{}.quant_dequant".format(in_var.name),
            shape=in_var.shape,
            dtype=in_var.dtype)

        scale_var = self._helper.create_parameter(
            attr=ParamAttr(
                name="{}.quant_dequant.scale".format(in_var.name),
                initializer=Constant(0.),
                trainable=False),
            shape=[1],
            dtype=in_var.dtype)
        scale_var.stop_gradient = True

        if not is_test:
            state_var = self._helper.create_parameter(
                attr=ParamAttr(
                    name="{}.quant_dequant.state".format(in_var.name),
                    initializer=Constant(0),
                    trainable=False),
                shape=[1],
                dtype=in_var.dtype)
            state_var.stop_gradient = True

            accum_var = self._helper.create_parameter(
                attr=ParamAttr(
                    name="{}.quant_dequant.accum".format(in_var.name),
                    initializer=Constant(0),
                    trainable=False),
                shape=[1],
                dtype=in_var.dtype)
            accum_var.stop_gradient = True

        attrs = {
            'moving_rate': self._moving_rate,
            'bit_length': quant_bits,
            'is_test': is_test
        }
        inputs = {'X': in_var, 'InScale': scale_var}
        outputs = {'Out': quant_dequant_var, 'OutScale': scale_var}
        if not is_test:
            inputs['InState'] = state_var
            inputs['InAccum'] = accum_var
            outputs['OutState'] = state_var
            outputs['OutAccum'] = accum_var

        block._insert_op(
            idx,
            type='fake_quantize_dequantize_moving_average_abs_max',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs)
        return quant_dequant_var

    def _insert_pc_abs_max_fq_op(self, block, idx, in_var, quant_bits, ch_axis):
        """
        Insert per channel abs max fake quant op.
        """
        quant_dequant_var = block.create_var(
            type=in_var.type,
            name="{}.quant_dequant".format(in_var.name),
            shape=in_var.shape,
            dtype=in_var.dtype)

        scale_var = self._helper.create_parameter(
            attr=ParamAttr(
                name="{}.quant_dequant.scale".format(in_var.name),
                initializer=Constant(0.),
                trainable=False),
            shape=[in_var.shape[ch_axis]],
            dtype=in_var.dtype)
        scale_var.stop_gradient = True

        inputs = {'X': in_var}
        outputs = {'Out': quant_dequant_var, 'OutScale': scale_var}
        attrs = {'bit_length': quant_bits, 'quant_axis': ch_axis}
        block._insert_op(
            idx,
            type='fake_channel_wise_quantize_dequantize_abs_max',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs)
        return quant_dequant_var

    def _insert_ma_abs_max_scale_op(self,
                                    block,
                                    idx,
                                    in_var,
                                    is_test,
                                    has_out_var=False):
        """
        Insert moving average abs max scale op.
        """
        scale_var = self._helper.create_parameter(
            attr=ParamAttr(
                name="{}.outscale.scale".format(in_var.name),
                initializer=Constant(0.),
                trainable=False),
            shape=[1],
            dtype=in_var.dtype)
        scale_var.stop_gradient = True

        attrs = {'moving_rate': self._moving_rate, 'is_test': is_test}
        inputs = {'X': in_var}
        outputs = {'OutScale': scale_var}

        if not is_test:
            state_var = self._helper.create_parameter(
                attr=ParamAttr(
                    name="{}.outscale.state".format(in_var.name),
                    initializer=Constant(0),
                    trainable=False),
                shape=[1],
                dtype=in_var.dtype)
            state_var.stop_gradient = True

            accum_var = self._helper.create_parameter(
                attr=ParamAttr(
                    name="{}.outscale.accum".format(in_var.name),
                    initializer=Constant(0),
                    trainable=False),
                shape=[1],
                dtype=in_var.dtype)
            accum_var.stop_gradient = True

            inputs['InState'] = state_var
            inputs['InAccum'] = accum_var
            outputs['OutState'] = state_var
            outputs['OutAccum'] = accum_var

        if has_out_var:
            out_var = block.create_var(
                type=in_var.type,
                name="{}.tmp".format(in_var.name),
                shape=in_var.shape,
                dtype=in_var.dtype)

            outputs['Out'] = out_var

        block._insert_op(
            idx,
            type='moving_average_abs_max_scale',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs)

        if has_out_var:
            return out_var