ptq.py 17.9 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 40


class ImperativePTQ(object):
    """
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 55 56 57 58 59
        """
        super(ImperativePTQ, self).__init__()

        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."
        if not inplace:
81
            model = copy.deepcopy(model)
X
XGZhang 已提交
82 83 84
        if fuse:
            model.eval()
            model = fuse_utils.fuse_layers(model, fuse_list)
85
        for name, layer in model.named_sublayers():
86
            if PTQRegistry.is_supported_layer(layer) \
87 88 89 90
                and utils.is_leaf_layer(layer) \
                and not self._is_skip_layer(layer):

                # Add quant config
91
                quant_config = copy.deepcopy(self._quant_config)
92 93
                if PTQRegistry.is_simulated_quant_layer(layer):
                    quant_config.enable_in_act_quantizer = True
94 95
                layer._quant_config = quant_config

96
                # register hook
97
                hook = ptq_hooks.quant_forward_post_hook
98 99
                quant_hook_handle = layer.register_forward_post_hook(hook)
                quant_config.quant_hook_handle = quant_hook_handle
100
                layer._forward_post_hooks.move_to_end(
101
                    quant_hook_handle._hook_id, last=False)
102

103
        return model
104

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

        Args:
112
            model (Layer): The model to be saved.
113
            path (str): The path prefix to save model. The format is
114 115 116
                ``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
117
                InputSpec or example Tensor. If None, all input variables of
118 119 120 121 122 123 124 125 126 127
                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.
                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.
128
                If the provided ``output_spec`` list is not all output variables,
129
                the saved model will be pruned according to the given
130
                ``output_spec`` list.
131

132
        Returns:
133
            None
134
        """
135

136
        assert isinstance(model, paddle.nn.Layer), \
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
            "The model must be the instance of paddle.nn.Layer."

        # 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

159 160 161 162 163 164
        [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))
165 166 167 168 169 170 171

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

        # Save final program
172 173 174 175 176 177 178
        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)
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

        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
        """
194 195

        for name, sub_layer in model.named_sublayers():
196 197
            if self._is_quant_layer(sub_layer):
                sub_layer._quant_config.quant_hook_handle.remove()
198

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
        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
        """
        assert isinstance(model, paddle.nn.Layer), \
            "The input model must be the instance of paddle.nn.Layer."

219 220
        total_num = 0
        cur_num = 0
221 222
        for name, sub_layer in model.named_sublayers():
            if self._is_quant_layer(sub_layer):
223 224 225 226 227 228 229 230 231
                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:
                    _logger.info("Process the %s / %s layer" %
                                 (cur_num, total_num))

232 233
                quant_config = sub_layer._quant_config

234 235
                if quant_config.enable_in_act_quantizer:
                    quant_config.in_act_quantizer.cal_thresholds()
236 237
                quant_config.out_act_quantizer.cal_thresholds()

238
                if PTQRegistry.is_simulated_quant_layer(sub_layer):
239 240
                    weights = (sub_layer.weight, )
                    quant_config.wt_quantizer.sample_data(sub_layer, weights)
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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
                    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
        """
        assert isinstance(sub_layer, paddle.nn.Layer), \
            "The input model must be the instance of paddle.nn.Layer."

        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
        assert 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]})

    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
        """
        assert isinstance(model, paddle.nn.Layer), \
            "The input model must be the instance of paddle.nn.Layer."

        for name, sub_layer in model.named_sublayers():
            if self._is_quant_layer(sub_layer) \
                and PTQRegistry.is_simulated_quant_layer(sub_layer):

                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,
                }

                quant_layer = quant_layers.__dict__[quant_layer_name](sub_layer,
                                                                      **kwargs)

                # save the input thresholds
                assert hasattr(quant_layer, "_fake_quant_input")
                assert hasattr(quant_layer._fake_quant_input, "_scale")
                assert len(in_act_quantizer.thresholds) == 1
313 314
                input_threshold = np.array([in_act_quantizer.thresholds[0]],
                                           dtype=np.float32)
315 316 317 318 319 320 321
                quant_layer._fake_quant_input._scale.set_value(input_threshold)

                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):
322 323
                    weight_threshold = np.array(weight_threshold,
                                                dtype=np.float32)
324
                else:
325 326
                    weight_threshold = np.array([weight_threshold],
                                                dtype=np.float32)
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
                quant_layer._fake_quant_weight._scale.set_value(
                    weight_threshold)

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

                # replace the layer
                parent_layer, sub_name = \
                    utils.find_parent_layer_and_sub_name(model, name)
                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

                if "quantize_dequantize" in previous_op.type or \
                    previous_op.type == "moving_average_abs_max_scale":
                    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)
359 360
                    argname, index = utils._get_input_name_index(
                        op, in_var_name)
361 362
                    op._set_attr(argname + str(index) + "_threshold",
                                 in_threshold)
363
                    op._set_attr("with_quant_attr", True)
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
                else:
                    for out_var_name in utils._get_op_output_var_names(
                            previous_op):
                        if out_var_name != in_var_name:
                            continue
                        argname, index = utils._get_output_name_index(
                            previous_op, out_var_name)
                        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(
                            op, in_var_name)
                        attr_name = argname + str(index) + "_threshold"
                        op._set_attr(attr_name, threshold)
380
                        op._set_attr("with_quant_attr", True)
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398

    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):
            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):
                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)
399
                next_op._set_attr("with_quant_attr", True)
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

        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(
420 421
                    next_op,
                    next_op.output("Out")[0])
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
                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)
438

439 440 441
    @staticmethod
    def _is_skip_layer(layer):
        return hasattr(layer, "skip_quant") and layer.skip_quant == True
442

443 444 445
    @staticmethod
    def _is_quant_layer(layer):
        return hasattr(layer, "_quant_config")