fake_quant.py 5.9 KB
Newer Older
1 2
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
3
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
4 5 6 7 8
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import math
9
from typing import Union
10 11

from .. import functional as F
12 13
from ..core.tensor.dtype import QuantDtypeMeta, _builtin_quant_dtypes
from ..logger import get_logger
14
from ..module import Module
M
Megvii Engine Team 已提交
15
from ..tensor import Parameter, Tensor
16
from .utils import (
M
Megvii Engine Team 已提交
17
    LSQParams,
18 19 20 21 22
    QParams,
    QParamsModuleMixin,
    QuantMode,
    create_qparams,
    fake_quant_tensor,
M
Megvii Engine Team 已提交
23
    lsq_forward,
24 25
    tqt_forward,
)
26

27
logger = get_logger(__name__)
28 29


30
class _FakeQuantize(Module):
31
    def __init__(
32
        self, dtype: Union[str, QuantDtypeMeta], enable: bool = True, **kwargs
33
    ):
34
        super().__init__()
35 36 37 38 39 40
        if isinstance(dtype, str):
            if not dtype in _builtin_quant_dtypes:
                raise ValueError(
                    "unknown dtype: {}, only support {}".format(
                        dtype, _builtin_quant_dtypes.keys()
                    )
41
                )
42 43 44 45 46 47 48
            dtype = _builtin_quant_dtypes[dtype]
        if "narrow_range" in kwargs:
            del kwargs["narrow_range"]
            logger.warning(
                "FakeQuantize currently has no narrow_range param "
                "so it is ignored here",
                exc_info=DeprecationWarning,
49 50
            )
        self.dtype = dtype
51 52
        self.qmin = dtype.qmin
        self.qmax = dtype.qmax
53 54 55 56 57 58 59 60
        self.enabled = enable

    def enable(self):
        self.enabled = True

    def disable(self):
        self.enabled = False

61 62
    def fake_quant_forward(self, inp, qparams: QParams = None):
        raise NotImplementedError
63

T
tpoisonooo 已提交
64
    def normal_forward(self, inp, qparams: QParams = None):
65 66
        return inp

67
    def forward(self, inp, qparams: QParams = None):
68
        if self.enabled:
69
            return self.fake_quant_forward(inp, qparams=qparams)
70
        else:
T
tpoisonooo 已提交
71
            return self.normal_forward(inp, qparams=qparams)
72 73


74
class TQT(_FakeQuantize, QParamsModuleMixin):
75 76 77
    r"""
    TQT: https://arxiv.org/abs/1903.08066 Trained Quantization Thresholds
    for Accurate and Efficient Fixed-Point Inference of Deep Neural Networks.
78 79

    :param dtype: a string or :class:`~.QuantDtypeMeta` indicating the target
80
        quantization dtype of input.
81
    :param enable: whether do ``normal_forward`` or ``fake_quant_forward``.
82 83
    """

84
    def __init__(
85
        self, dtype: Union[str, QuantDtypeMeta], enable: bool = True, **kwargs
86
    ):
87
        super().__init__(dtype, enable, **kwargs)
88
        self.scale = Parameter(0.0, dtype="float32")
89

90
    def fake_quant_forward(self, inp, qparams: QParams = None):
91
        # when enable, TQT will do fakequant forward, finetune the scale
M
Megvii Engine Team 已提交
92
        return tqt_forward(self.qmin, self.qmax, inp, self.scale)
93

94
    def set_qparams(self, qparams: QParams):
95
        assert (
96
            qparams.mode == QuantMode.SYMMERTIC
97
        ), "only symmetric quantization is supported by TQT"
98
        if qparams.scale is None:
99
            raise AssertionError("Can not get an initialized scale")
100
        self.scale[...] = F.log(qparams.scale) / math.log(2)
101

102 103
    def get_qparams(self):
        return create_qparams(QuantMode.SYMMERTIC, self.dtype, scale=2 ** self.scale)
104 105 106 107 108


class FakeQuantize(_FakeQuantize):
    r"""
    A module to do quant and dequant according to observer's scale and zero_point.
109 110

    :param dtype: a string or :class:`~.QuantDtypeMeta` indicating the target
111
        quantization dtype of input.
112
    :param enable: whether do ``normal_forward`` or ``fake_quant_forward``.
113 114
    """

115 116 117 118 119 120 121
    def fake_quant_forward(self, inp, qparams: QParams = None):
        assert (
            qparams.dtype_meta is self.dtype
        ), "input qparams' dtype is not equal to self.dtype.\nqparams.dtype_meta={}\nself.dtype={}".format(
            qparams.dtype_meta, self.dtype
        )
        return fake_quant_tensor(inp, qparams)
M
Megvii Engine Team 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 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


class LSQ(_FakeQuantize, QParamsModuleMixin):
    r"""
    LSQ: https://arxiv.org/pdf/1902.08153.pdf Estimating and scaling the 
    task loss gradient at each weight and activation layer's quantizer step size

    :param dtype: a string or :class:`~.QuantDtypeMeta` indicating the target
        quantization dtype of input.
    :param enable: whether do ``normal_forward`` or ``fake_quant_forward``.
    :param eps:a small value to avoid division by zero. Default: 1e-5
    """

    def init(
        self,
        dtype: Union[str, QuantDtypeMeta],
        enable: bool = True,
        eps: float = 1e-5,
        **kwargs
    ):
        super().__init__(dtype=dtype, enable=enable, **kwargs)
        self.eps = Tensor(eps, dtype="float32")
        self.step_size = Parameter(1.0, dtype="float32")

    def set_qparams(self, qparams: LSQParams):
        self.mode = qparams.mode
        if qparams.mode == QuantMode.ASYMMERTIC:
            self.zero_point = qparams.zero_point
        else:
            self.zero_point = Tensor([0.0], dtype="float32")
        if qparams.scale is None:
            raise AssertionError("Can not get an initialized scale")
        init_step_size = qparams.scale
        if init_step_size < self.eps:
            init_step_size = 0
        else:
            init_step_size = init_step_size - self.eps
        self.step_size = Parameter(init_step_size, dtype="float32")

        self.grad_scale = qparams.grad_scale

    def fake_quant_forward(self, inp, qparams: LSQParams = None):
        step_size = F.abs(self.step_size) + self.eps
        return lsq_forward(
            self.qmin, self.qmax, inp, step_size, self.zero_point, self.grad_scale
        )

    def get_qparams(self):
        return LSQParams(
            mode=self.mode,
            dtype_meta=self.dtype,
            scale=F.abs(self.step_size.detach()) + self.eps,
            zero_point=self.zero_point,
            grad_scale=self.grad_scale,
        )