Repository: pytorch
Issue: qnnpack quantized model can not be traced
Labels: oncall: jit,oncall: quantization,low priority,triaged

### 🐛 Describe the bug

Hi, quantization team guys

QAT config of qnnpack backend can be converted to quantized model successfuly, but can not be traced using torch.jit.trace. The error seems to be introduced by xnnpack.

code:
```
import torch 
from torch.ao.quantization.qconfig_mapping import QConfigMapping
from torch.ao.quantization.backend_config.qnnpack import get_qnnpack_backend_config
from torch.ao.quantization.qconfig import default_symmetric_qnnpack_qat_qconfig
# from torch.ao.quantization.backend_config.x86 import get_x86_backend_config
# from torch.ao.quantization.qconfig import get_default_qat_qconfig
from torch.ao.quantization.quantize_fx import prepare_qat_fx
from torch.ao.quantization.quantize_fx import convert_fx
import torch.nn as nn

class Net(nn.Module):
    def __init__(self, ):
        super().__init__()
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=1, padding=0, stride=1, groups=1,bias=True)
        self.conv2 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=1, padding=0, stride=1, groups=1,bias=True)
        self.beta = nn.Parameter(torch.zeros((1, 3, 1, 1)), requires_grad=True)

    def forward(self, inp):
        x_1 = self.conv1(inp)
        x_2 = self.conv2(inp)
        x = x_1 * x_2
        y = inp + x * self.beta #error is introduced by this line.
        return y


if __name__=='__main__':
    torch.manual_seed(3)
    print('The default quantized engine is {}:'.format(torch.backends.quantized.engine))
    torch.backends.quantized.engine='qnnpack'
    print('After change the quantization backend,The default quantized engine is {}:'.format(torch.backends.quantized.engine))
    
    net=Net()
    backend_config=get_qnnpack_backend_config()
    qconfig=default_symmetric_qnnpack_qat_qconfig 
    # backend_config=get_x86_backend_config()
    # qconfig=get_default_qat_qconfig() 
    qconfig_mapping = QConfigMapping().set_global(qconfig)

    net.train()
    net_prepare=prepare_qat_fx(net,qconfig_mapping,torch.randn(1,3,10,10),backend_config=backend_config)
    net_prepare(torch.randn(1,3,10,10))
    net_prepare(torch.randn(1,3,10,10))
    net_converted=convert_fx(net_prepare,qconfig_mapping=qconfig_mapping,backend_config=backend_config)
    print('net_converted:')
    print(net_converted)
    net_converted_traced=torch.jit.trace(net_converted,torch.randn(1,3,10,10))
    torch.jit.save(net_converted_traced,'net_converted_traced.pth')
    
```
result:
```
The default quantized engine is x86:
After change the quantization backend,The default quantized engine is qnnpack:
net_converted:
GraphModule(
  (conv1): QuantizedConv2d(3, 3, kernel_size=(1, 1), stride=(1, 1), scale=0.0169826652854681, zero_point=0)
  (conv2): QuantizedConv2d(3, 3, kernel_size=(1, 1), stride=(1, 1), scale=0.01659565418958664, zero_point=0)
)



def forward(self, inp):
    conv1_input_scale_0 = self.conv1_input_scale_0
    conv1_input_zero_point_0 = self.conv1_input_zero_point_0
    quantize_per_tensor = torch.quantize_per_tensor(inp, conv1_input_scale_0, conv1_input_zero_point_0, torch.qint8);  inp = conv1_input_scale_0 = conv1_input_zero_point_0 = None
    conv1 = self.conv1(quantize_per_tensor)
    conv2 = self.conv2(quantize_per_tensor)
    _scale_0 = self._scale_0
    _zero_point_0 = self._zero_point_0
    mul_2 = torch.ops.quantized.mul(conv1, conv2, _scale_0, _zero_point_0);  conv1 = conv2 = _scale_0 = _zero_point_0 = None
    beta = self.beta
    _scale_1 = self._scale_1
    _zero_point_1 = self._zero_point_1
    quantize_per_tensor_4 = torch.quantize_per_tensor(beta, _scale_1, _zero_point_1, torch.qint8);  beta = _scale_1 = _zero_point_1 = None
    _scale_2 = self._scale_2
    _zero_point_2 = self._zero_point_2
    mul_3 = torch.ops.quantized.mul(mul_2, quantize_per_tensor_4, _scale_2, _zero_point_2);  mul_2 = quantize_per_tensor_4 = _scale_2 = _zero_point_2 = None
    _scale_3 = self._scale_3
    _zero_point_3 = self._zero_point_3
    add_1 = torch.ops.quantized.add(quantize_per_tensor, mul_3, _scale_3, _zero_point_3);  quantize_per_tensor = mul_3 = _scale_3 = _zero_point_3 = None
    dequantize_6 = add_1.dequantize();  add_1 = None
    return dequantize_6
    
# To see more debug info, please use `graph_module.print_readable()`
Traceback (most recent call last):
    net_converted_traced=torch.jit.trace(net_converted,torch.randn(1,3,10,10))
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/jit/_trace.py", line 794, in trace
    return trace_module(
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/jit/_trace.py", line 1056, in trace_module
    module._c._create_method_from_trace(
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/fx/graph_module.py", line 662, in call_wrapped
    return self._wrapped_call(self, *args, **kwargs)
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/fx/graph_module.py", line 281, in __call__
    raise e
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/fx/graph_module.py", line 271, in __call__
    return super(self.cls, obj).__call__(*args, **kwargs)  # type: ignore[misc]
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1501, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1488, in _slow_forward
    result = self.forward(*input, **kwargs)
  File "<eval_with_key>.6", line 19, in forward
  File "/home/sfadmin/anaconda3/envs/torch2.01/lib/python3.9/site-packages/torch/_ops.py", line 502, in __call__
    return self._op(*args, **kwargs or {})
RuntimeError: xnnp_mul(): xnn setup operator failed(2)!
```

### Versions

Collecting environment information...
PyTorch version: 2.0.1+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.3 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.22.1
Libc version: glibc-2.31

Python version: 3.9.12 (main, Apr  5 2022, 06:56:58)  [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-5.4.0-155-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.3.58
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-PCIE-40GB
  MIG 7g.40gb     Device  0:
GPU 1: NVIDIA A100-PCIE-40GB
  MIG 3g.20gb     Device  0:
  MIG 2g.10gb     Device  1:
  MIG 2g.10gb     Device  2:
GPU 2: NVIDIA A100-PCIE-40GB
  MIG 3g.20gb     Device  0:
  MIG 2g.10gb     Device  1:
  MIG 2g.10gb     Device  2:
GPU 3: NVIDIA A100-PCIE-40GB
  MIG 3g.20gb     Device  0:
  MIG 2g.10gb     Device  1:
  MIG 2g.10gb     Device  2:

Nvidia driver version: 470.82.01
cuDNN version: Could not collect
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):                          96
On-line CPU(s) list:             0-89
Off-line CPU(s) list:            90-95
Thread(s) per core:              1
Core(s) per socket:              24
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Gold 6248R CPU @ 3.00GHz
Stepping:                        7
CPU MHz:                         2811.906
CPU max MHz:                     4000.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        6000.00
Virtualization:                  VT-x
L1d cache:                       768 KiB
L1i cache:                       768 KiB
L2 cache:                        24 MiB
L3 cache:                        35.8 MiB
NUMA node0 CPU(s):               0-23,48-71
NUMA node1 CPU(s):               24-47,72-95
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 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] numpy==1.22.3
[pip3] torch==2.0.1+cu117
[pip3] torch-pruning==1.0.0
[pip3] torch-scatter==2.1.0+pt112cu113
[pip3] torch-tb-profiler==0.4.0
[pip3] torchsummary==1.5.1
[pip3] torchvision==0.15.2
[pip3] torchviz==0.0.2
[pip3] triton==2.0.0
[conda] numpy                     1.22.3                   pypi_0    pypi
[conda] torch                     2.0.1+cu117              pypi_0    pypi
[conda] torch-pruning             1.0.0                    pypi_0    pypi
[conda] torch-scatter             2.1.0+pt112cu113          pypi_0    pypi
[conda] torch-tb-profiler         0.4.0                    pypi_0    pypi
[conda] torchsummary              1.5.1                    pypi_0    pypi
[conda] torchvision               0.15.2                   pypi_0    pypi
[conda] torchviz                  0.0.2                    pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel @jerryzh168 @jianyuh @raghuramank100 @jamesr66a @vkuzo @Xia-Weiwen @leslie-fang-intel