Repository: pytorch
Issue: [ONNX] ONNX export of simple quantized model fails
Labels: module: onnx,low priority,triaged

### 🐛 Describe the bug

ONNX export fails for many simple quantized models, such as a single Conv2d or Linear layer.

The below code sample produces these errors:
```
$ python3 test_onnx_export.py 
./home/andrew/.local/lib/python3.8/site-packages/torch/overrides.py:110: UserWarning: 'has_cuda' is deprecated, please use 'torch.backends.cuda.is_built()'
  torch.has_cuda,
/home/andrew/.local/lib/python3.8/site-packages/torch/overrides.py:111: UserWarning: 'has_cudnn' is deprecated, please use 'torch.backends.cudnn.is_available()'
  torch.has_cudnn,
/home/andrew/.local/lib/python3.8/site-packages/torch/overrides.py:117: UserWarning: 'has_mps' is deprecated, please use 'torch.backends.mps.is_built()'
  torch.has_mps,
/home/andrew/.local/lib/python3.8/site-packages/torch/overrides.py:118: UserWarning: 'has_mkldnn' is deprecated, please use 'torch.backends.mkldnn.is_available()'
  torch.has_mkldnn,
/home/andrew/.local/lib/python3.8/site-packages/torch/fx/graph.py:1377: UserWarning: Node _packed_weight_0 target _packed_weight_0 _packed_weight_0 of  does not reference an nn.Module, nn.Parameter, or buffer, which is what 'get_attr' Nodes typically target
  warnings.warn(f'Node {node} target {node.target} {atom} of {seen_qualname} does '
E...E.E
======================================================================
ERROR: test_conv2d_quantized (__main__.TestOnnxExportConv2d)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_onnx_export.py", line 112, in test_conv2d_quantized
    self._onnx_export_quantized()
  File "test_onnx_export.py", line 56, in _onnx_export_quantized
    _export_to_onnx(model=quantized_model, x=self.x)
  File "test_onnx_export.py", line 143, in _export_to_onnx
    torch.onnx.export(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 516, in export
    _export(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1596, in _export
    graph, params_dict, torch_out = _model_to_graph(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1135, in _model_to_graph
    graph, params, torch_out, module = _create_jit_graph(model, args)
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1011, in _create_jit_graph
    graph, torch_out = _trace_and_get_graph_from_model(model, args)
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 907, in _trace_and_get_graph_from_model
    orig_state_dict_keys = torch.jit._unique_state_dict(model).keys()
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/jit/_trace.py", line 76, in _unique_state_dict
    filtered_dict[k] = v.detach()
AttributeError: __torch__.torch.classes.quantized.Conv2dPackedParamsBase (of Python compilation unit at: 0) does not have a field with name 'detach'

======================================================================
ERROR: test_linear_quantized (__main__.TestOnnxExportLinear)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_onnx_export.py", line 79, in test_linear_quantized
    self._onnx_export_quantized()
  File "test_onnx_export.py", line 56, in _onnx_export_quantized
    _export_to_onnx(model=quantized_model, x=self.x)
  File "test_onnx_export.py", line 143, in _export_to_onnx
    torch.onnx.export(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 516, in export
    _export(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1596, in _export
    graph, params_dict, torch_out = _model_to_graph(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1135, in _model_to_graph
    graph, params, torch_out, module = _create_jit_graph(model, args)
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1011, in _create_jit_graph
    graph, torch_out = _trace_and_get_graph_from_model(model, args)
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 907, in _trace_and_get_graph_from_model
    orig_state_dict_keys = torch.jit._unique_state_dict(model).keys()
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/jit/_trace.py", line 76, in _unique_state_dict
    filtered_dict[k] = v.detach()
AttributeError: __torch__.torch.classes.quantized.LinearPackedParamsBase (of Python compilation unit at: 0) does not have a field with name 'detach'

======================================================================
ERROR: test_linear_relu_quantized (__main__.TestOnnxExportLinearRelu)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_onnx_export.py", line 94, in test_linear_relu_quantized
    self._onnx_export_quantized()
  File "test_onnx_export.py", line 56, in _onnx_export_quantized
    _export_to_onnx(model=quantized_model, x=self.x)
  File "test_onnx_export.py", line 143, in _export_to_onnx
    torch.onnx.export(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 516, in export
    _export(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1596, in _export
    graph, params_dict, torch_out = _model_to_graph(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1139, in _model_to_graph
    graph = _optimize_graph(
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 677, in _optimize_graph
    graph = _C._jit_pass_onnx(graph, operator_export_type)
  File "/home/andrew/.local/lib/python3.8/site-packages/torch/onnx/utils.py", line 1950, in _run_symbolic_function
    raise errors.UnsupportedOperatorError(
torch.onnx.errors.UnsupportedOperatorError: Exporting the operator 'quantized::linear_relu' to ONNX opset version 17 is not supported. Please feel free to request support or submit a pull request on PyTorch GitHub: https://github.com/pytorch/pytorch/issues.

----------------------------------------------------------------------
Ran 8 tests in 1.213s

FAILED (errors=3)
```

Wrapping the single-layer models inside an `nn.Sequential` module works around most of the errors, as you can see by running the same test like this:

```
$ WRAP_WITH_SEQUENTIAL=1 SKIP_LINEAR_RELU_TEST=1 python3 test_onnx_export.py 
.......s
----------------------------------------------------------------------
Ran 8 tests in 1.216s

OK (skipped=1)
```

Here is the test code:
```python
"""Implements tests of PyTorch's ONNX export of simple quantized models.

Environment variables:

    WRAP_WITH_SEQUENTIAL(int): wrap single layer models with nn.Sequential.
        This works around a BUG with torch.onnx.export that otherwise causes
        single-layer model export to fail.

    SKIP_LINEAR_RELU_TEST(int): skip the test for the quantized linear->relu model.

    USE_DYNAMO_EXPORT(int): use torch.onnx.dynamo_export instead of
        torch.onnx.export In PyTorch 2.1, torch.onnx.dynamo_export support for
        quantized models has many errors.

"""
import unittest
from functools import partial
import os
from tempfile import NamedTemporaryFile

import torch
import torch.nn as nn
from torch.ao.quantization.quantize_fx import prepare_fx, convert_fx, fuse_fx


def _get_env_flag(name, default=0) -> bool:
    """Return the given environment variable name converted to a boolean flag"""
    return int(os.environ.get(name, default)) != 0


WRAP_WITH_SEQUENTIAL = _get_env_flag("WRAP_WITH_SEQUENTIAL")
SKIP_LINEAR_RELU_TEST = _get_env_flag("SKIP_LINEAR_RELU_TEST")
USE_DYNAMO_EXPORT = _get_env_flag("USE_DYNAMO_EXPORT")


class _BaseTest(unittest.TestCase):
    CHS_IN = 32
    CHS_OUT = 32
    HEIGHT = 8
    WIDTH = 16
    BATCH_SIZE = 4
    KERNELS_SIZE = 3
    PADDING = 1

    def _onnx_export(self):
        """Test ONNX export."""
        _export_to_onnx(model=self.model, x=self.x)

    def _onnx_export_quantized(self):
        """Test ONNX export of a quantized model."""
        corpus = _get_random_corpus(self.x)
        batch_size = self.x.shape[0]
        quantized_model = _static_quantize_model(
            model=self.model, corpus=corpus, batch_size=batch_size
        )
        _export_to_onnx(model=quantized_model, x=self.x)

    def _wrap(self, model):
        """A bug in torch.onnx.export causes single layer models to fail export.

        Wrapping the layer with nn.Sequential makes onnx export work.
        """
        if WRAP_WITH_SEQUENTIAL:
            model = nn.Sequential(model)
        return model


class TestOnnxExportLinear(_BaseTest):
    """Test cases for exporting a linear layer."""

    def setUp(self):
        self.model = self._wrap(nn.Linear(self.CHS_IN, self.CHS_OUT))
        self.x = torch.rand(self.BATCH_SIZE, self.CHS_IN)

    def test_linear(self):
        self._onnx_export()

    def test_linear_quantized(self):
        self._onnx_export_quantized()


class TestOnnxExportLinearRelu(_BaseTest):
    """Test cases for exporting a linear layer followed by ReLU."""

    def setUp(self):
        self.model = nn.Sequential(nn.Linear(self.CHS_IN, self.CHS_OUT), nn.ReLU())
        self.x = torch.rand(self.BATCH_SIZE, self.CHS_IN)

    def test_linear_relu(self):
        self._onnx_export()

    @unittest.skipIf(SKIP_LINEAR_RELU_TEST, "quantized::linear_relu not supported")
    def test_linear_relu_quantized(self):
        self._onnx_export_quantized()


class TestOnnxExportConv2d(_BaseTest):
    """Test cases for exporting a conv2d layer."""

    def setUp(self):
        self.model = self._wrap(
            nn.Conv2d(
                self.CHS_IN, self.CHS_OUT, self.KERNELS_SIZE, padding=self.PADDING
            )
        )
        self.x = torch.rand(self.BATCH_SIZE, self.CHS_IN, self.HEIGHT, self.WIDTH)

    def test_conv2d(self):
        self._onnx_export()

    def test_conv2d_quantized(self):
        self._onnx_export_quantized()


class TestOnnxExportConv2dRelu(_BaseTest):
    """Test cases for exporting a conv2d layer followed by ReLU."""

    def setUp(self):
        """Setup the model and dummy input."""
        self.model = nn.Sequential(
            nn.Conv2d(
                self.CHS_IN, self.CHS_OUT, self.KERNELS_SIZE, padding=self.PADDING
            ),
            nn.ReLU(),
        )
        self.x = torch.rand(self.BATCH_SIZE, self.CHS_IN, self.HEIGHT, self.WIDTH)

    def test_conv2d_relu(self):
        self._onnx_export()

    def test_conv2d_relu_quantized(self):
        self._onnx_export_quantized()


def _export_to_onnx(model=None, x=None, input_names=["input"], output_names=["output"]):
    """Exports a model to a temporary ONNX file."""
    model.eval()
    with NamedTemporaryFile() as f:
        if USE_DYNAMO_EXPORT:
            onnx_program = torch.onnx.dynamo_export(model, x)
            onnx_program.save(f.name)
        else:
            torch.onnx.export(
                model,
                x,
                f.name,
                export_params=True,
                input_names=input_names,
                output_names=output_names,
            )


def _get_random_corpus(dummy_input, corpus_size=64):
    """Returns a random tensor representing a quantization corpus."""
    batch_size, *input_shape = dummy_input.shape
    corpus_shape = (corpus_size, *input_shape)
    return torch.rand(*corpus_shape)


def _static_quantize_model(model=None, corpus=None, batch_size=None):
    """Returns a model created from static quantization of the given model.

    Applies post-training static quantization, using per-channel symmetric
    quantization for weights and per-tensor affine quantization of activations.
    """
    activations_observer = partial(
        torch.ao.quantization.observer.HistogramObserver,
        qscheme=torch.per_tensor_affine,
        dtype=torch.quint8,
    )

    weights_observer = partial(
        torch.ao.quantization.observer.PerChannelMinMaxObserver,
        qscheme=torch.per_channel_symmetric,
        dtype=torch.qint8,
    )

    my_qconfig = torch.ao.quantization.QConfig(
        activation=activations_observer, weight=weights_observer
    )

    qconfig_mapping = torch.ao.quantization.QConfigMapping().set_global(my_qconfig)

    dataset = torch.utils.data.TensorDataset(corpus)
    data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size)

    model.eval()

    first_input = (next(iter(data_loader))[0],)

    prepared_model = prepare_fx(model, qconfig_mapping, first_input)

    _calibrate(prepared_model, data_loader)
    quantized_model = convert_fx(prepared_model)
    return quantized_model


def _calibrate(model, data_loader):
    """Runs all inputs in the data-loader through the model.

    This function can be used to calibrate static quantization parameters.
    """
    with torch.no_grad():
        for (x,) in data_loader:
            model(x)


if __name__ == "__main__":
    unittest.main()
```

### Versions

Collecting environment information...
PyTorch version: 2.1.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.25.0
Libc version: glibc-2.31

Python version: 3.8.10 (default, May 26 2023, 14:05:08)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-156-generic-x86_64-with-glibc2.29
Is CUDA available: True
CUDA runtime version: 11.7.64
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA RTX A5000
GPU 1: Quadro RTX 6000

Nvidia driver version: 515.86.01
cuDNN version: Probably one of the following:
/usr/local/cuda-10.1/targets/x86_64-linux/lib/libcudnn.so.7.6.5
/usr/local/cuda-10.2/targets/x86_64-linux/lib/libcudnn.so.7.6.5
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          32
On-line CPU(s) list:             0-31
Thread(s) per core:              2
Core(s) per socket:              16
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Silver 4216 CPU @ 2.10GHz
Stepping:                        7
CPU MHz:                         997.383
CPU max MHz:                     3200.0000
CPU min MHz:                     800.0000
BogoMIPS:                        4200.00
Virtualization:                  VT-x
L1d cache:                       512 KiB
L1i cache:                       512 KiB
L2 cache:                        16 MiB
L3 cache:                        22 MiB
NUMA node0 CPU(s):               0-31
Vulnerability Itlb multihit:     KVM: Mitigation: Split huge pages
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Mitigation; Enhanced IBRS
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; TSX disabled
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.1
[pip3] onnx==1.14.1
[pip3] onnxruntime-gpu==1.13.1
[pip3] onnxscript==0.1.0.dev20231106
[pip3] pytorch-jacinto-ai==1.0.0
[pip3] pytorch-triton==2.0.0+0d7e753227
[pip3] torch==2.1.0+cu118
[pip3] torchaudio==2.1.0+cu118
[pip3] torchmetrics==1.0.0
[pip3] torchvision==0.16.0+cu118
[pip3] triton==2.1.0
[conda] Could not collect


cc @jerryzh168 @jianyuh @raghuramank100 @jamesr66a @vkuzo @jgong5 @Xia-Weiwen @leslie-fang-intel