quantize_transpiler.py 21.8 KB
Newer Older
D
Dang Qingqing 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2018 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 numpy as np

18 19 20 21 22
from paddle.fluid.framework import (
    default_main_program,
    default_startup_program,
    program_guard,
)
D
Dang Qingqing 已提交
23 24
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid import unique_name
25
from paddle.fluid import core
D
Dang Qingqing 已提交
26 27 28 29
from paddle.fluid.initializer import Constant
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.layers.nn import autoincreased_step_counter
30 31 32 33
from paddle.fluid.framework import Variable
from paddle.fluid.executor import global_scope

__all__ = ['QuantizeTranspiler']
D
Dang Qingqing 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

_QUANTIZABLE_OP_TYPES = ['conv2d', 'depthwise_conv2d', 'mul']


def _quantized_var_name(var_name):
    """
    Return quantized variable name for the input `var_name`.
    """
    return "%s.quantized" % (var_name)


def _dequantized_var_name(var_name):
    """
    Return dequantized variable name for the input `var_name`.
    """
    return "%s.dequantized" % (var_name)


def _quantized_scale_name(var_name):
    """
    Return quantized variable name for the input `var_name`.
    """
    return "%s.scale" % (var_name)


def _original_var_name(var_name):
    """
    Return the original variable name.
    """
    if var_name.endswith('.quantized.dequantized'):
64
        return var_name[: -len('.quantized.dequantized')]
D
Dang Qingqing 已提交
65
    if var_name.endswith('.quantized'):
66
        return var_name[: -len('.quantized')]
D
Dang Qingqing 已提交
67
    if var_name.endswith('.dequantized'):
68
        return var_name[: -len('.dequantized')]
D
Dang Qingqing 已提交
69
    if var_name.endswith('.scale'):
70
        return var_name[: -len('.scale')]
D
Dang Qingqing 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83
    else:
        return var_name


def _is_float(v):
    return isinstance(v, float) or isinstance(v, np.float32)


def quant(x, scale, num_bits):
    y = np.round(x / scale * ((1 << (num_bits - 1)) - 1))
    return y


84
class QuantizeTranspiler:
85 86 87 88 89 90 91 92 93
    def __init__(
        self,
        weight_bits=8,
        activation_bits=8,
        activation_quantize_type='abs_max',
        weight_quantize_type='abs_max',
        window_size=10000,
        moving_rate=0.9,
    ):
D
Dang Qingqing 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        """
        Convert and rewrite the fluid Program according to weight and
        activation quantization type.

        Args:
            weight_bits (int): quantization bit number for weights,
                the bias is not quantized.
            activation_bits (int): quantization bit number for activation.
            activation_quantize_type (str): quantization type for activation,
                now support 'abs_max', 'range_abs_max'. If use 'abs_max' mode,
                the quantization scale will be calculated dynamically each step
                in both training and testing period. If use 'range_abs_max',
                a static quantization scale will be calculated during training
                and used in inference.
            weight_quantize_type (str): quantization type for weights,
                support 'abs_max'. The 'range_abs_max' usually is not used for
                weight, since weights are fixed once the model is well trained.
            window_size (int): the window size for 'range_abs_max' quantization.

        Examples:

        .. code-block:: python

            # the original program will be rewrite, if you don't want to
            # change it, please clone at first.
            # quantize_program = program.clone()
            t = fluid.QuantizeTranspiler()
            t.transpile(quantize_program)

        """
        self.weight_bits = weight_bits
        self.activation_bits = activation_bits
126
        quant_type = ['abs_max', 'range_abs_max', 'moving_average_abs_max']
D
Dang Qingqing 已提交
127 128 129
        if weight_quantize_type not in quant_type:
            raise ValueError(
                "Unknown weight_quantize_type: '%s'. It can only be ",
130
                "'abs_max' or 'range_abs_max' or 'moving_average_abs_max'.",
131 132
                str(weight_quantize_type),
            )
D
Dang Qingqing 已提交
133 134 135
        if activation_quantize_type not in quant_type:
            raise ValueError(
                "Unknown activation_quantize_type : '%s'. It can only be ",
136
                "'abs_max' or 'range_abs_max' or 'moving_average_abs_max'.",
137 138
                str(activation_quantize_type),
            )
D
Dang Qingqing 已提交
139 140 141 142 143

        self.weight_quantize_type = weight_quantize_type
        self.activation_quantize_type = activation_quantize_type

        self.window_size = window_size
144
        self.moving_rate = moving_rate
D
Dang Qingqing 已提交
145 146
        self.helper = LayerHelper(self.__class__.__name__)
        self.fake_quant_op_types = [
147 148 149
            'fake_quantize_abs_max',
            'fake_quantize_range_abs_max',
            'fake_quantize_moving_average_abs_max',
D
Dang Qingqing 已提交
150 151 152 153 154 155 156 157 158
        ]
        self.fake_dequant_op_types = ['fake_dequantize_max_abs']
        self.is_test = None
        self.global_step = None

    def training_transpile(self, program=None, startup_program=None):
        """Rewrites a training input program in place for simulated
        quantization. Insert fake quantization and de-quantization ops into
        program to simulate the error introduced by quantization. And change
T
tianshuo78520a 已提交
159
        the gradient ops' input by using the faked quantization weights and
D
Dang Qingqing 已提交
160 161 162 163 164 165 166 167
        activation. Since the program is transformed in place, the graph
        connection will change.

        Args:
            program (Program): the input program to be transpile.
        """
        self.is_test = False
        program = default_main_program() if program is None else program
168 169 170 171 172
        startup_program = (
            default_startup_program()
            if startup_program is None
            else startup_program
        )
D
Dang Qingqing 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186

        # marked the variable which has been quantized and dequantized.
        dequanted_vars = [
            collections.OrderedDict() for _ in range(len(program.blocks))
        ]
        grad_op_types = ['%s_grad' % (type) for type in _QUANTIZABLE_OP_TYPES]

        params = [p.name for p in program.global_block().iter_parameters()]

        def _transpile_forward(block, op):
            idx = block.ops.index(op)
            block_id = block.idx
            # insert quant op and dequant op
            for name in op.input_arg_names:
187
                # if share input between ops
D
Dang Qingqing 已提交
188 189 190 191
                if name in dequanted_vars[block_id]:
                    dequant_var = dequanted_vars[block_id][name]
                else:
                    var = block.var(name)
192 193 194 195 196 197 198 199 200 201
                    quant_bits = (
                        self.weight_bits
                        if var.name in params
                        else self.activation_bits
                    )
                    quant_type = (
                        self.weight_quantize_type
                        if var.name in params
                        else self.activation_quantize_type
                    )
D
Dang Qingqing 已提交
202 203

                    quant_var, scale_var = self._insert_quant_op(
204 205
                        block, idx, var, quant_bits, quant_type
                    )
D
Dang Qingqing 已提交
206
                    dequant_var = self._insert_dequant_op(
207 208
                        block, idx + 1, quant_var, scale_var, quant_bits
                    )
D
Dang Qingqing 已提交
209 210
                    dequanted_vars[block_id][name] = dequant_var
                # rename the forward op inputs
211
                op._rename_input(name, dequant_var.name)
D
Dang Qingqing 已提交
212 213 214 215 216 217 218

        def _transpile_backward(block, op):
            block_id = block.idx
            no_dequanted_input_vars = True
            for name in op.input_arg_names:
                if name in dequanted_vars[block_id]:
                    dequant_var = dequanted_vars[block_id][name]
219
                    op._rename_input(name, dequant_var.name)
D
Dang Qingqing 已提交
220 221
                    no_dequanted_input_vars = False
            if no_dequanted_input_vars:
222 223 224
                raise ValueError(
                    "There is no dequanted inputs for op %s." % (op.type)
                )
D
Dang Qingqing 已提交
225 226

        with program_guard(program, startup_program):
D
Dang Qingqing 已提交
227
            self._create_global_step()
D
Dang Qingqing 已提交
228 229 230 231 232 233 234 235 236 237 238
            for block in program.blocks:
                ops = list(block.ops)
                block_id = block.idx
                for op in ops:
                    # rewrite the forward ProgramDes
                    if op.type in _QUANTIZABLE_OP_TYPES:
                        _transpile_forward(block, op)
                    # rename the backward op inputs
                    if op.type in grad_op_types:
                        _transpile_backward(block, op)

D
Dang Qingqing 已提交
239
    def _create_global_step(self):
240 241 242 243
        if (
            self.weight_quantize_type == 'range_abs_max'
            or self.activation_quantize_type == 'range_abs_max'
        ):
D
Dang Qingqing 已提交
244 245
            self.global_step = autoincreased_step_counter()

246
    def freeze_program(self, program, place, scope=None):
D
Dang Qingqing 已提交
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
        """Freeze input training program for inference.

        Args:
            program (Program): the input program to be transpile.
        """

        self.is_test = True
        scope = global_scope() if scope is None else scope
        program = default_main_program() if program is None else program

        persistable_vars = [
            v.name
            for v in filter(lambda var: var.persistable, program.list_vars())
        ]
        op_in_rename_map = [
            collections.OrderedDict() for _ in range(len(program.blocks))
        ]
        op_out_rename_map = [
            collections.OrderedDict() for _ in range(len(program.blocks))
        ]
        var_scale_map = [
            collections.OrderedDict() for _ in range(len(program.blocks))
        ]

        def _remove_fake_quant_and_dequant_op(block, op):
            idx = block.ops.index(op)
            block_id = block.idx
            k = op.output('Out')[0]
            v = op.input('X')[0]
            if v not in op_in_rename_map[block_id]:
                op_in_rename_map[block_id][k] = v
            else:
                op_in_rename_map[block_id][k] = op_in_rename_map[block_id][v]
            block._remove_op(idx)

        def _insert_post_dequant_op(block, op):
            idx = block.ops.index(op)
            block_id = block.idx
            max_range = None
            scale_var = None
            for name in op.input_arg_names:
288
                # rename input name of the op to the input name of last op which has be removed
D
Dang Qingqing 已提交
289
                if name in op_in_rename_map[block_id]:
290
                    op._rename_input(name, op_in_rename_map[block_id][name])
D
Dang Qingqing 已提交
291 292 293 294 295 296 297 298 299

                scale_v = var_scale_map[block_id][_original_var_name(name)]
                if _original_var_name(name) in persistable_vars:
                    param_range = (1 << (self.weight_bits - 1)) - 1
                    act_range = (1 << (self.activation_bits - 1)) - 1
                    assert _is_float(scale_v)
                    max_range = param_range * act_range / scale_v
                else:
                    assert isinstance(scale_v, Variable)
300
                    scale_var = scale_v
D
Dang Qingqing 已提交
301 302

            if len(op.output_arg_names) != 1:
303 304 305 306
                raise ValueError(
                    "Only support one output, but op %s has"
                    " more than one output." % (op.type)
                )
D
Dang Qingqing 已提交
307
            out_var = block.var(op.output_arg_names[0])
308 309 310 311 312 313
            dequant_var = block.create_var(
                name=_dequantized_var_name(out_var.name),
                type=out_var.type,
                shape=out_var.shape,
                dtype=out_var.dtype,
            )
D
Dang Qingqing 已提交
314
            # insert fake_dequantize_op
315 316 317 318 319 320 321
            dequant_op = block._insert_op(
                idx + 1,
                type="fake_dequantize_max_abs",
                attrs={'max_range': float(max_range)},
                inputs={"X": out_var, 'Scale': scale_var},
                outputs={"Out": dequant_var},
            )
D
Dang Qingqing 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
            op_out_rename_map[block_id][out_var.name] = dequant_var.name
            return dequant_var

        def _load_var(name):
            return np.array(scope.find_var(name).get_tensor())

        def _restore_var(name, arr):
            t = scope.find_var(name).get_tensor()
            t.set(arr, place)

        for block in program.blocks:
            ops = list(block.ops)
            block_id = block.idx
            for op in ops:
                op_type = op.type

                # insert dequant_op after fc/conv, need to rename
339
                # input of the followed ops(of fc/conv) to the dquant_op
D
Dang Qingqing 已提交
340 341
                for name in op.input_arg_names:
                    if name in op_out_rename_map[block_id]:
342 343 344
                        op._rename_input(
                            name, op_out_rename_map[block_id][name]
                        )
D
Dang Qingqing 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

                if op_type in self.fake_quant_op_types:
                    in_arg_name = op.input('X')[0]
                    if in_arg_name in persistable_vars:
                        if self.weight_quantize_type == 'abs_max':
                            param = _load_var(in_arg_name)
                            scale_v = np.max(np.abs(param))
                        else:
                            scale_v = _load_var(op.output('OutScale')[0])
                        var_scale_map[block_id][in_arg_name] = scale_v
                    else:
                        scale_v = block.var(op.output('OutScale')[0])
                        var_scale_map[block_id][in_arg_name] = scale_v

                    if in_arg_name in persistable_vars:
                        _remove_fake_quant_and_dequant_op(block, op)
                        # quantize weight and restore
                        param_t = _load_var(in_arg_name)
                        param_q_t = quant(param_t, scale_v, self.weight_bits)
                        _restore_var(in_arg_name, param_q_t)

                if op_type in self.fake_dequant_op_types:
                    _remove_fake_quant_and_dequant_op(block, op)

                if op_type in _QUANTIZABLE_OP_TYPES:
                    dequant_var = _insert_post_dequant_op(block, op)

        # remove the unused var in ProgramDesc
        self._remove_unused_var(program)
374
        # program = program.clone()
D
Dang Qingqing 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    def convert_to_int8(self, program, place, scope=None):
        scope = global_scope() if scope is None else scope
        program = default_main_program() if program is None else program

        def _load_var(name):
            return np.array(scope.find_var(name).get_tensor())

        global_block = program.global_block()

        def convert_to_int8(var):
            int8_var_name = var.name + ".int8"
            int8_var = global_block.create_parameter(
                name=int8_var_name.encode('ascii'),
                type=var.type,
                dtype=core.VarDesc.VarType.INT8,
391 392
                shape=var.shape,
            )
D
Dang Qingqing 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

            tensor = _load_var(var.name)

            scope.var(int8_var_name)
            int8_tensor = scope.find_var(int8_var_name).get_tensor()
            int8_tensor.set(tensor.astype(np.int8), place)
            return int8_var

        input_map = {}
        for block in program.blocks:
            for op in list(block.ops):
                if op.type in _QUANTIZABLE_OP_TYPES:
                    for name in op.input_arg_names:
                        var = block.var(name)
                        if var.persistable:
                            if name not in input_map:
                                int8_var = convert_to_int8(var)
                                input_map[name] = int8_var.name
411
                            op._rename_input(name, input_map[name])
D
Dang Qingqing 已提交
412 413 414
        self._remove_unused_var(program)

    def _remove_unused_var(self, program):
415
        all_remove_vars = []
D
Dang Qingqing 已提交
416 417 418 419 420
        for block in program.blocks:
            args = []
            for op in block.ops:
                args += op.input_arg_names
                args += op.output_arg_names
421
            args = list(set(args))  # vals of all left ops
422
            var_names = block.vars.keys()  # all vals
423
            sub_block_remove_vars = []
D
Dang Qingqing 已提交
424
            for var in var_names:
D
Dang Qingqing 已提交
425
                if var not in args:
426 427 428 429 430 431 432
                    sub_block_remove_vars.append(var)
            all_remove_vars.append(sub_block_remove_vars)

        remove_vars = [list(set(v)) for v in all_remove_vars]
        for i, block in enumerate(program.blocks):
            for v in remove_vars[i]:
                block._remove_var(v)
D
Dang Qingqing 已提交
433 434

    def _insert_quant_abs_max_op(self, block, idx, var, quant_bits):
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
        """Insert fake_quantize_abs_max op."""
        quant_var = block.create_var(
            name=_quantized_var_name(var.name),
            type=var.type,
            shape=var.shape,
            dtype=var.dtype,
        )
        scale = block.create_var(
            name=_quantized_scale_name(var.name),
            type=var.type,
            shape=var.shape,
            dtype=var.dtype,
        )
        quant_op = block._insert_op(
            idx,
            type='fake_quantize_abs_max',
            attrs={'bit_length': quant_bits},
            inputs={'X': var},
            outputs={'Out': quant_var, 'OutScale': scale},
        )
D
Dang Qingqing 已提交
455 456 457
        return quant_var, scale

    def _insert_quant_range_abs_max_op(self, block, idx, var, quant_bits):
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        """Insert fake_quantize_range_abs_max"""
        quant_var = block.create_var(
            name=_quantized_var_name(var.name),
            type=var.type,
            shape=var.shape,
            dtype=var.dtype,
        )
        scale = self.helper.create_parameter(
            attr=ParamAttr(
                name=_quantized_scale_name(var.name),
                initializer=Constant(0.001),
                trainable=False,
            ),
            shape=[1],
            dtype=var.dtype,
        )
D
Dang Qingqing 已提交
474 475 476 477 478 479 480 481 482 483
        scale.stop_gradient = True

        ins = {'X': var, 'InScale': scale}
        outs = {'Out': quant_var, 'OutScale': scale}
        if not self.is_test:
            # A global step counter variable with type int64
            scales = self.helper.create_global_variable(
                name=unique_name.generate('scales'),
                persistable=True,
                dtype=var.dtype,
484 485 486 487 488
                shape=[self.window_size],
            )
            self.helper.set_variable_initializer(
                scales, initializer=Constant(value=0)
            )
D
Dang Qingqing 已提交
489 490 491 492 493 494 495

            ins['Iter'] = self.global_step
            outs['OutScales'] = scales

        attrs = {
            'window_size': self.window_size,
            'bit_length': quant_bits,
496
            'is_test': self.is_test,
D
Dang Qingqing 已提交
497 498
        }

499 500 501 502 503 504 505
        quant_op = block._insert_op(
            idx,
            type='fake_quantize_range_abs_max',
            attrs=attrs,
            inputs=ins,
            outputs=outs,
        )
D
Dang Qingqing 已提交
506 507 508

        return quant_var, scale

509 510 511 512 513 514 515 516 517 518
    def _insert_quant_moving_average_abs_max_op(
        self, block, idx, var, quant_bits
    ):
        """Insert fake_quantize_moving_average_abs_max"""
        quant_var = block.create_var(
            name=_quantized_var_name(var.name),
            type=var.type,
            shape=var.shape,
            dtype=var.dtype,
        )
519 520 521 522
        state = self.helper.create_global_variable(
            name=unique_name.generate('state'),
            persistable=True,
            dtype=var.dtype,
523 524 525 526 527
            shape=[1],
        )
        self.helper.set_variable_initializer(
            state, initializer=Constant(value=1)
        )
528 529 530 531
        accum = self.helper.create_global_variable(
            name=unique_name.generate('accum'),
            persistable=True,
            dtype=var.dtype,
532 533 534 535 536 537 538 539 540 541 542 543 544 545
            shape=[1],
        )
        self.helper.set_variable_initializer(
            accum, initializer=Constant(value=1)
        )
        scale = self.helper.create_parameter(
            attr=ParamAttr(
                name=_quantized_scale_name(var.name),
                initializer=Constant(0.001),
                trainable=False,
            ),
            shape=[1],
            dtype=var.dtype,
        )
546 547 548 549 550 551 552 553 554 555 556 557 558
        scale.stop_gradient = True

        ins = {'X': var, 'InScale': scale}
        outs = {'Out': quant_var, 'OutScale': scale}
        if not self.is_test:
            ins['InState'] = state
            ins['InAccum'] = accum
            outs['OutState'] = state
            outs['OutAccum'] = accum

        attrs = {
            'bit_length': quant_bits,
            'moving_rate': self.moving_rate,
559
            'is_test': self.is_test,
560 561
        }

562 563 564 565 566 567 568
        quant_op = block._insert_op(
            idx,
            type='fake_quantize_moving_average_abs_max',
            attrs=attrs,
            inputs=ins,
            outputs=outs,
        )
569 570 571

        return quant_var, scale

D
Dang Qingqing 已提交
572 573 574 575 576 577 578
    def _insert_quant_op(self, block, idx, var, quant_bits, quant_type):
        """
        Insert fake_quantize_op
        """
        if quant_type == 'abs_max':
            return self._insert_quant_abs_max_op(block, idx, var, quant_bits)
        elif quant_type == 'range_abs_max':
579 580 581
            return self._insert_quant_range_abs_max_op(
                block, idx, var, quant_bits
            )
582
        elif quant_type == 'moving_average_abs_max':
583
            return self._insert_quant_moving_average_abs_max_op(
584 585
                block, idx, var, quant_bits
            )
D
Dang Qingqing 已提交
586 587 588 589 590

    def _insert_dequant_op(self, block, idx, var, scale, quant_bits):
        """
        Insert fake_quantize_op
        """
591 592 593 594 595 596
        dequant_var = block.create_var(
            name=_dequantized_var_name(var.name),
            type=var.type,
            shape=var.shape,
            dtype=var.dtype,
        )
D
Dang Qingqing 已提交
597 598
        # insert fake_dequantize_op
        max_range = (1 << (quant_bits - 1)) - 1
599 600 601 602 603 604 605
        dequant_op = block._insert_op(
            idx,
            type="fake_dequantize_max_abs",
            attrs={'max_range': float(max_range)},
            inputs={"X": var, 'Scale': scale},
            outputs={"Out": dequant_var},
        )
D
Dang Qingqing 已提交
606
        return dequant_var