|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +from torch.testing._internal.common_utils import TestCase |
| 4 | +import intel_extension_for_pytorch # noqa |
| 5 | + |
| 6 | +from torch.quantization.quantize_jit import ( |
| 7 | + convert_jit, |
| 8 | + prepare_jit, |
| 9 | +) |
| 10 | +import pytest |
| 11 | +import time |
| 12 | + |
| 13 | +def trace_int8_model(model, device, test_input): |
| 14 | + model = model.to(device) |
| 15 | + modelJit = torch.jit.trace(model, test_input.to(device)) |
| 16 | + modelJit.eval() |
| 17 | + modelJit.to(device) |
| 18 | + print(modelJit) |
| 19 | + print("finish jit tracing...") |
| 20 | + |
| 21 | + print("start ", device, " calibration ...") |
| 22 | + qconfig_u8 = torch.quantization.QConfig( |
| 23 | + activation=torch.quantization.observer.MinMaxObserver.with_args( |
| 24 | + qscheme=torch.per_tensor_symmetric, |
| 25 | + reduce_range=False, |
| 26 | + dtype=torch.quint8 |
| 27 | + ), |
| 28 | + weight=torch.quantization.default_weight_observer |
| 29 | + ) |
| 30 | + |
| 31 | + modelJit = prepare_jit(modelJit, {'': qconfig_u8}, True) |
| 32 | + |
| 33 | + # do calibration |
| 34 | + test_input = test_input.to(device) |
| 35 | + with torch.no_grad(): |
| 36 | + for i in range(1): |
| 37 | + calib_input = test_input |
| 38 | + modelJit(calib_input) |
| 39 | + print("start ", device, " convert...") |
| 40 | + modelJit = convert_jit(modelJit, True) |
| 41 | + # inference |
| 42 | + print("start ", device, " inference ...") |
| 43 | + with torch.no_grad(): |
| 44 | + for i in range(1): |
| 45 | + start = time.time() |
| 46 | + output_cpu = modelJit(test_input) |
| 47 | + end = time.time() |
| 48 | + print("iter.{} ... {time:.3f}ms".format(i, time=(end - start) * 1000)) |
| 49 | + print("print ", device, " jit graph ....") |
| 50 | + print(modelJit.graph_for(test_input)) |
| 51 | + |
| 52 | + print("get ", device, " test input result....") |
| 53 | + output = modelJit(test_input) |
| 54 | + print("finish ", device, " testing.......") |
| 55 | + return output |
| 56 | + |
| 57 | +class SimpleModule(nn.Module): |
| 58 | + def __init__(self): |
| 59 | + super().__init__() |
| 60 | + self.conv = nn.Conv2d(3, 6, 3, 1, 1) |
| 61 | + self.instance_norm = nn.InstanceNorm2d(6, **{'eps': 1e-5, 'affine': True, 'momentum': 0.1}) |
| 62 | + |
| 63 | + def forward(self, x): |
| 64 | + x = self.conv(x) |
| 65 | + x = self.instance_norm(x) |
| 66 | + return x |
| 67 | + |
| 68 | + |
| 69 | +class TestQTensortoPlain(TestCase): |
| 70 | + def test_q_to_plain(self): |
| 71 | + mod = SimpleModule() |
| 72 | + test_input = torch.randn(3, 3, 16, 16) |
| 73 | + with torch.no_grad(): |
| 74 | + with torch.xpu.onednn_layout(): |
| 75 | + trace_int8_model(mod, "xpu", test_input) |
| 76 | + |
0 commit comments