test_quantize.py 12.5 KB
Newer Older
1 2 3
import numpy as np
import pytest

4
from megengine import Parameter, Tensor
5
from megengine import module as Float
6 7 8 9 10 11 12 13 14
from megengine.functional import ones, zeros
from megengine.module import (
    BatchNorm2d,
    Conv2d,
    ConvBn2d,
    ConvTranspose2d,
    ConvTransposeBn2d,
    ReLU,
)
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
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
from megengine.utils.bn_fusion import fuse_conv_bn_relu_module
37 38


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

    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()
59
        self.linear = Float.Sequential(QAT.Linear(3, 3), QAT.Linear(3, 3))
60
        self.dequant = QAT.DequantStub()
61 62
        self.linear[0].bias[...] = Parameter(np.random.rand(3))
        self.linear[1].bias[...] = Parameter(np.random.rand(3))
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

    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),
80 81 82 83 84 85 86 87
            isinstance(net.linear[0].weight_observer, MinMaxObserver),
            isinstance(net.linear[0].weight_fake_quant, FakeQuantize),
            isinstance(net.linear[0].act_observer, MinMaxObserver),
            isinstance(net.linear[0].act_fake_quant, FakeQuantize),
            isinstance(net.linear[1].weight_observer, MinMaxObserver),
            isinstance(net.linear[1].weight_fake_quant, FakeQuantize),
            isinstance(net.linear[1].act_observer, MinMaxObserver),
            isinstance(net.linear[1].act_fake_quant, FakeQuantize),
88 89 90 91 92 93 94 95 96 97 98
            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)
99 100
    min_val = np.random.randint(-127, 0, size=(3,))
    max_val = np.random.randint(1, 127, size=(3,))
101 102
    net.quant.act_observer.min_val[...] = Parameter(min_val[0])
    net.quant.act_observer.max_val[...] = Parameter(max_val[0])
103 104 105 106 107 108 109 110
    net.linear[0].weight_observer.min_val[...] = Parameter(min_val[1])
    net.linear[0].weight_observer.max_val[...] = Parameter(max_val[1])
    net.linear[0].act_observer.min_val[...] = Parameter(min_val[2])
    net.linear[0].act_observer.max_val[...] = Parameter(max_val[2])
    net.linear[1].weight_observer.min_val[...] = Parameter(min_val[1])
    net.linear[1].weight_observer.max_val[...] = Parameter(max_val[1])
    net.linear[1].act_observer.min_val[...] = Parameter(min_val[2])
    net.linear[1].act_observer.max_val[...] = Parameter(max_val[2])
111 112 113 114 115 116 117
    return net


def test_reset_qconfig():
    qat_net = init_qat_net()
    new_qat_net = reset_qconfig(qat_net, passive_qconfig)
    assert (
118 119
        new_qat_net.linear[0].get_weight_qparams()
        == qat_net.linear[0].get_weight_qparams()
120 121
    )
    assert (
122 123 124 125 126 127 128 129 130 131
        new_qat_net.linear[0].get_activation_qparams()
        == qat_net.linear[0].get_activation_qparams()
    )
    assert (
        new_qat_net.linear[1].get_weight_qparams()
        == qat_net.linear[1].get_weight_qparams()
    )
    assert (
        new_qat_net.linear[1].get_activation_qparams()
        == qat_net.linear[1].get_activation_qparams()
132 133 134 135 136 137
    )


def test_enable_and_disable_observer():
    net = init_qat_net()
    enable_observer(net)
138
    assert net.quant.act_observer.enabled is True
139 140 141 142
    assert net.linear[0].weight_observer.enabled is True
    assert net.linear[0].act_observer.enabled is True
    assert net.linear[1].weight_observer.enabled is True
    assert net.linear[1].act_observer.enabled is True
143
    disable_observer(net)
144
    assert net.quant.act_observer.enabled is False
145 146 147 148
    assert net.linear[0].weight_observer.enabled is False
    assert net.linear[0].weight_observer.enabled is False
    assert net.linear[1].act_observer.enabled is False
    assert net.linear[1].act_observer.enabled is False
149 150 151 152 153


def test_enable_and_disable_fake_quant():
    net = init_qat_net()
    disable_fake_quant(net)
154
    assert net.quant.act_fake_quant.enabled is False
155 156 157 158
    assert net.linear[0].weight_fake_quant.enabled is False
    assert net.linear[0].act_fake_quant.enabled is False
    assert net.linear[1].weight_fake_quant.enabled is False
    assert net.linear[1].act_fake_quant.enabled is False
159
    enable_fake_quant(net)
160
    assert net.quant.act_fake_quant.enabled is True
161 162 163 164
    assert net.linear[0].weight_fake_quant.enabled is True
    assert net.linear[0].act_fake_quant.enabled is True
    assert net.linear[1].weight_fake_quant.enabled is True
    assert net.linear[1].act_fake_quant.enabled is True
165 166 167 168 169 170 171 172 173 174 175


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():
176
    x = Tensor(np.random.randint(1, 10, size=(3, 3)).astype(np.float32))
177
    net = FloatNet()
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    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():
195
    net = FloatNet()
196 197
    qat_net = quantize_qat(net, inplace=False, qconfig=min_max_fakequant_qconfig)
    assert isinstance(qat_net.quant, QAT.QuantStub)
198 199
    assert isinstance(qat_net.linear[0], QAT.Linear)
    assert isinstance(qat_net.linear[1], QAT.Linear)
200 201 202 203 204 205 206
    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)
207 208
    assert isinstance(q_net.linear[0], Q.Linear)
    assert isinstance(q_net.linear[1], Q.Linear)
209 210 211 212 213
    assert isinstance(q_net.dequant, Q.DequantStub)


def test_apply_easy_quant():
    qat_net = init_qat_net()
214
    data = Tensor(np.random.rand(2, 3, 3, 3), dtype=np.float32)
215 216 217
    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)
218 219 220 221
    assert isinstance(eq_net.linear[0].weight_observer, PassiveObserver)
    assert isinstance(eq_net.linear[0].act_observer, PassiveObserver)
    assert isinstance(eq_net.linear[1].weight_observer, PassiveObserver)
    assert isinstance(eq_net.linear[1].act_observer, PassiveObserver)
222 223 224 225 226 227 228
    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)
229 230 231 232
    assert isinstance(tqt_net.linear[0].weight_fake_quant, TQT)
    assert isinstance(tqt_net.linear[0].act_fake_quant, TQT)
    assert isinstance(tqt_net.linear[1].weight_fake_quant, TQT)
    assert isinstance(tqt_net.linear[1].act_fake_quant, TQT)
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 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
    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)
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385


def test_ConvBn2d_fold_weight_bias():
    in_channels = 32
    out_channels = 64
    kernel_size = 3

    conv = Conv2d(in_channels, out_channels, kernel_size)
    bn = BatchNorm2d(out_channels)
    relu = ReLU()

    fused_conv = fuse_conv_bn_relu_module(conv, bn, relu)
    bn.eval()
    fused_conv.eval()
    inputs = Tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32))
    expected_result = relu(bn(conv(inputs)))
    actual_result = fused_conv(inputs)
    np.testing.assert_allclose(
        expected_result.numpy(), actual_result.numpy(), atol=1e-4
    )

    conv.eval()
    bn.eval()
    relu.eval()
    fused_conv = fuse_conv_bn_relu_module(conv, bn, relu)
    fused_conv.eval()
    expected_result = relu(conv(inputs))
    actual_result = fused_conv(inputs)
    np.testing.assert_allclose(
        expected_result.numpy(), actual_result.numpy(), atol=1e-4
    )

    conv.train()
    bn.train()
    fused_conv = fuse_conv_bn_relu_module(conv, bn, None)
    fused_conv.train()
    expected_result = bn(conv(inputs))
    actual_result = fused_conv(inputs)
    np.testing.assert_allclose(
        expected_result.numpy(), actual_result.numpy(), atol=1e-4
    )


def test_ConvTransposeBn2d_fold_weight_bias():
    in_channels = 32
    out_channels = 64
    kernel_size = 3

    conv = ConvTranspose2d(in_channels, out_channels, kernel_size)
    bn = BatchNorm2d(out_channels)
    relu = ReLU()

    fused_conv = fuse_conv_bn_relu_module(conv, bn, relu)
    bn.eval()
    fused_conv.eval()
    inputs = Tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32))
    expected_result = relu(bn(conv(inputs)))
    actual_result = fused_conv(inputs)
    np.testing.assert_allclose(
        expected_result.numpy(), actual_result.numpy(), atol=1e-4
    )

    conv.eval()
    bn.eval()
    relu.eval()
    fused_conv = fuse_conv_bn_relu_module(conv, bn, relu)
    fused_conv.eval()
    expected_result = relu(conv(inputs))
    actual_result = fused_conv(inputs)
    np.testing.assert_allclose(
        expected_result.numpy(), actual_result.numpy(), atol=1e-4
    )

    conv.train()
    bn.train()
    fused_conv = fuse_conv_bn_relu_module(conv, bn, None)
    fused_conv.train()
    expected_result = bn(conv(inputs))
    actual_result = fused_conv(inputs)
    np.testing.assert_allclose(
        expected_result.numpy(), actual_result.numpy(), atol=1e-4
    )