qat.py 25.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

G
guofei 已提交
15
import collections
16 17 18
import logging
import numpy as np
import sys
19
import os
20 21
import warnings

22
import paddle
23
import paddle.nn.quant.quant_layers as quant_layers
24
from paddle.fluid import dygraph, core, framework, unique_name
25
from paddle.fluid.framework import IrGraph
26
from paddle.fluid.executor import Executor, global_scope
27 28
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.initializer import Constant
29 30
from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX
from paddle.fluid.io import load_inference_model, save_inference_model
31
from paddle.fluid.log_helper import get_logger
32
from .. import quantization_pass
C
cc 已提交
33
from . import utils
34

C
cc 已提交
35
__all__ = ['ImperativeQuantAware']
36 37 38 39 40 41 42

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


class ImperativeQuantAware(object):
    """
43
    Applying quantization aware training (QAT) to the dgraph model.
44 45
    """

46 47 48 49 50 51 52 53 54 55 56 57
    def __init__(
            self,
            quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'],
            weight_quantize_type='abs_max',
            activation_quantize_type='moving_average_abs_max',
            weight_bits=8,
            activation_bits=8,
            moving_rate=0.9,
            weight_preprocess_layer=None,
            act_preprocess_layer=None,
            weight_quantize_layer=None,
            act_quantize_layer=None):
C
cc 已提交
58
        """
59 60 61
        The constructor for ImperativeQuantAware.

        Args:
62 63
            quantizable_layer_type(list[str | layer]): List the type of
                layers that will be quantized. Default is ['Conv2D', 'Linear'].
64
            weight_quantize_type(str): quantization type for weights,
65
                which supports 'abs_max' and 'channel_wise_abs_max'.
66 67
            activation_quantize_type(str): quantization type for activations,
                which supports 'abs_max' and 'moving_average_abs_max' now.
C
cc 已提交
68 69 70 71 72
                If using 'abs_max' mode, the quantization scale will be
                calculated dynamically each step in both training and testing
                period. If using 'moving_average_abs_max', the static
                quantization scale will be calculated during training and
                used in inference.
73 74
            weight_bits(int): quantization bit number for weights, whereas
                the bias is not quantized.
C
cc 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
            activation_bits(int): quantization bit number for activations.
            moving_rate(float): the parameter for 'moving_average_abs_max'
                quantization.
            weight_preprocess_layer(paddle.nn.Layer, optional): A paddle
                Layer that defines how to preprocess weight before quantization.
                Using this can quickly test if user's preprocess method works
                or not. The 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_layer(paddle.nn.Layer, optional): A paddle Layer
                that defines how to preprocess activation before quantization.
                Using this can quickly test if user's preprocess method works
                or not. The input is non-quantized activation and function returns
                processed activation to be quantized.
                If None, the activation will be quantized directly.
                Default is None.
            weight_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that
                defines how to quantize weight.
94 95 96
                Using this can quickly test if user's quantization method works or not.
                In this layer, user should both define quantization method and
                dequantization method, that is, the function's input is non-quantized
C
cc 已提交
97 98 99 100 101
                weight and returns dequantized weight.
                If None, will use uantization op defined by 'weight_quantize_type'.
                Default is None.
            act_quantize_layer(paddle.nn.Layer, optional): A paddle Layer that defines
                how to quantize activation.
102 103 104
                Using this can quickly test if user's quantization method works or not.
                In this layer, user should both define quantization method and
                dequantization method, that is, the function's input is non-quantized
C
cc 已提交
105 106 107
                activation and returns dequantized activation. 
                If None, will use quantization op defined by 'activation_quantize_type'.
                Default is None.
108

109
        Note:
C
cc 已提交
110 111 112 113
            If user sets attribute 'skip_quant' to a Layer that support dynamic
            quantization and sets it to true, the layer would not be quantized
            during training. If this attribute is not sets or the attribute is
            false, the Layer would be qunatized in training.
114 115

        Examples 1:
116 117
        .. code-block:: python

118
            import paddle
119 120
            from paddle.fluid.contrib.slim.quantization \
                import ImperativeQuantAware
121
            from paddle.vision.models \
122 123 124 125 126 127 128 129 130 131
                import resnet
            
            model = resnet.resnet50(pretrained=True)

            imperative_qat = ImperativeQuantAware(
                weight_quantize_type='abs_max',
                activation_quantize_type='moving_average_abs_max')
            
            # Add the fake quant logical.
            # The original model will be rewrite.
132
            # The outscale of outputs in supportted layers would be calculated.
133 134 135 136 137 138
            imperative_qat.quantize(model)

            # Fine-tune the quantized model
            # ...
            
            # Save quant model for the inference.
139
            imperative_qat.save_quantized_model(
140 141 142 143 144
                layer=model,
                model_path="./resnet50_qat",
                input_spec=[
                    paddle.static.InputSpec(
                    shape=[None, 3, 224, 224], dtype='float32')])
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

        Examples 2:
        .. code-block:: python

            import paddle
            from paddle.fluid.contrib.slim.quantization \
                import ImperativeQuantAware

            class ImperativeModel(paddle.nn.Layer):
                def __init__(self):
                    super(ImperativeModel, self).__init__()
                    # self.linear_0 would skip the quantization.
                    self.linear_0 = paddle.nn.Linear(784, 400)
                    self.linear_0.skip_quant = True

                    # self.linear_1 would not skip the quantization.
                    self.linear_1 = paddle.nn.Linear(400, 10)
                    self.linear_1.skip_quant = False

                def forward(self, inputs):
                    x = self.linear_0(inputs)
                    x = self.linear_1(inputs)
                    return x

            model = ImperativeModel()
            imperative_qat = ImperativeQuantAware(
                weight_quantize_type='abs_max',
                activation_quantize_type='moving_average_abs_max')

            # Add the fake quant logical.
            # The original model will be rewrite.
            #
            # There is only one Layer(self.linear1) would be added the
            # fake quant logical.
            imperative_qat.quantize(model)

            # Fine-tune the quantized model
            # ...

            # Save quant model for the inference.
            imperative_qat.save_quantized_model(
                layer=model,
                model_path="./imperative_model_qat")
188 189
        """
        super(ImperativeQuantAware, self).__init__()
H
huangxu96 已提交
190

C
cc 已提交
191 192 193 194 195 196 197 198 199 200 201
        kwargs = {
            "quantizable_layer_type": quantizable_layer_type,
            "weight_quantize_type": weight_quantize_type,
            "activation_quantize_type": activation_quantize_type,
            "weight_bits": weight_bits,
            "activation_bits": activation_bits,
            "moving_rate": moving_rate,
            "weight_preprocess_layer": weight_preprocess_layer,
            "act_preprocess_layer": act_preprocess_layer,
            "weight_quantize_layer": weight_quantize_layer,
            "act_quantize_layer": act_quantize_layer
202
        }
C
cc 已提交
203 204 205

        self._quantize_inputs = ImperativeQuantizeInputs(**kwargs)

X
XGZhang 已提交
206
        self._quantize_outputs = ImperativeQuantizeOutputs(moving_rate)
207 208 209

    def quantize(self, model):
        """
C
cc 已提交
210 211 212 213 214
        According to weights' and activations' quantization types,
        the model will be added some fake quant ops, such as
        fake_quantize_dequantize_moving_average_abs_max,
        fake_quantize_dequantize_abs_max and so on. At the same time,
        the out_scale value of outputs would be calculated.
215 216

        Args:
217
            model(paddle.nn.Layer): the model to be quantized.
218 219
        Returns:
            None
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

        Examples:
        .. code-block:: python

            import paddle
            from paddle.fluid.contrib.slim.quantization \
                import ImperativeQuantAware

            class ImperativeModel(paddle.nn.Layer):
                def __init__(self):
                    super(ImperativeModel, self).__init__()
                    # self.linear_0 would skip the quantization.
                    self.linear_0 = paddle.nn.Linear(784, 400)
                    self.linear_0.skip_quant = True

                    # self.linear_1 would not skip the quantization.
                    self.linear_1 = paddle.nn.Linear(400, 10)
                    self.linear_1.skip_quant = False

                def forward(self, inputs):
                    x = self.linear_0(inputs)
                    x = self.linear_1(inputs)
                    return x

            model = ImperativeModel()
            imperative_qat = ImperativeQuantAware(
                weight_quantize_type='abs_max',
                activation_quantize_type='moving_average_abs_max')

            # Add the fake quant logical.
            # The original model will be rewrite.
            #
            # There is only one Layer(self.linear1) would be added the
            # fake quant logical.
            imperative_qat.quantize(model)
255
        """
C
cc 已提交
256 257 258
        assert isinstance(model, dygraph.Layer), \
            "The model must be the instance of dygraph.Layer."
        self._quantize_inputs.apply(model)
259
        self._quantize_outputs.apply(model)
C
cc 已提交
260 261

    def save_quantized_model(self, layer, path, input_spec=None, **config):
262 263
        self._quantize_outputs.save_quantized_model(layer, path, input_spec,
                                                    **config)
C
cc 已提交
264 265 266 267 268 269 270 271


class ImperativeQuantizeInputs(object):
    """
    Based on the input params, add the quant_dequant computational
    logic both for activation inputs and weight inputs.
    """

272 273 274 275 276 277 278 279 280 281 282 283
    def __init__(
            self,
            quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'],
            weight_quantize_type='abs_max',
            activation_quantize_type='moving_average_abs_max',
            weight_bits=8,
            activation_bits=8,
            moving_rate=0.9,
            weight_preprocess_layer=None,
            act_preprocess_layer=None,
            weight_quantize_layer=None,
            act_quantize_layer=None):
C
cc 已提交
284 285 286 287 288 289 290 291
        """
        The constructor for ImperativeQuantizeInputs. 

        Please refer to the args of ImperativeQuantAware.
        """
        super(ImperativeQuantizeInputs, self).__init__()

        self._quantizable_layer_type = tuple(
292 293
            utils.layer_name_map[layer]
            if layer in utils.layer_name_map else layer
C
cc 已提交
294 295
            for layer in quantizable_layer_type)
        for layer in self._quantizable_layer_type:
296 297
            assert not isinstance(layer, str) \
                and layer in utils.fake_quant_input_layers, \
C
cc 已提交
298 299 300 301 302
                "%s is unspported to be quantized." % layer

        quantize_type = {
            'abs_max', 'moving_average_abs_max', 'channel_wise_abs_max'
        }
303 304
        assert weight_quantize_type != 'moving_average_abs_max' \
            and weight_quantize_type in quantize_type, \
C
cc 已提交
305
            "Unsupported weight_quantize_type: %s. It can only " \
306 307 308
            "be abs_max or channel_wise_abs_max." % weight_quantize_type
        # TODO (jc): activation_quantize_type supports range_abs_max
        assert activation_quantize_type == 'moving_average_abs_max', \
C
cc 已提交
309
            "Unsupported activation_quantize_type: %s. It can " \
310
            "only be moving_average_abs_max now." \
C
cc 已提交
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
            % activation_quantize_type

        bits_check = lambda bits: isinstance(bits, int) \
            and bits >= 0 and bits <= 16
        assert bits_check(weight_bits), \
            "weight_bits should be 1, 2,... or 16."
        assert bits_check(activation_bits), \
            "activation_bits should be 1, 2,... or 16."

        layer_check = lambda method: method is None or \
            issubclass(method, dygraph.layers.Layer)
        assert layer_check(weight_preprocess_layer), \
            "weight_preprocess should be nn.Layer."
        assert layer_check(act_preprocess_layer), \
            "act_preprocess should be nn.Layer."
        assert layer_check(weight_quantize_layer), \
            "weight_quantize should be nn.Layer."
        assert layer_check(act_quantize_layer), \
            "act_quantize should be nn.Layer."

        self._kwargs = {
            "weight_quantize_type": weight_quantize_type,
            "activation_quantize_type": activation_quantize_type,
            "weight_bits": weight_bits,
            "activation_bits": activation_bits,
            "moving_rate": moving_rate,
            "weight_pre_layer": weight_preprocess_layer,
            "act_pre_layer": act_preprocess_layer,
            "weight_quant_layer": weight_quantize_layer,
            "act_quant_layer": act_quantize_layer
        }

    def apply(self, model):
344 345 346 347 348 349 350 351 352 353 354 355
        """
        Quantize the weights and activations to calculate for specific 
        layers.

        Args:
            model(paddle.nn.Layer): The target model which would
                calculate the input quantization scale.

        Returns:
            None
        """

C
cc 已提交
356 357 358
        assert isinstance(model, dygraph.Layer), \
            "The model must be the instance of dygraph.Layer."

359 360 361 362
        for name, cur_layer in model.named_sublayers():
            if not isinstance(cur_layer, self._quantizable_layer_type) \
                or (hasattr(cur_layer, "skip_quant") \
                    and cur_layer.skip_quant == True):
363 364
                continue

365 366 367 368 369
            parent_layer, sub_name = \
                utils.find_parent_layer_and_sub_name(model, name)

            cur_quant_layer = self._get_input_quantized_layer(cur_layer)
            setattr(parent_layer, sub_name, cur_quant_layer)
370

371
    def _get_input_quantized_layer(self, layer):
C
cc 已提交
372
        quant_layer_name = None
373 374

        for key, value in utils.layer_name_map.items():
C
cc 已提交
375 376 377 378 379 380
            if isinstance(layer, value):
                quant_layer_name = 'Quantized' + key
                break
        assert quant_layer_name is not None, \
            "The layer %s is unsupported to be quantized." \
            % layer.full_name()
381

382
        return quant_layers.__dict__[quant_layer_name](layer, **self._kwargs)
383

384

385 386
class ImperativeQuantizeOutputs(object):
    """
387
    Calculate the output scales for target layers.
388 389
    """

390
    def __init__(self, moving_rate=0.9):
391
        """
392
        The constructor for ImperativeQuantizeOutputs.
393 394

        Args:
C
cc 已提交
395 396
            moving_rate(float): The decay coefficient of moving average.
                                The default value is 0.9.
397
        """
398
        super(ImperativeQuantizeOutputs, self).__init__()
399 400
        self._moving_rate = moving_rate

C
cc 已提交
401
    def apply(self, model):
402
        """
403 404
        Insert the `moving_average_abs_max_scale` layers to calculate the
        output scales for specific layers in the dygraph model.
405 406

        Args:
407
            model(paddle.nn.Layer): The target model which would be
408
                calculate the output quantization scale.
409 410 411 412

        Returns:
            None
        """
C
cc 已提交
413 414
        assert isinstance(model, dygraph.Layer), \
            "The model must be the instance of dygraph.Layer."
415

416
        for cur_name, cur_layer in model.named_sublayers():
X
XGZhang 已提交
417 418
            if '_act_preprocess' in cur_name:
                continue
419
            if not self._is_target_layer(cur_layer):
420 421
                continue

422 423 424 425
            parent_layer, sub_name = \
                utils.find_parent_layer_and_sub_name(model, cur_name)

            if isinstance(cur_layer, tuple(utils.fake_quant_output_layers)):
426
                cur_quant_layer = quant_layers.FakeQuantMAOutputScaleLayer(
427 428
                    cur_layer, self._moving_rate)
            else:
429 430
                cur_quant_layer = quant_layers.MAOutputScaleLayer(
                    cur_layer, self._moving_rate)
431 432

            setattr(parent_layer, sub_name, cur_quant_layer)
433

434
    def save_quantized_model(self, model, path, input_spec=None, **config):
435 436 437 438
        """
        Save the quantized model for the inference.

        Args:
439
            model (Layer): The model to be saved.
440 441 442 443 444 445 446 447 448 449 450
            path (str): The path prefix to save model. The format is 
                ``dirname/file_prefix`` or ``file_prefix``.
            input_spec (list[InputSpec|Tensor], optional): Describes the input
                of the saved model's forward method, which can be described by
                InputSpec or example Tensor. If None, all input variables of 
                the original Layer's forward method would be the inputs of
                the saved model. Default None.
            **configs (dict, optional): Other save configuration options for
                compatibility. We do not recommend using these configurations,
                they may be removed in the future. If not necessary, DO NOT use
                them. Default None.
451
                The following options are currently supported:
452 453 454 455 456 457
                (1) output_spec (list[Tensor]): Selects the output targets of
                the saved model. By default, all return variables of original
                Layer's forward method are kept as the output of the saved model.
                If the provided ``output_spec`` list is not all output variables, 
                the saved model will be pruned according to the given
                ``output_spec`` list. 
458 459 460 461

        Returns:
            None
        """
462
        assert isinstance(model, dygraph.Layer), \
463 464
            "The model must be the instance of dygraph.Layer."

465
        paddle.jit.save(layer=model, path=path, input_spec=input_spec, **config)
466 467

        is_dynamic_mode = False
468 469 470 471
        if paddle.in_dynamic_mode():
            is_dynamic_mode = True
            paddle.enable_static()

472 473
        place = core.CPUPlace()
        scope = global_scope()
474 475 476
        exe = Executor(place)

        dirname = os.path.dirname(path)
477 478 479
        basename = os.path.basename(path)
        model_filename = basename + INFER_MODEL_SUFFIX
        params_filename = basename + INFER_PARAMS_SUFFIX
480 481

        [infer_program, feed_target_names, fetch_targets] = (
482 483 484 485 486 487
            load_inference_model(
                dirname=dirname,
                executor=exe,
                model_filename=model_filename,
                params_filename=params_filename))

488
        self._gather_scales(infer_program, scope, fetch_targets)
489

490 491 492 493 494 495 496 497 498
        # Remove `moving_average_abs_max_scale` node in sub graphs.
        graph = IrGraph(core.Graph(infer_program.desc), for_test=False)
        for sub_graph in graph.all_sub_graphs():
            for _op in sub_graph.all_op_nodes():
                if _op.name() == "moving_average_abs_max_scale":
                    sub_graph.safe_remove_nodes(_op)
            sub_graph.resolve_hazard()
        infer_program = graph.to_program()

499
        self._set_skip_quant_attr(infer_program)
G
guofei 已提交
500

501 502 503 504 505
        save_inference_model(
            dirname=dirname,
            feeded_var_names=feed_target_names,
            target_vars=fetch_targets,
            executor=exe,
506
            main_program=infer_program.clone(),
507
            model_filename=model_filename,
508 509
            params_filename=params_filename,
            clip_extra=True)
510

511 512 513
        if is_dynamic_mode:
            paddle.disable_static()

514
    def _is_target_layer(self, layer):
515
        """
516
        Whether the layer needs to calculate output scales.
517
        """
518 519
        flag = False
        if isinstance(layer, dygraph.Layer):
520
            # exclude fake_quant ops in quant_layers file
521 522 523
            if utils.is_leaf_layer(layer) and \
                not isinstance(layer, tuple(utils.fake_quant_leaf_layers)):
                flag = True
524

525 526
            if isinstance(layer, tuple(utils.fake_quant_wrap_layers)):
                flag = True
527 528 529 530

            if isinstance(layer, paddle.nn.quant.FloatFunctionalLayer):
                flag = True

531
        return flag
C
cc 已提交
532

533
    def _gather_scales(self, program, scope, fetch_targets):
534
        """
535
        Get all scales from fake ops, save them into the corresponding ops
536
        and delete all moving_average_abs_max_scale ops.
537
        """
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561

        def _gather_input_scale():
            target_ops = []
            skip_ops = utils.fake_quantize_dequantize_op_types + \
                ["moving_average_abs_max_scale"]
            for block in program.blocks:
                for op in block.ops:
                    if op.type not in skip_ops:
                        target_ops.append(op)

            for op in target_ops:
                for in_var_name in utils._get_op_input_var_names(op):
                    previous_op = utils.find_previous_op(op.block, in_var_name)

                    if previous_op is not None and \
                        ("quantize_dequantize" in previous_op.type or \
                        previous_op.type == "moving_average_abs_max_scale"):
                        scale_name = previous_op.output('OutScale')[0]
                        in_scale = utils.load_variable_data(scope, scale_name)
                        in_scale = utils.fp_numpy_to_naive(in_scale)
                        argname, index = utils._get_input_name_index(
                            op, in_var_name)
                        op._set_attr(argname + str(index) + "_threshold",
                                     in_scale)
562
                        op._set_attr("with_quant_attr", True)
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582

        def _gather_output_scale():
            target_ops = []
            for block in program.blocks:
                for op in block.ops:
                    if op.type == "moving_average_abs_max_scale":
                        target_ops.append(op)

            for op in target_ops:
                in_var_name = op.input('X')[0]
                out_var_name = op.output('Out')[0]
                block = op.block
                previous_op = utils.find_previous_op(block, in_var_name)
                next_ops = utils.find_next_ops(block, out_var_name)

                out_scale_name = op.output('OutScale')[0]
                out_scale = utils.load_variable_data(scope, out_scale_name)
                out_scale = utils.fp_numpy_to_naive(out_scale)

                if previous_op.type != "feed":
X
XGZhang 已提交
583 584 585 586 587 588
                    res = utils._get_output_name_index(previous_op, in_var_name)
                    if res is not None:
                        argname, index = res
                        previous_op._set_attr(
                            argname + str(index) + "_threshold", out_scale)
                        previous_op._set_attr("out_threshold", out_scale)
589
                        previous_op._set_attr("with_quant_attr", True)
590 591 592

                for next_op in next_ops:
                    next_op._rename_input(out_var_name, in_var_name)
593 594 595 596 597
                    # If next_op is `fetch` and out_var_name in fetch_targets,
                    # fetch_targets must update to in_var_name when rename input.
                    for i in range(len(fetch_targets)):
                        if fetch_targets[i].name == out_var_name:
                            fetch_targets[i] = block.var(in_var_name)
598 599 600

        _gather_input_scale()
        _gather_output_scale()
C
cc 已提交
601

602
    def _set_skip_quant_attr(self, program):
603
        """
604
        Label the skip quantized ops.
605
        """
606 607 608 609
        for block in program.blocks:
            for op in block.ops:
                if self._is_skip_quant_op(block, op):
                    op._set_attr("skip_quant", True)
610
                    op._set_attr("with_quant_attr", True)
G
guofei 已提交
611 612 613 614 615 616 617

    def _is_skip_quant_op(self, block, in_op):
        """
        The input op should be skipped quantization.
        1. the type of input op should be conv2d, depthwise_conv2d or matmul
        2. the previous ops of the input op are not fake_quantize_dequantize ops
        """
618 619 620
        target_op_types = [
            "conv2d", "depthwise_conv2d", "matmul", "conv2d_transpose"
        ]
G
guofei 已提交
621 622 623
        if in_op.type not in target_op_types:
            return False

624
        previous_ops = [utils.find_previous_op(block, arg_name) \
G
guofei 已提交
625
            for arg_name in in_op.input_arg_names]
626
        return any(op is not None and op.type not in \
627
            utils.fake_quantize_dequantize_op_types for op in previous_ops)