quantize_transpiler_v2.py 17.2 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
from .... import unique_name
from ....layer_helper import LayerHelper
from ....param_attr import ParamAttr
from ....initializer import Constant
from ....log_helper import get_logger

27 28 29
_logger = get_logger(
    __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s'
)
C
cc 已提交
30 31


32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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)
48
    assert var_node is not None, "Cannot find " + var_name + " in scope."
49 50 51
    return np.array(var_node.get_tensor())


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

        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.
73
                Only support to be 'abs_max' and 'channel_wise_abs_max'.
C
cc 已提交
74
            activation_quantize_type(str): the quantization type for activation.
75
                Only support to be 'abs_max' and 'moving_average_abs_max'.
C
cc 已提交
76 77 78 79 80 81 82 83
            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

84 85 86 87 88
        assert activation_quantize_type in [
            "abs_max",
            "moving_average_abs_max",
        ], (
            "activation_quantize_type should be abs_max "
89
            "or moving_average_abs_max for now."
90 91 92 93 94
        )
        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 已提交
95 96 97
        self._activation_quantize_type = activation_quantize_type
        self._weight_quantize_type = weight_quantize_type

98
        for op_type in quantizable_op_type:
99 100 101 102 103
            assert op_type in [
                'conv2d',
                'depthwise_conv2d',
                'mul',
            ], "Quantize op should be ['conv2d', 'depthwise_conv2d', 'mul']"
C
cc 已提交
104 105 106 107 108 109
        self._quantizable_ops = quantizable_op_type
        self._quantizable_grad_ops = [
            '%s_grad' % (op) for op in self._quantizable_ops
        ]

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

112 113 114 115
        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 已提交
116 117 118 119 120 121
        """
        Apply quantization to fluid Program.

        Args:
            program(Program): the train or test program to be quantized.
            startup_program(Program): the corresponding startup_program.
122
            is_test(bool): Whethe the program is used for test.
C
cc 已提交
123 124 125
        Returns:
            None
        """
126 127 128 129 130 131
        assert isinstance(
            program, Program
        ), "program must be the instance of Program"
        assert isinstance(
            startup_program, Program
        ), "startup_program must be the instance of Program"
C
cc 已提交
132

133
        var_rename_map = [
C
cc 已提交
134 135 136 137 138 139
            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:
140 141 142 143 144 145
                    if op.type in self._quantizable_ops and (
                        not self._is_skip_quant(op)
                    ):
                        self._transform_forward(
                            block, op, var_rename_map, is_test
                        )
146

C
cc 已提交
147 148 149
            for block in program.blocks:
                ops = list(block.ops)
                for op in ops:
150 151 152
                    if op.type in self._quantizable_grad_ops and (
                        not self._is_skip_quant(op)
                    ):
153 154 155 156
                        self._transform_backward(block, op, var_rename_map)

    def convert(self, test_program, scope=None):
        """
157
        Convert the test program.
158
        Get the out scale from the moving_average_abs_max_scale op and save the
159
        out scale into the quantized op.
160 161
        Args:
            test_program(Program): the test program to be converted.
162 163
            scope(fluid.Scope, optional): The scope of the program, use it to load
                and save variables. If scope=None, get scope by global_scope().
164
        """
165
        scope = global_scope() if scope is None else scope
166 167 168

        for block in test_program.blocks:
            for op in block.ops:
169 170 171 172
                if (
                    op.has_attr("quantization_type")
                    and op.attr("quantization_type") == "qat_with_weight"
                ):
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
                    # 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)
205
                target_dtype = [
206 207
                    core.VarDesc.VarType.FP32,
                    core.VarDesc.VarType.FP16,
208 209
                ]
                if in_var.dtype not in target_dtype:
210 211
                    continue

212 213 214 215 216 217 218 219 220 221
                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
                )
222 223

                if quant_type == "abs_max":
224
                    new_var = self._insert_abs_max_fq_op(
225 226
                        block, idx, in_var, quant_bits
                    )
227
                elif quant_type == "moving_average_abs_max":
228
                    new_var = self._insert_ma_abs_max_fq_op(
229 230
                        block, idx, in_var, quant_bits, is_test
                    )
231 232
                elif quant_type == "channel_wise_abs_max":
                    ch_axis = 1 if op.type in self._out_ch_axis1_ops else 0
233
                    new_var = self._insert_pc_abs_max_fq_op(
234 235
                        block, idx, in_var, quant_bits, ch_axis
                    )
236
                else:
237 238 239
                    _logger.error(
                        "Don't support the quant_type: %s" % quant_type
                    )
240 241 242 243 244 245 246 247 248 249 250 251 252 253
                    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(
254 255
                block, idx + 1, out_var, is_test, True
            )
256 257 258 259

            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 已提交
260 261 262 263 264 265 266

    def _is_skip_quant(self, op):
        """
        Analyse whether the op should skip quantization or not.
        """
        user_skipped = False
        if isinstance(self._skip_pattern, list):
267 268 269 270
            user_skipped = op.has_attr("op_namescope") and any(
                pattern in op.attr("op_namescope")
                for pattern in self._skip_pattern
            )
C
cc 已提交
271
        elif isinstance(self._skip_pattern, str):
272 273 274 275
            user_skipped = (
                op.has_attr("op_namescope")
                and op.attr("op_namescope").find(self._skip_pattern) != -1
            )
C
cc 已提交
276 277
        return user_skipped

278 279 280 281 282
    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 已提交
283 284 285
        block_id = block.idx
        no_dequanted_input_vars = True
        for name in op.input_arg_names:
286 287 288
            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 已提交
289 290
                no_dequanted_input_vars = False
        if no_dequanted_input_vars:
291 292 293
            raise ValueError(
                "There is no dequanted inputs for op %s." % (op.type)
            )
C
cc 已提交
294

295 296 297 298
    def _insert_abs_max_fq_op(self, block, idx, in_var, quant_bits):
        """
        Inset abs max fake quant op.
        """
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
        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.0),
                trainable=False,
            ),
            shape=[1],
            dtype=in_var.dtype,
        )
C
cc 已提交
314 315 316 317 318
        scale_var.stop_gradient = True

        inputs = {'X': in_var}
        outputs = {'Out': quant_dequant_var, 'OutScale': scale_var}
        attrs = {'bit_length': quant_bits}
319 320 321 322 323 324 325
        block._insert_op(
            idx,
            type='fake_quantize_dequantize_abs_max',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs,
        )
C
cc 已提交
326
        return quant_dequant_var
327 328 329 330 331

    def _insert_ma_abs_max_fq_op(self, block, idx, in_var, quant_bits, is_test):
        """
        Insert moving average abs max fake quant op.
        """
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
        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.0),
                trainable=False,
            ),
            shape=[1],
            dtype=in_var.dtype,
        )
348 349 350
        scale_var.stop_gradient = True

        if not is_test:
351 352 353 354 355 356 357 358 359
            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,
            )
360 361
            state_var.stop_gradient = True

362 363 364 365 366 367 368 369 370
            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,
            )
371 372 373 374 375
            accum_var.stop_gradient = True

        attrs = {
            'moving_rate': self._moving_rate,
            'bit_length': quant_bits,
376
            'is_test': is_test,
377 378 379 380 381 382 383 384 385
        }
        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

386 387 388 389 390 391 392
        block._insert_op(
            idx,
            type='fake_quantize_dequantize_moving_average_abs_max',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs,
        )
393 394 395 396 397 398
        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.
        """
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        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.0),
                trainable=False,
            ),
            shape=[in_var.shape[ch_axis]],
            dtype=in_var.dtype,
        )
415 416 417 418 419
        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}
420 421 422 423 424 425 426
        block._insert_op(
            idx,
            type='fake_channel_wise_quantize_dequantize_abs_max',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs,
        )
427 428
        return quant_dequant_var

429 430 431
    def _insert_ma_abs_max_scale_op(
        self, block, idx, in_var, is_test, has_out_var=False
    ):
432 433 434
        """
        Insert moving average abs max scale op.
        """
435 436 437 438 439 440 441 442 443
        scale_var = self._helper.create_parameter(
            attr=ParamAttr(
                name="{}.outscale.scale".format(in_var.name),
                initializer=Constant(0.0),
                trainable=False,
            ),
            shape=[1],
            dtype=in_var.dtype,
        )
444 445 446 447 448 449 450
        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:
451 452 453 454 455 456 457 458 459
            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,
            )
460 461
            state_var.stop_gradient = True

462 463 464 465 466 467 468 469 470
            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,
            )
471 472 473 474 475 476 477 478
            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:
479 480 481 482 483 484
            out_var = block.create_var(
                type=in_var.type,
                name="{}.tmp".format(in_var.name),
                shape=in_var.shape,
                dtype=in_var.dtype,
            )
485 486 487

            outputs['Out'] = out_var

488 489 490 491 492 493 494
        block._insert_op(
            idx,
            type='moving_average_abs_max_scale',
            attrs=attrs,
            inputs=inputs,
            outputs=outputs,
        )
495 496 497

        if has_out_var:
            return out_var