test_qat.py 9.9 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 22 23 24
    DequantStub,
    Module,
    QuantStub,
)
25 26 27 28 29 30
from megengine.quantization.quantize import (
    disable_fake_quant,
    enable_fake_quant,
    quantize,
    quantize_qat,
)
31 32 33 34 35 36


def test_qat_convbn2d():
    in_channels = 32
    out_channels = 64
    kernel_size = 3
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

    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))
54
    for groups, bias in product([1, 4], [True, False]):
55 56 57 58 59 60
        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)
61
        np.testing.assert_allclose(
62
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-4,
63 64
        )
        np.testing.assert_allclose(
65 66
            net.conv_bn.bn.running_mean.numpy(),
            qat_net.conv_bn.bn.running_mean.numpy(),
67 68 69
            atol=5e-8,
        )
        np.testing.assert_allclose(
70 71 72
            net.conv_bn.bn.running_var.numpy(),
            qat_net.conv_bn.bn.running_var.numpy(),
            atol=5e-7,
73
        )
74 75 76 77
        net.eval()
        normal_outputs = net(inputs)
        qat_net.eval()
        qat_outputs = qat_net(inputs)
78
        np.testing.assert_allclose(
79
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-4,
80 81 82 83 84 85 86
        )


def test_qat_convtransposebn2d():
    in_channels = 32
    out_channels = 64
    kernel_size = 3
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

    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

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


128 129 130 131 132 133 134 135 136 137 138 139
@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):
140 141 142 143 144 145 146 147 148 149 150

    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(
151 152 153 154 155 156 157
                in_channels,
                out_channels,
                kernel_size,
                groups=groups,
                bias=bias,
                padding=padding,
                padding_mode=padding_mode,
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
            )
            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)
178
        np.testing.assert_allclose(normal_outputs.numpy(), qat_outputs.numpy())
179 180 181 182 183

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


187
@pytest.mark.skipif(get_device_count("gpu") > 0, reason="no int8 algorithm on cuda")
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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
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)
285 286
        infer_cg = cgtools.GraphInference(file)[0]
        dumped_outputs = list(infer_cg.run(inputs.numpy()).values())[0]
287
        np.testing.assert_allclose(quantize_outputs.numpy(), dumped_outputs, atol=1e-6)
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302


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
            )
303 304 305
            self.conv_transpose2d_relu = ConvTransposeRelu2d(
                out_channels, in_channels, kernel_size, bias=bias
            )
306 307 308 309

        def forward(self, inp):
            out = self.quant(inp)
            out = self.conv(out)
310
            out = self.conv_transpose2d_relu(out)
311 312 313 314 315 316 317 318 319 320 321
            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)
322 323 324
        np.testing.assert_allclose(
            normal_outputs.numpy(), qat_outputs.numpy(), atol=1e-6
        )
325 326 327 328 329

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