test_quantize.py 8.4 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 9 10
#
# 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 numpy as np
import pytest

11
from megengine import Parameter, Tensor
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
from megengine import module as Float
from megengine.module import qat as QAT
from megengine.module import quantized as Q
from megengine.quantization import (
    min_max_fakequant_qconfig,
    passive_qconfig,
    tqt_qconfig,
)
from megengine.quantization.fake_quant import TQT, FakeQuantize
from megengine.quantization.observer import MinMaxObserver, PassiveObserver
from megengine.quantization.quantize import (
    _get_quantable_module_names,
    apply_easy_quant,
    disable_fake_quant,
    disable_observer,
    enable_fake_quant,
    enable_observer,
    propagate_qconfig,
    quantize,
    quantize_qat,
    reset_qconfig,
)


36
class FloatNet(Float.Module):
37 38 39 40 41
    def __init__(self):
        super().__init__()
        self.quant = Float.QuantStub()
        self.linear = Float.Linear(3, 3)
        self.dequant = Float.DequantStub()
42
        self.linear.bias[...] = Parameter(np.random.rand(3))
43 44 45 46 47 48 49 50 51 52 53 54 55 56

    def forward(self, x):
        x = self.quant(x)
        x = self.linear(x)
        x = self.dequant(x)
        return x


class QATNet(Float.Module):
    def __init__(self):
        super().__init__()
        self.quant = QAT.QuantStub()
        self.linear = QAT.Linear(3, 3)
        self.dequant = QAT.DequantStub()
57
        self.linear.bias[...] = Parameter(np.random.rand(3))
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

    def forward(self, x):
        x = self.quant(x)
        x = self.linear(x)
        x = self.dequant(x)
        return x


def test_propagate_qconfig():
    net = QATNet()
    propagate_qconfig(net, min_max_fakequant_qconfig)
    assert all(
        [
            net.quant.weight_observer is None,
            net.quant.weight_fake_quant is None,
            isinstance(net.quant.act_observer, MinMaxObserver),
            isinstance(net.quant.act_fake_quant, FakeQuantize),
            isinstance(net.linear.weight_observer, MinMaxObserver),
            isinstance(net.linear.weight_fake_quant, FakeQuantize),
            isinstance(net.linear.act_observer, MinMaxObserver),
            isinstance(net.linear.act_fake_quant, FakeQuantize),
            net.dequant.weight_observer is None,
            net.dequant.weight_fake_quant is None,
            net.dequant.act_observer is None,
            net.dequant.act_observer is None,
        ]
    )


def init_qat_net():
    net = QATNet()
    propagate_qconfig(net, min_max_fakequant_qconfig)
90 91
    min_val = np.random.randint(-127, 0, size=(3,))
    max_val = np.random.randint(1, 127, size=(3,))
92 93 94 95 96 97
    net.quant.act_observer.min_val[...] = Parameter(min_val[0])
    net.quant.act_observer.max_val[...] = Parameter(max_val[0])
    net.linear.weight_observer.min_val[...] = Parameter(min_val[1])
    net.linear.weight_observer.max_val[...] = Parameter(max_val[1])
    net.linear.act_observer.min_val[...] = Parameter(min_val[2])
    net.linear.act_observer.max_val[...] = Parameter(max_val[2])
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    return net


def test_reset_qconfig():
    qat_net = init_qat_net()
    new_qat_net = reset_qconfig(qat_net, passive_qconfig)
    assert (
        new_qat_net.linear.get_weight_qparams() == qat_net.linear.get_weight_qparams()
    )
    assert (
        new_qat_net.linear.get_activation_qparams()
        == qat_net.linear.get_activation_qparams()
    )


def test_enable_and_disable_observer():
    net = init_qat_net()
    enable_observer(net)
116 117 118
    assert net.quant.act_observer.enabled is True
    assert net.linear.weight_observer.enabled is True
    assert net.linear.act_observer.enabled is True
119
    disable_observer(net)
120 121 122
    assert net.quant.act_observer.enabled is False
    assert net.linear.weight_observer.enabled is False
    assert net.linear.act_observer.enabled is False
123 124 125 126 127


def test_enable_and_disable_fake_quant():
    net = init_qat_net()
    disable_fake_quant(net)
128 129 130
    assert net.quant.act_fake_quant.enabled is False
    assert net.linear.weight_fake_quant.enabled is False
    assert net.linear.act_fake_quant.enabled is False
131
    enable_fake_quant(net)
132 133 134
    assert net.quant.act_fake_quant.enabled is True
    assert net.linear.weight_fake_quant.enabled is True
    assert net.linear.act_fake_quant.enabled is True
135 136 137 138 139 140 141 142 143 144 145


def init_observer(module, data):
    enable_observer(module)
    disable_fake_quant(module)
    module(data)
    disable_observer(module)
    enable_fake_quant(module)


def test_enable_and_disable_all():
146
    x = Tensor(np.random.randint(1, 10, size=(3, 3)).astype(np.float32))
147
    net = FloatNet()
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
    y1 = net(x).numpy()
    net = quantize_qat(net, min_max_fakequant_qconfig)

    init_observer(net, x)

    y2 = net(x).numpy()
    disable_fake_quant(net)
    y3 = net(x).numpy()
    enable_fake_quant(net)
    y4 = net(x).numpy()
    np.testing.assert_allclose(y1, y3)
    np.testing.assert_allclose(y2, y4)
    with pytest.raises(AssertionError):
        np.testing.assert_allclose(y2, y3)


def test_quantize_qat():
165
    net = FloatNet()
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    qat_net = quantize_qat(net, inplace=False, qconfig=min_max_fakequant_qconfig)
    assert isinstance(qat_net.quant, QAT.QuantStub)
    assert isinstance(qat_net.linear, QAT.Linear)
    assert isinstance(qat_net.dequant, QAT.DequantStub)


def test_quantize():
    qat_net = init_qat_net()
    q_net = quantize(qat_net, inplace=False)
    assert isinstance(q_net.quant, Q.QuantStub)
    assert isinstance(q_net.linear, Q.Linear)
    assert isinstance(q_net.dequant, Q.DequantStub)


def test_apply_easy_quant():
    qat_net = init_qat_net()
182
    data = Tensor(np.random.rand(2, 3, 3, 3), dtype=np.float32)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 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
    eq_net = reset_qconfig(qat_net, passive_qconfig, inplace=False)
    apply_easy_quant(eq_net, data, 0.9, 1.1, 10)
    assert isinstance(eq_net.quant.act_observer, PassiveObserver)
    assert isinstance(eq_net.linear.weight_observer, PassiveObserver)
    assert isinstance(eq_net.linear.act_observer, PassiveObserver)
    assert eq_net.dequant.act_observer is None


def test_apply_tqt():
    qat_net = init_qat_net()
    tqt_net = reset_qconfig(qat_net, tqt_qconfig, inplace=False)
    assert isinstance(tqt_net.quant.act_fake_quant, TQT)
    assert isinstance(tqt_net.linear.weight_fake_quant, TQT)
    assert isinstance(tqt_net.linear.act_fake_quant, TQT)
    assert tqt_net.dequant.act_fake_quant is None


def test_get_quantable_module_names():
    # need to make sure names from Quantized and QAT are the same
    def _get_qat_module_names():
        def is_qat(key: str):
            value = getattr(QAT, key)
            return (
                isinstance(value, type)
                and issubclass(value, QAT.QATModule)
                and value != QAT.QATModule
            )

        # source should have all quantable modules' names
        quantable_module_names = [key for key in dir(QAT) if is_qat(key)]
        return quantable_module_names

    qat_module_names = _get_qat_module_names()
    quantized_module_names = _get_quantable_module_names()
    assert set(qat_module_names) == set(quantized_module_names)

    for key in qat_module_names:
        value = getattr(Float, key)
        assert (
            isinstance(value, type)
            and issubclass(value, Float.Module)
            and value != Float.Module
        )


def test_disable_quantize():
    class Net(Float.Module):
        def __init__(self):
            super().__init__()
            self.conv = Float.ConvBnRelu2d(3, 3, 3)
            self.conv.disable_quantize()

        def forward(self, x):
            return self.conv(x)

    net = Net()
    qat_net = quantize_qat(net, inplace=False)
    assert isinstance(qat_net.conv, Float.ConvBnRelu2d)
    assert isinstance(qat_net.conv.conv, Float.Conv2d)


def test_convert_with_custom_mapping():
    class FloatExample(Float.Module):
        def forward(self, x):
            return x

    class QATExample(QAT.QATModule):
        def forward(self, x):
            return x

        @classmethod
        def from_float_module(cls, float_module):
            return cls()

    class Net(Float.Module):
        def __init__(self):
            super().__init__()
            self.example = FloatExample()

        def forward(self, x):
            return self.example(x)

    net = Net()
    qat_net = quantize_qat(net, inplace=False, mapping={FloatExample: QATExample})
    assert isinstance(qat_net.example, QATExample)