test_qat.py 13.7 KB
Newer Older
1
import io
2 3 4
from itertools import product

import numpy as np
5
import pytest
6

7
import megengine.utils.comp_graph_tools as cgtools
8 9 10
from megengine import jit
from megengine import module as M
from megengine import tensor
11
from megengine.device import get_device_count
12
from megengine.functional import expand_dims
13
from megengine.module import (
14
    BatchMatMulActivation,
15 16 17
    Conv2d,
    ConvBn2d,
    ConvRelu2d,
18
    ConvTranspose2d,
19 20
    ConvTransposeBn2d,
    ConvTransposeRelu2d,
21
    DequantStub,
22 23 24 25
    Linear,
    LinearBn1d,
    LinearBnRelu1d,
    LinearRelu,
26 27 28
    Module,
    QuantStub,
)
29 30 31 32 33 34
from megengine.quantization.quantize import (
    disable_fake_quant,
    enable_fake_quant,
    quantize,
    quantize_qat,
)
35 36 37 38 39 40


def test_qat_convbn2d():
    in_channels = 32
    out_channels = 64
    kernel_size = 3
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

    class TestNet(Module):
        def __init__(self, groups, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.conv_bn = ConvBn2d(
                in_channels, out_channels, kernel_size, groups=groups, bias=bias,
            )

        def forward(self, inp):
            out = self.quant(inp)
            out = self.conv_bn(out)
            out = self.dequant(out)
            return out

    inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32))
58
    for groups, bias in product([1, 4], [True, False]):
59 60 61 62 63 64
        net = TestNet(groups, bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
65
        np.testing.assert_allclose(
66
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-4,
67 68
        )
        np.testing.assert_allclose(
69 70
            net.conv_bn.bn.running_mean.numpy(),
            qat_net.conv_bn.bn.running_mean.numpy(),
71 72 73
            atol=5e-8,
        )
        np.testing.assert_allclose(
74 75 76
            net.conv_bn.bn.running_var.numpy(),
            qat_net.conv_bn.bn.running_var.numpy(),
            atol=5e-7,
77
        )
78 79 80 81
        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
82
        np.testing.assert_allclose(
83
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-4,
84 85 86 87 88 89 90
        )


def test_qat_convtransposebn2d():
    in_channels = 32
    out_channels = 64
    kernel_size = 3
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

    class TestNet(Module):
        def __init__(self, groups, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.conv_transpose_bn = ConvTransposeBn2d(
                in_channels, out_channels, kernel_size, groups=groups, bias=bias,
            )

        def forward(self, inp):
            out = self.quant(inp)
            out = self.conv_transpose_bn(out)
            out = self.dequant(out)
            return out

107
    for groups, bias in product([1, 4], [True, False]):
108 109 110 111
        net = TestNet(groups, bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
112
        inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32))
113 114
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
115
        np.testing.assert_allclose(
116
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-5,
117
        )
118
        np.testing.assert_allclose(
119 120 121
            net.conv_transpose_bn.bn.running_var.numpy(),
            qat_net.conv_transpose_bn.bn.running_var.numpy(),
            atol=5e-7,
122
        )
123 124 125 126
        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
127
        np.testing.assert_allclose(
128
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-5,
129
        )
130 131


132 133 134 135 136 137 138 139 140 141 142 143
@pytest.mark.parametrize(
    "padding, padding_mode",
    [
        (0, "zeros"),
        ((1, 2), "zeros"),
        (3, "reflect"),
        ((1, 2), "reflect"),
        (4, "replicate"),
        ((1, 2), "replicate"),
    ],
)
def test_qat_conv(padding, padding_mode):
144 145 146 147 148 149 150 151 152 153 154

    in_channels = 32
    out_channels = 64
    kernel_size = 3

    class TestNet(Module):
        def __init__(self, groups, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.conv = Conv2d(
155 156 157 158 159 160 161
                in_channels,
                out_channels,
                kernel_size,
                groups=groups,
                bias=bias,
                padding=padding,
                padding_mode=padding_mode,
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
            )
            self.conv_relu = ConvRelu2d(
                out_channels, in_channels, kernel_size, groups=groups, bias=bias
            )

        def forward(self, inp):
            out = self.quant(inp)
            out = self.conv(out)
            out = self.conv_relu(out)
            out = self.dequant(out)
            return out

    inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32))
    for groups, bias in product([1, 4], [True, False]):
        net = TestNet(groups, bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
182
        np.testing.assert_allclose(normal_outputs.numpy(), qat_outputs.numpy())
183 184 185 186 187

        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
188
        np.testing.assert_allclose(normal_outputs.numpy(), qat_outputs.numpy())
189 190


191
@pytest.mark.skipif(get_device_count("gpu") > 0, reason="no int8 algorithm on cuda")
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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
def test_qat_batchmatmul_activation():
    batch = 4
    in_features = 8
    out_features = 4

    class TestNet(Module):
        def __init__(self, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.batch_mm = BatchMatMulActivation(
                batch, in_features, out_features, bias=bias
            )

        def forward(self, inp):
            out = self.quant(inp)
            out = self.batch_mm(out)
            out = self.dequant(out)
            return out

    inputs = tensor(
        np.random.randn(batch, in_features, out_features).astype(np.float32)
    )
    for bias in (True, False):
        net = TestNet(bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(normal_outputs.numpy(), qat_outputs.numpy())

        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(normal_outputs.numpy(), qat_outputs.numpy())


@pytest.mark.skip(reason="FIXME: abnormal exit")
def test_quantize_batchmatmul_activation():
    batch = 4
    in_features = 8
    out_features = 4

    class TestNet(Module):
        def __init__(self, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.batch_mm = BatchMatMulActivation(
                batch, in_features, out_features, bias=bias
            )

        def forward(self, inp):
            out = self.quant(inp)
            out = self.batch_mm(out)
            out = expand_dims(out, -1)
            out = self.dequant(out)
            return out

    inputs = tensor(
        np.random.randn(batch, in_features, out_features).astype(np.float32)
    )
    for bias in (True, False):
        net = TestNet(bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(normal_outputs.numpy(), qat_outputs.numpy())

        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(normal_outputs.numpy(), qat_outputs.numpy())

        enable_fake_quant(qat_net)
        qat_outputs = qat_net(inputs)
        qnet = quantize(qat_net, inplace=False)
        qnet.eval()
        quantize_outputs = qnet(inputs)
        np.testing.assert_allclose(
            qat_outputs.numpy(), quantize_outputs.numpy(), atol=1e-6
        )

        @jit.trace(capture_as_const=True)
        def f(x):
            qnet.eval()
            return qnet(x)

        f(inputs)
        file = io.BytesIO()
        f.dump(file, enable_nchw4=True)
        file.seek(0)
289 290
        infer_cg = cgtools.GraphInference(file)[0]
        dumped_outputs = list(infer_cg.run(inputs.numpy()).values())[0]
291
        np.testing.assert_allclose(quantize_outputs.numpy(), dumped_outputs, atol=1e-6)
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306


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

    class TestNet(Module):
        def __init__(self, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.conv = ConvTranspose2d(
                in_channels, out_channels, kernel_size, bias=bias
            )
307 308 309
            self.conv_transpose2d_relu = ConvTransposeRelu2d(
                out_channels, in_channels, kernel_size, bias=bias
            )
310 311 312 313

        def forward(self, inp):
            out = self.quant(inp)
            out = self.conv(out)
314
            out = self.conv_transpose2d_relu(out)
315 316 317 318 319 320 321 322 323 324 325
            out = self.dequant(out)
            return out

    inputs = tensor(np.random.randn(4, in_channels, 32, 32).astype(np.float32))
    for bias in [True, False]:
        net = TestNet(bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
326 327 328
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6
        )
329 330 331 332 333

        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
334 335 336
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6
        )
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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460


def test_qat_linearbn1d():
    in_features = 10
    out_features = 5

    class TestNet(Module):
        def __init__(self, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.linear_bn = LinearBn1d(in_features, out_features, bias=bias,)

        def forward(self, inp):
            out = self.quant(inp)
            out = self.linear_bn(out)
            out = self.dequant(out)
            return out

    inputs = tensor(np.random.randn(4, in_features).astype(np.float32))
    for bias in [True, False]:
        net = TestNet(bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6,
        )
        np.testing.assert_allclose(
            net.linear_bn.bn.running_mean.numpy(),
            qat_net.linear_bn.bn.running_mean.numpy(),
            atol=5e-8,
        )
        np.testing.assert_allclose(
            net.linear_bn.bn.running_var.numpy(),
            qat_net.linear_bn.bn.running_var.numpy(),
            atol=5e-7,
        )

        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6,
        )


def test_qat_linear_relu():
    in_features = 10
    out_features = 5

    class TestNet(Module):
        def __init__(self, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.linear_relu = LinearRelu(in_features, out_features, bias=bias,)

        def forward(self, inp):
            out = self.quant(inp)
            out = self.linear_relu(out)
            out = self.dequant(out)
            return out

    inputs = tensor(np.random.randn(4, in_features).astype(np.float32))
    for bias in [True, False]:
        net = TestNet(bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6,
        )

        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6,
        )


def test_qat_linear_bn_relu():
    in_features = 10
    out_features = 5

    class TestNet(Module):
        def __init__(self, bias):
            super().__init__()
            self.quant = QuantStub()
            self.dequant = DequantStub()
            self.linear_bn_relu = LinearBnRelu1d(in_features, out_features, bias=bias,)

        def forward(self, inp):
            out = self.quant(inp)
            out = self.linear_bn_relu(out)
            out = self.dequant(out)
            return out

    inputs = tensor(np.random.randn(4, in_features).astype(np.float32))
    for bias in [True, False]:
        net = TestNet(bias)
        net.train()
        qat_net = quantize_qat(net, inplace=False)
        disable_fake_quant(qat_net)
        normal_outputs = net(inputs)
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6,
        )

        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6,
        )