quant_int8_mkldnn_pass.py 11.4 KB
Newer Older
1
#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
W
Wojciech Uss 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#
# 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 numpy as np

17 18
from ...fluid.framework import IrGraph
from ...framework import _get_paddle_place
W
Wojciech Uss 已提交
19 20


21
class QuantInt8MkldnnPass:
W
Wojciech Uss 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
    """
    Convert QuantizationFreezePass generated IrGraph to MKL-DNN supported INT8
    IrGraph. Following transformations did in this pass:
        1. Convert int8 range weights with float32 data type, which are generated by
           the QuantizationFreezePass, to float32 range weights with float32 data type
           by using the corresponding scales. This conversion is because MKL-DNN INT8
           conv2d kernel and mul kernel now only support float32 weights input, hence
           weights quantization will happen inside the conv2d and mul INT8 kernel.
        2. Create the new conv2d or mul op with the converted weights and link its output
           to fake_dequantize_abs_max op's output and set conv2d's attribute "force_fp32
           _output" as true
        3. Transform fake_quantize_xx op to quantize op
        4. Remove fake_dequantize_abs_max op
    """

    def __init__(self, _scope=None, _place=None):
38
        r"""
W
Wojciech Uss 已提交
39
        Args:
40 41
            scope(static.Scope): scope is used to initialize the new parameters.
            place(static.CPUPlace|str): place is used to initialize the new parameters.
42
            When it is string, it can be only 'cpu'.
W
Wojciech Uss 已提交
43 44 45 46 47


        Examples:
        .. code-block:: python
            # The original graph will be rewrite.
48 49
            import paddle.static as static
            from paddle.static.quantization \
W
Wojciech Uss 已提交
50
                import QuantInt8MkldnnPass
W
Wojciech Uss 已提交
51
            from paddle.fluid.framework import IrGraph
52
            from paddle.framework import core
W
Wojciech Uss 已提交
53

54 55 56
            graph = IrGraph(core.Graph(static.Program().desc), for_test=False)
            place = static.CPUPlace()
            mkldnn_pass = QuantInt8MkldnnPass(static.global_scope(),
W
Wojciech Uss 已提交
57 58 59 60 61
            place)
            mkldnn_pass.apply(graph)
        """

        self._scope = _scope
62
        self._place = _get_paddle_place(_place)
W
Wojciech Uss 已提交
63 64 65

        self._quantize_type = [
            'fake_quantize_moving_average_abs_max',
66
            'fake_quantize_range_abs_max',
W
Wojciech Uss 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
        ]
        self._dequantize_type = ['fake_dequantize_max_abs']
        self._quantize_dequantize_type = [
            'fake_quantize_dequantize_moving_average_abs_max'
        ]

        self._quantizable_ops = ['conv2d', 'depthwise_conv2d', 'mul']
        self._conv_ops = ['conv2d', 'depthwise_conv2d']
        self._pool_ops = ['pool2d']

        self._in_scale = {}
        self._max_range = {}
        self._new_output = {}
        self._s8_max = 127

    def apply(self, graph):
        """
        Quantize the graph for running MKL-DNN INT8 inference. According
        to activation quantization type, the graph will transform fake
        quantize ops to quantize ops and remove the fake dequantize ops.

        Args:
            graph(IrGraph): the applied graph.
        """

92 93 94
        assert isinstance(
            graph, IrGraph
        ), 'graph must be the instance of IrGraph.'
W
Wojciech Uss 已提交
95 96 97 98 99 100 101 102 103
        ops = graph.all_op_nodes()

        persistable_vars = [p.name() for p in graph.all_persistable_nodes()]
        # Collect the _in_scales and _max_range to calculate the new scales for MKL-DNN
        # INT8 conv2d and mul
        for op_node in ops:
            if op_node.name() in self._dequantize_type:
                input_name = op_node.input("X")[0]
                scale_name = op_node.input("Scale")[0]
104
                self._in_scale[input_name] = self._load_param(
105 106
                    self._scope, scale_name
                )[0]
W
Wojciech Uss 已提交
107 108 109 110 111 112 113 114
                self._max_range[input_name] = op_node.op().attr("max_range")
                self._new_output[input_name] = op_node.output("Out")[0]

            if op_node.name() in self._quantize_dequantize_type:
                inputs = op_node.op().input_names()
                attrs = op_node.op().attr_names()
                input_name = op_node.input("X")[0]
                scale_name = op_node.input("InScale")[0]
115
                self._in_scale[input_name] = self._load_param(
116 117
                    self._scope, scale_name
                )[0]
W
Wojciech Uss 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
                #  self._max_range[input_name] = op_node.op().attr("max_range")
                self._new_output[input_name] = op_node.output("Out")[0]

        for op_node in ops:
            if op_node.name() in self._quantizable_ops:
                if op_node.name() in self._conv_ops:
                    self._transform_to_conv_mkldnn(graph, op_node)
                elif op_node.name() in self._pool_ops:
                    self._transform_to_pool_mkldnn(graph, op_node)
                else:
                    self._transform_to_mul_mkldnn(graph, op_node)
            elif op_node.name() in self._quantize_type:
                self._transform_to_quantize_mkldnn(graph, op_node)
            elif op_node.name() in self._dequantize_type:
                self._remove_fake_dequantize_op(graph, op_node)
            self._remove_unused_var_nodes(graph)
        return graph

    def _transform_to_pool_mkldnn(self, graph, op):
        output_name = op.output("Out")[0]
        input_name = op.input("X")[0]

    def _transform_to_conv_mkldnn(self, graph, op_node):
        weight_name = op_node.input("Filter")[0]
        output_name = op_node.output("Output")[0]
        # Convert int8 range weights to fp32 range weights
        weight = self._load_param(self._scope, weight_name)
145 146 147
        w_fp32 = np.divide(
            np.multiply(weight, self._s8_max), self._max_range[output_name]
        )
W
Wojciech Uss 已提交
148 149
        w_fp32 = w_fp32.reshape(weight.shape)
        self._restore_var(weight_name, w_fp32)
150 151 152
        input_var_node = graph._find_node_by_name(
            op_node.inputs, op_node.input("Input")[0]
        )
W
Wojciech Uss 已提交
153 154 155 156
        weight_var_node = graph._find_node_by_name(op_node.inputs, weight_name)

        # Set fake_dequantize_abs_max's output as new output of conv2d
        output_var_node = graph._find_node_by_name(
157 158
            graph.all_var_nodes(), self._new_output[output_name]
        )
W
Wojciech Uss 已提交
159
        attrs = {
160
            name: op_node.op().attr(name) for name in op_node.op().attr_names()
W
Wojciech Uss 已提交
161 162
        }

163
        conv_op_node = graph.create_op_node(
164
            op_type='fused_conv2d',
165 166 167 168
            attrs=attrs,
            inputs={'Input': input_var_node, 'Filter': weight_var_node},
            outputs={'Output': output_var_node},
        )
W
Wojciech Uss 已提交
169

W
Wojciech Uss 已提交
170
        # Based on the Quant's scales to calculate the scales of MKL-DNN INT8 conv2d
W
Wojciech Uss 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        scale_in = self._s8_max / self._in_scale[output_name]
        scale_w = []
        scale_w = [self._max_range[output_name] / self._s8_max]

        conv_op_node.set_attr("Scale_weights", scale_w)
        conv_op_node.set_attr("Scale_in", scale_in)
        conv_op_node.set_attr("Scale_out", 1.0)
        conv_op_node.set_attr("use_mkldnn", 1)
        conv_op_node.set_attr("force_fp32_output", 1)
        graph.link_to(input_var_node, conv_op_node)
        graph.link_to(weight_var_node, conv_op_node)
        graph.link_to(conv_op_node, output_var_node)
        graph.safe_remove_nodes(op_node)

    def _transform_to_mul_mkldnn(self, graph, op_node):
        # For MKL-DNN INT8 mul, input Y should be the weights
        weight_name = op_node.input("Y")[0]
        output_name = op_node.output("Out")[0]
        # Convert int8 range weights to fp32 range weights
        weight = self._load_param(self._scope, weight_name)
191 192 193
        w_fp32 = np.divide(
            np.multiply(weight, self._s8_max), self._max_range[output_name]
        )
W
Wojciech Uss 已提交
194 195
        w_fp32 = w_fp32.reshape(weight.shape)
        self._restore_var(weight_name, w_fp32)
196 197 198
        input_var_node = graph._find_node_by_name(
            op_node.inputs, op_node.input("X")[0]
        )
W
Wojciech Uss 已提交
199 200 201 202
        weight_var_node = graph._find_node_by_name(op_node.inputs, weight_name)

        # Set fake_dequantize_abs_max's output as new output of mul
        output_var_node = graph._find_node_by_name(
203 204
            graph.all_var_nodes(), self._new_output[output_name]
        )
W
Wojciech Uss 已提交
205
        attrs = {
206
            name: op_node.op().attr(name) for name in op_node.op().attr_names()
W
Wojciech Uss 已提交
207 208
        }

209 210 211 212 213 214
        mul_op_node = graph.create_op_node(
            op_type='mul',
            attrs=attrs,
            inputs={'X': input_var_node, 'Y': weight_var_node},
            outputs={'Out': output_var_node},
        )
W
Wojciech Uss 已提交
215

W
Wojciech Uss 已提交
216
        # Based on the Quant's scales to calculate MKL-DNN INT8 mul's scales
W
Wojciech Uss 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        scale_in = self._s8_max / self._in_scale[output_name]
        scale_w = []
        scale_w = [self._max_range[output_name] / self._s8_max]

        mul_op_node.set_attr("scale_y", scale_w)
        mul_op_node.set_attr("scale_x", scale_in)
        mul_op_node.set_attr("scale_out", 1.0)
        mul_op_node.set_attr("use_mkldnn", 1)
        mul_op_node.set_attr("force_fp32_output", 1)
        graph.link_to(input_var_node, mul_op_node)
        graph.link_to(weight_var_node, mul_op_node)
        graph.link_to(mul_op_node, output_var_node)
        graph.safe_remove_nodes(op_node)

    def _transform_to_quantize_mkldnn(self, graph, op_node):
        """
        Transform fake_quantize_xx op to quantize mkldnn op in the graph.
        """
235 236 237 238 239 240 241 242 243 244
        input_var_node = graph._find_node_by_name(
            op_node.inputs, op_node.input("X")[0]
        )
        output_var_node = graph._find_node_by_name(
            op_node.outputs, op_node.output("Out")[0]
        )
        scale_in = (
            self._s8_max
            / self._load_param(self._scope, op_node.input("InScale")[0])[0]
        )
W
Wojciech Uss 已提交
245 246 247 248 249 250
        quant_op_node = graph.create_op_node(
            op_type='quantize',
            attrs={
                'data_format': 'MKLDNNLAYOUT',
                'use_mkldnn': 1,
                'Scale': scale_in,
251
                'is_negative_input': 1,
W
Wojciech Uss 已提交
252 253
            },
            inputs={'Input': input_var_node},
254 255
            outputs={'Output': output_var_node},
        )
W
Wojciech Uss 已提交
256 257 258 259 260
        graph.link_to(input_var_node, quant_op_node)
        graph.link_to(quant_op_node, output_var_node)
        graph.safe_remove_nodes(op_node)

    def _remove_fake_dequantize_op(self, graph, op_node):
261 262 263
        input_var_node = graph._find_node_by_name(
            op_node.inputs, op_node.input("X")[0]
        )
W
Wojciech Uss 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        graph.safe_remove_nodes(op_node)

    def _load_param(self, scope, param_name):
        return np.array(scope.find_var(param_name).get_tensor())

    def _restore_var(self, name, array):
        tensor = self._scope.find_var(name).get_tensor()
        tensor.set(array, self._place)

    def _remove_unused_var_nodes(self, graph):
        all_used_vars = set()
        ops = graph.all_op_nodes()
        for op_node in ops:
            for input_node in op_node.inputs:
                all_used_vars.add(input_node)
            for output_node in op_node.outputs:
                all_used_vars.add(output_node)

        all_used_vars = {n.node for n in all_used_vars}
        all_unused_vars = {
            n
285 286 287 288
            for n in filter(
                lambda node: node.node not in all_used_vars,
                graph.all_var_nodes(),
            )
W
Wojciech Uss 已提交
289 290
        }
        graph.safe_remove_nodes(all_unused_vars)