ptq.py 18.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2021 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 logging
import copy
17
import os
18 19 20
import numpy as np

import paddle
21
import paddle.nn.quant.quant_layers as quant_layers
22
from paddle.fluid.log_helper import get_logger
23
from paddle.fluid.dygraph.io import INFER_MODEL_SUFFIX, INFER_PARAMS_SUFFIX
24

X
XGZhang 已提交
25
from . import fuse_utils
26 27 28
from . import utils
from . import ptq_hooks
from . import ptq_config
29
from . import ptq_quantizer
30 31 32 33
from .ptq_registry import PTQRegistry

__all__ = ['ImperativePTQ']

34 35 36
_logger = get_logger(
    __name__, logging.INFO, fmt='%(asctime)s-%(levelname)s: %(message)s'
)
37 38


39
class ImperativePTQ:
40
    """
41
    Static post training quantization.
42 43 44 45 46
    """

    def __init__(self, quant_config=ptq_config.default_ptq_config):
        """
        Constructor.
47

48
        Args:
49 50
            quant_config(PTQConfig): the config of post training quantization.
                The config has weight_quantizer and activation_quantizer.
51 52
                In default, the weight_quantizer is PerChannelAbsmaxQuantizer
                and the activation_quantizer is KLQuantizer.
53
        """
54
        super().__init__()
55 56 57 58 59

        assert isinstance(quant_config, ptq_config.PTQConfig)

        self._quant_config = quant_config

X
XGZhang 已提交
60
    def quantize(self, model, inplace=False, fuse=False, fuse_list=None):
61
        """
62
        Add quant config and hook to the target layer.
63 64 65

        Args:
            model(paddle.nn.Layer): The model to be quantized.
66 67
            inplace(bool): Whether apply quantization to the input model.
                           Default: False.
X
XGZhang 已提交
68 69 70 71 72 73 74 75
            fuse(bool): Whether to fuse layers.
                        Default: False.
            fuse_list(list): The layers' names to be fused. For example,
                "fuse_list = [["conv1", "bn1"], ["conv2", "bn2"]]".
                A TypeError would be raised if "fuse" was set as
                True but "fuse_list" was None.
                Default: None.
        Return
76
            quantized_model(paddle.nn.Layer): The quantized model.
77
        """
78 79 80
        assert isinstance(
            model, paddle.nn.Layer
        ), "The model must be the instance of paddle.nn.Layer."
81
        if not inplace:
82
            model = copy.deepcopy(model)
X
XGZhang 已提交
83 84 85
        if fuse:
            model.eval()
            model = fuse_utils.fuse_layers(model, fuse_list)
86
        for name, layer in model.named_sublayers():
87 88 89 90 91
            if (
                PTQRegistry.is_supported_layer(layer)
                and utils.is_leaf_layer(layer)
                and not self._is_skip_layer(layer)
            ):
92 93

                # Add quant config
94
                quant_config = copy.deepcopy(self._quant_config)
95 96
                if PTQRegistry.is_simulated_quant_layer(layer):
                    quant_config.enable_in_act_quantizer = True
97 98
                layer._quant_config = quant_config

99
                # register hook
100
                hook = ptq_hooks.quant_forward_post_hook
101 102
                quant_hook_handle = layer.register_forward_post_hook(hook)
                quant_config.quant_hook_handle = quant_hook_handle
103
                layer._forward_post_hooks.move_to_end(
104 105
                    quant_hook_handle._hook_id, last=False
                )
106

107
        return model
108

109
    def save_quantized_model(self, model, path, input_spec=None, **config):
110
        """
111 112
        1. Convert the quantized model
        2. Call jit.save to save the inference model
113
        3. Post process the inference model.
114 115

        Args:
116
            model (Layer): The model to be saved.
117
            path (str): The path prefix to save model. The format is
118 119 120
                ``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
121
                InputSpec or example Tensor. If None, all input variables of
122 123
                the original Layer's forward method would be the inputs of
                the saved model. Default None.
124
            **config (dict, optional): Other save configuration options for
125 126 127 128 129 130 131
                compatibility. We do not recommend using these configurations,
                they may be removed in the future. If not necessary, DO NOT use
                them. Default None.
                The following options are currently supported:
                (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.
132
                If the provided ``output_spec`` list is not all output variables,
133
                the saved model will be pruned according to the given
134
                ``output_spec`` list.
135

136
        Returns:
137
            None
138
        """
139

140 141 142
        assert isinstance(
            model, paddle.nn.Layer
        ), "The model must be the instance of paddle.nn.Layer."
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

        # Convert and save dygraph quantized model
        self._convert(model)

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

        # Load inference program
        is_dynamic_mode = False
        if paddle.in_dynamic_mode():
            is_dynamic_mode = True
            paddle.enable_static()

        place = paddle.CPUPlace()
        scope = paddle.static.global_scope()
        exe = paddle.static.Executor(place)

        dirname = os.path.dirname(path)
        basename = os.path.basename(path)
        model_filename = basename + INFER_MODEL_SUFFIX
        params_filename = basename + INFER_PARAMS_SUFFIX

164 165 166 167 168 169 170 171 172 173
        [
            infer_program,
            feed_target_names,
            fetch_targets,
        ] = paddle.fluid.io.load_inference_model(
            dirname=dirname,
            executor=exe,
            model_filename=model_filename,
            params_filename=params_filename,
        )
174 175 176 177 178 179 180

        # Process inference program
        self._clean_up(infer_program)
        self._gather_input_thresholds(infer_program, scope)
        self._remove_scale_op(infer_program)

        # Save final program
181 182 183 184 185 186 187 188 189
        paddle.fluid.io.save_inference_model(
            dirname=dirname,
            feeded_var_names=feed_target_names,
            target_vars=fetch_targets,
            executor=exe,
            main_program=infer_program.clone(),
            model_filename=model_filename,
            params_filename=params_filename,
        )
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

        if is_dynamic_mode:
            paddle.disable_static()

    def _convert(self, model):
        """
        Convert the quantized model.

        Args:
            model(paddle.nn.Layer): The quantized model.
            inplace(bool): Whether apply conversion to the input model.
                           Default: False.
        Returns:
            None
        """
205 206

        for name, sub_layer in model.named_sublayers():
207 208
            if self._is_quant_layer(sub_layer):
                sub_layer._quant_config.quant_hook_handle.remove()
209

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        self._cal_thresholds(model)

        for name, sub_layer in model.named_sublayers():
            if self._is_quant_layer(sub_layer):
                self._save_output_thresholds(sub_layer, sub_layer._quant_config)

        self._wrap_simulated_layers(model)

    def _cal_thresholds(self, model):
        """
        Calculate the thresholds of inputs and outputs.

        Args:
            model(paddle.nn.Layer): The quantized model.
        Returns:
            None
        """
227 228 229
        assert isinstance(
            model, paddle.nn.Layer
        ), "The input model must be the instance of paddle.nn.Layer."
230

231 232
        total_num = 0
        cur_num = 0
233 234
        for name, sub_layer in model.named_sublayers():
            if self._is_quant_layer(sub_layer):
235 236 237 238 239 240
                total_num += 1

        for name, sub_layer in model.named_sublayers():
            if self._is_quant_layer(sub_layer):
                cur_num += 1
                if cur_num % 5 == 0:
241 242 243
                    _logger.info(
                        "Process the %s / %s layer" % (cur_num, total_num)
                    )
244

245 246
                quant_config = sub_layer._quant_config

247 248
                if quant_config.enable_in_act_quantizer:
                    quant_config.in_act_quantizer.cal_thresholds()
249 250
                quant_config.out_act_quantizer.cal_thresholds()

251
                if PTQRegistry.is_simulated_quant_layer(sub_layer):
252
                    weights = (sub_layer.weight,)
253
                    quant_config.wt_quantizer.sample_data(sub_layer, weights)
254 255 256 257 258 259 260 261 262 263 264 265
                    quant_config.wt_quantizer.cal_thresholds()

    def _save_output_thresholds(self, sub_layer, quant_config):
        """
        Save the output thresholds to the layer.

        Args:
            sub_layer(paddle.nn.Layer): The quantized layer.
            quant_config(PTQConfig): the quant config for the layer.
        Returns:
            None
        """
266 267 268
        assert isinstance(
            sub_layer, paddle.nn.Layer
        ), "The input model must be the instance of paddle.nn.Layer."
269 270 271 272 273 274

        layer_info = PTQRegistry.layer_info(sub_layer)

        output_names = layer_info.output_names
        output_thresholds = quant_config.out_act_quantizer.thresholds
        assert len(output_names) == 1
275 276 277 278 279 280 281 282 283 284
        if len(output_thresholds) == 1:
            save_name = output_names[0] + str(0) + "_threshold"
            sub_layer._set_op_attrs({save_name: output_thresholds[0]})
            sub_layer._set_op_attrs({"out_threshold": output_thresholds[0]})
        else:
            _logger.warning(
                "output_thresholds shape of {} need to be 1, but received {}".format(
                    output_names[0], len(output_thresholds)
                )
            )
285 286 287 288 289 290 291 292 293 294

    def _wrap_simulated_layers(self, model):
        """
        Replace conv2d and linear with the quantized layers, and save
        thresholds into the fake layers.
        Args:
            model(paddle.nn.Layer): The model to be quantized.
        Returns:
            None
        """
295 296 297
        assert isinstance(
            model, paddle.nn.Layer
        ), "The input model must be the instance of paddle.nn.Layer."
298 299

        for name, sub_layer in model.named_sublayers():
300 301 302
            if self._is_quant_layer(
                sub_layer
            ) and PTQRegistry.is_simulated_quant_layer(sub_layer):
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

                quant_config = sub_layer._quant_config
                assert quant_config.enable_in_act_quantizer == True
                wt_quantizer = quant_config.wt_quantizer
                in_act_quantizer = quant_config.in_act_quantizer

                # create layer
                quant_layer_name = None
                for key, value in utils.layer_name_map.items():
                    if isinstance(sub_layer, value):
                        quant_layer_name = 'Quantized' + key
                        break
                assert quant_layer_name is not None

                if isinstance(wt_quantizer, ptq_quantizer.AbsmaxQuantizer):
                    weight_quantize_type = "abs_max"
                else:
                    weight_quantize_type = "channel_wise_abs_max"
                kwargs = {
                    "weight_quantize_type": weight_quantize_type,
                    "activation_quantize_type": "moving_average_abs_max",
                    "weight_bits": wt_quantizer.quant_bits,
                    "activation_bits": in_act_quantizer.quant_bits,
                }

328 329 330
                quant_layer = quant_layers.__dict__[quant_layer_name](
                    sub_layer, **kwargs
                )
331 332 333 334

                # save the input thresholds
                assert hasattr(quant_layer, "_fake_quant_input")
                assert hasattr(quant_layer._fake_quant_input, "_scale")
335 336 337 338 339 340 341
                if len(in_act_quantizer.thresholds) == 1:
                    input_threshold = np.array(
                        [in_act_quantizer.thresholds[0]], dtype=np.float32
                    )
                    quant_layer._fake_quant_input._scale.set_value(
                        input_threshold
                    )
342 343 344 345 346 347

                assert hasattr(quant_layer, "_fake_quant_weight")
                assert hasattr(quant_layer._fake_quant_weight, "_scale")
                assert len(wt_quantizer.thresholds) == 1
                weight_threshold = wt_quantizer.thresholds[0]
                if isinstance(weight_threshold, list):
348 349 350
                    weight_threshold = np.array(
                        weight_threshold, dtype=np.float32
                    )
351
                else:
352 353 354
                    weight_threshold = np.array(
                        [weight_threshold], dtype=np.float32
                    )
355
                quant_layer._fake_quant_weight._scale.set_value(
356 357
                    weight_threshold
                )
358 359 360 361 362

                # save the output thresholds
                self._save_output_thresholds(quant_layer, quant_config)

                # replace the layer
363 364 365
                parent_layer, sub_name = utils.find_parent_layer_and_sub_name(
                    model, name
                )
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
                setattr(parent_layer, sub_name, quant_layer)

    def _gather_input_thresholds(self, program, scope):
        """
        Get and save input thresholds from the front ops.

        Args:
            program(Program): the input infer program.
            scope(Scope): the corresponding scope for the program.
        Returns:
            None
        """
        for op in utils.program_all_ops(program):
            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 None:
                    continue

384 385 386 387
                if (
                    "quantize_dequantize" in previous_op.type
                    or previous_op.type == "moving_average_abs_max_scale"
                ):
388 389 390
                    attr_name = previous_op.output('OutScale')[0]
                    in_threshold = utils.load_variable_data(scope, attr_name)
                    in_threshold = utils.fp_numpy_to_naive(in_threshold)
391
                    argname, index = utils._get_input_name_index(
392 393 394 395 396
                        op, in_var_name
                    )
                    op._set_attr(
                        argname + str(index) + "_threshold", in_threshold
                    )
397
                    op._set_attr("with_quant_attr", True)
398 399
                else:
                    for out_var_name in utils._get_op_output_var_names(
400 401
                        previous_op
                    ):
402 403 404
                        if out_var_name != in_var_name:
                            continue
                        argname, index = utils._get_output_name_index(
405 406
                            previous_op, out_var_name
                        )
407 408 409 410 411 412
                        attr_name = argname + str(index) + "_threshold"
                        if not previous_op.has_attr(attr_name):
                            continue
                        threshold = previous_op.attr(attr_name)

                        argname, index = utils._get_input_name_index(
413 414
                            op, in_var_name
                        )
415 416
                        attr_name = argname + str(index) + "_threshold"
                        op._set_attr(attr_name, threshold)
417
                        op._set_attr("with_quant_attr", True)
418 419 420 421 422 423 424 425 426 427 428 429

    def _clean_up(self, program):
        """
        Remove useless thresholds which are added in jit.save.

        Args:
            program(Program): the input infer program.
        Returns:
            None
        """

        def _helper(op, next_op, old_attr_name, new_attr_name):
430 431 432 433 434
            if (
                op.has_attr(old_attr_name)
                and next_op.has_attr(old_attr_name)
                and op.attr(old_attr_name) == next_op.attr(old_attr_name)
            ):
435 436 437 438
                threshold = op.attr(old_attr_name)
                op._remove_attr(old_attr_name)
                next_op._remove_attr(old_attr_name)
                next_op._set_attr(new_attr_name, threshold)
439
                next_op._set_attr("with_quant_attr", True)
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459

        for op in utils.program_all_ops(program):
            if "quantize_dequantize" in op.type:
                # remove the thresholds in fake ops
                for attr_name in op.attr_names:
                    if "_threshold" in attr_name:
                        op._remove_attr(attr_name)
            elif op.type in ["conv2d", "matmul"]:
                # change the thresholds in conv2d/matmul + eleadd
                arg_name = "Output" if op.type == "conv2d" else "Out"
                out_var_name = op.output(arg_name)[0]
                next_ops = utils.find_next_ops(op.block, out_var_name)
                if len(next_ops) > 1 or next_ops[0].type != "elementwise_add":
                    continue
                next_op = next_ops[0]

                argname, index = utils._get_output_name_index(op, out_var_name)
                old_attr_name = argname + str(index) + "_threshold"

                argname, index = utils._get_output_name_index(
460 461
                    next_op, next_op.output("Out")[0]
                )
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
                new_attr_name = argname + str(index) + "_threshold"

                _helper(op, next_op, old_attr_name, new_attr_name)
                _helper(op, next_op, "out_threshold", "out_threshold")

    def _remove_scale_op(self, program):
        """
        Remove the moving_average_abs_max_scale op.
        """
        for op in utils.program_all_ops(program):
            if op.type == "moving_average_abs_max_scale":
                in_var_name = op.input("X")[0]
                out_var_name = op.output("Out")[0]
                next_ops = utils.find_next_ops(op.block, out_var_name)
                for next_op in next_ops:
                    next_op._rename_input(out_var_name, in_var_name)
478

479 480 481
    @staticmethod
    def _is_skip_layer(layer):
        return hasattr(layer, "skip_quant") and layer.skip_quant == True
482

483 484 485
    @staticmethod
    def _is_quant_layer(layer):
        return hasattr(layer, "_quant_config")