pytorch / pytorch

Tensors and Dynamic neural networks in Python with strong GPU acceleration
https://pytorch.org
Other
83.16k stars 22.43k forks source link

RuntimeError: Unsupported qscheme: per_channel_affine. When using quantise_fx( #125004

Open HaoyuLiu12 opened 5 months ago

HaoyuLiu12 commented 5 months ago

🐛 Describe the bug

Apply Quantization Aware Training (QAT) to a model using PyTorch's torch.ao.quantization module. After preparing the model for QAT and running the simplified training loop, it attempts to finalize the quantization process with the convert_fx function. However, a RuntimeError is raised: RuntimeError: Unsupported qscheme: per_channel_affine

Here's a snippet of the code that leads to the error

import torch
import torch.nn as nn
import torch.optim as optim
from torch.ao.quantization import get_default_qat_qconfig_mapping
from torch.ao.quantization.quantize_fx import prepare_qat_fx, convert_fx
import timm
from tqdm import tqdm

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = timm.create_model('efficientnet_b0', pretrained=True, num_classes=5).to(device)
qat_config = get_default_qat_qconfig_mapping("x86")
sample_input = torch.rand((1, 3, 224, 224)).to(device)
model.train()
prepared_model = prepare_qat_fx(model, qat_config, sample_input)

def train_model_with_qat(prepared_model, iterations=10, batch_size=32, device='cpu'):
    optimizer = optim.SGD(prepared_model.parameters(), lr=0.001, momentum=0.9)
    loss_function = nn.CrossEntropyLoss()
    prepared_model.train()
    for _ in tqdm(range(iterations), desc="Training Iterations"):
        inputs = torch.rand((batch_size, 3, 224, 224)).to(device)
        labels = torch.randint(0, 5, (batch_size,)).to(device)
        optimizer.zero_grad()
        outputs = prepared_model(inputs)
        loss = loss_function(outputs, labels)
        loss.backward()
        optimizer.step()

train_model_with_qat(prepared_model, device=device)
finalized_model = convert_fx(prepared_model)

Versions

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 Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 144 On-line CPU(s) list: 0-143 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8352V CPU @ 2.10GHz CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 36 Socket(s): 2 Stepping: 6 CPU max MHz: 3500.0000 CPU min MHz: 800.0000 BogoMIPS: 4200.00 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 invpcid_single 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 rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 3.4 MiB (72 instances) L1i cache: 2.3 MiB (72 instances) L2 cache: 90 MiB (72 instances) L3 cache: 108 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-35,72-107 NUMA node1 CPU(s): 36-71,108-143 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Retbleed: Not affected 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: Not affected

Versions of relevant libraries: [pip3] numpy==1.23.5 [pip3] torch==2.3.0 [pip3] triton==2.3.0 [conda] numpy 1.23.5 pypi_0 pypi [conda] torch 2.3.0 pypi_0 pypi [conda] triton 2.3.0 pypi_0 pypi

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

Xia-Weiwen commented 5 months ago

Hi @HaoyuLiu12 I could not reproduce the issue in my cpu-only environment (Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz). Can you please remove the CUDA part in your code and try again? Besides, looks like the versions info you provided is incomplete. Please download https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py and run it then update the info above. Thanks.

HaoyuLiu12 commented 5 months ago

Hi @HaoyuLiu12 I could not reproduce the issue in my cpu-only environment (Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz). Can you please remove the CUDA part in your code and try again? Besides, looks like the versions info you provided is incomplete. Please download https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py and run it then update the info above. Thanks.

Hi Weiwen, the issue seems to be solved when I remove the CUDA part and I am confused that why that RuntimeError is raised? Collecting environment information...
PyTorch version: 2.3.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: Could not collect
Clang version: Could not collect
CMake version: version 3.26.4
Libc version: glibc-2.35

Python version: 3.10.14 (main, Mar 21 2024, 16:24:04) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.4.0-170-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090
Nvidia driver version: 535.154.05
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 Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 144 On-line CPU(s) list: 0-143 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8352V CPU @ 2.10GHz CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 36 Socket(s): 2 Stepping: 6 CPU max MHz: 3500.0000 CPU min MHz: 800.0000 BogoMIPS: 4200.00 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 invpcid_single 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 rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 3.4 MiB (72 instances) L1i cache: 2.3 MiB (72 instances) L2 cache: 90 MiB (72 instances) L3 cache: 108 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-35,72-107 NUMA node1 CPU(s): 36-71,108-143 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Retbleed: Not affected 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: Not affected

Versions of relevant libraries: [pip3] numpy==1.23.5 [pip3] torch==2.3.0 [pip3] torchvision==0.18.0 [pip3] triton==2.3.0 [conda] numpy 1.23.5 pypi_0 pypi [conda] torch 2.3.0 pypi_0 pypi [conda] torchvision 0.18.0 pypi_0 pypi [conda] triton 2.3.0 pypi_0 pypi

Xia-Weiwen commented 5 months ago

@HaoyuLiu12 I don't have an environment with CUDA so I can't experiment with your code. However, you may try to do the training on GPU and move the model to CPU before convert_fx. The QAT path you used and the x86 backend is basically designed for x86 CPU. So, the runtime error you met was probably caused by the device issue.