executorch icon indicating copy to clipboard operation
executorch copied to clipboard

Exception: An error occurred when running the 'InsertIOQDQ' pass after the following passes: ['FoldQDQ', 'InsertRequantize']

Open ThreeD-H opened this issue 10 months ago • 10 comments

🐛 Describe the bug

quant_dtype=QuantDtype.use_16a16w,The error report is as follows: Exception: An error occurred when running the 'InsertIOQDQ' pass after the following passes: ['FoldQDQ', 'InsertRequantize'] There won't be any problem as long as 8a8w is used

quantizer = QnnQuantizer()
quantizer.set_default_quant_config(
            quant_dtype=QuantDtype.use_16a16w,
            is_qat=False,
            is_conv_per_channel=False,
            is_linear_per_channel=False
        )
backend_options = generate_htp_compiler_spec(
        use_fp16= False if quantized else True
    )
    # QNN Compiler Spec
    compile_spec = generate_qnn_executorch_compiler_spec(
        soc_model=QcomChipset.SA8295,
        backend_options=backend_options,
    )
    print("Compiling model...")
    # Lower to QNN backend
    delegated_program = to_edge_transform_and_lower_to_qnn(
        quantized_model if quantized else exported_program,
        example_inputs,
        compile_spec,
        skip_mutable_buffer = True
    )

Versions

Collecting environment information... PyTorch version: 2.9.0+cpu Is debug build: False CUDA used to build PyTorch: Could not collect ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04.2) 11.4.0 Clang version: 14.0.0-1ubuntu1.1 CMake version: version 3.31.10 Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 4 2025, 08:48:33) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-6.8.0-90-generic-x86_64-with-glibc2.35 Is CUDA available: False CUDA runtime version: 12.8.61 CUDA_MODULE_LOADING set to: N/A GPU models and configuration: GPU 0: Quadro P4000 Nvidia driver version: 580.95.05 cuDNN version: Could not collect Is XPU available: False HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True Caching allocator config: N/A

CPU: 架构: x86_64 CPU 运行模式: 32-bit, 64-bit Address sizes: 46 bits physical, 48 bits virtual 字节序: Little Endian CPU: 8 在线 CPU 列表: 0-7 厂商 ID: GenuineIntel 型号名称: Intel(R) Xeon(R) Gold 5122 CPU @ 3.60GHz CPU 系列: 6 型号: 85 每个核的线程数: 2 每个座的核数: 4 座: 1 步进: 4 CPU 最大 MHz: 3700.0000 CPU 最小 MHz: 1200.0000 BogoMIPS: 7200.00 标记: 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 pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm 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 hwp hwp_act_window hwp_epp hwp_pkg_req vnmi pku ospke md_clear flush_l1d arch_capabilities ibpb_exit_to_user 虚拟化: VT-x L1d 缓存: 128 KiB (4 instances) L1i 缓存: 128 KiB (4 instances) L2 缓存: 4 MiB (4 instances) L3 缓存: 16.5 MiB (1 instance) NUMA 节点: 1 NUMA 节点0 CPU: 0-7 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Meltdown: Mitigation; PTI Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Mitigation; IBRS Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

Versions of relevant libraries: [pip3] executorch==1.0.1a0+7b220c6 [pip3] numpy==2.2.6 [pip3] nvidia-cublas-cu12==12.8.4.1 [pip3] nvidia-cuda-cupti-cu12==12.8.90 [pip3] nvidia-cuda-nvrtc-cu12==12.8.93 [pip3] nvidia-cuda-runtime-cu12==12.8.90 [pip3] nvidia-cudnn-cu12==9.10.2.21 [pip3] nvidia-cufft-cu12==11.3.3.83 [pip3] nvidia-curand-cu12==10.3.9.90 [pip3] nvidia-cusolver-cu12==11.7.3.90 [pip3] nvidia-cusparse-cu12==12.5.8.93 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-nccl-cu12==2.27.5 [pip3] nvidia-nvjitlink-cu12==12.8.93 [pip3] nvidia-nvtx-cu12==12.8.90 [pip3] pytorch_tokenizers==1.0.1 [pip3] torch==2.9.0+cpu [pip3] torchao==0.14.0+git02941240f [pip3] torchaudio==2.9.1 [pip3] torchdata==0.11.0 [pip3] torchsr==1.0.4 [pip3] torchtune==0.6.1 [pip3] torchvision==0.24.1 [pip3] triton==3.5.1 [conda] No relevant packages

cc @cccclai @winskuo-quic @shewu-quic @haowhsu-quic @DannyYuyang-quic @cbilgin

ThreeD-H avatar Jan 04 '26 07:01 ThreeD-H

There should be stack trace to report the error message for the pass. Can you share it? Or can you share the repro steps

cccclai avatar Jan 04 '26 22:01 cccclai

There should be stack trace to report the error message for the pass. Can you share it? Or can you share the repro steps

This is the log.log.txt

ThreeD-H avatar Jan 05 '26 08:01 ThreeD-H

Hi @ThreeD-H, There seems to be op validation failure when you are lowering 16a16w model. The root cause is that SA8295 does not support 16a16w for some operations, which is why 8a8w lowers successfully. May I know if the accuracy for 8a8w is acceptable for you?

winskuo-quic avatar Jan 05 '26 09:01 winskuo-quic

Hi @ThreeD-H, There seems to be op validation failure when you are lowering 16a16w model. The root cause is that SA8295 does not support 16a16w for some operations, which is why 8a8w lowers successfully. May I know if the accuracy for 8a8w is acceptable for you?

There is a significant loss of accuracy. And if I don't perform quantification and directly export, it fails to run on android。

QnnDsp <E> Skel failed to process context binary.
QnnDsp <E> Context create from binary failed for deviceId 0 coreId 0 pdId 0 for context 1, err 5005
QnnDsp <E> Context 1 failed on pd 0

but 8a8w can run successfully. My complete code is as follows:

class WrappedInternViT(nn.Module):
    def __init__(self, model_path='OpenGVLab/InternViT-300M-448px-V2_5'):
        super(WrappedInternViT, self).__init__()
        self.model = AutoModel.from_pretrained(
            model_path,
            torch_dtype=torch.float32,
            low_cpu_mem_usage=True,
            trust_remote_code=True,
            use_flash_attn=False
        )

    def forward(self, pixel_values: torch.Tensor):
        outputs = self.model(pixel_values)
        return outputs.last_hidden_state

def exportInternVit():
    print("export InternVit model...")
    model = WrappedInternViT().eval()
    example_inputs = (torch.randn(1, 3, 448, 448),)
    exported_program = torch.export.export(model, example_inputs, strict=True).module()
    quantized = False
    if quantized:
        quantizer = QnnQuantizer()
        quantizer.set_default_quant_config(
            quant_dtype=QuantDtype.use_16a16w,
            is_qat=False,
            is_conv_per_channel=False,
            is_linear_per_channel=False
        )
        quantization_type = "ptq"
        training_steps = 10
        if quantization_type == "ptq":
            prepared_model = prepare_pt2e(exported_program, quantizer)
            # Calibration loop would go here
            prepared_model(*example_inputs)
        # QAT (Quantization-Aware Training)
        elif quantization_type == "qat":
            prepared_model = prepare_qat_pt2e(exported_program, quantizer)
            # Training loop would go here
            for _ in range(training_steps):
                prepared_model(*example_inputs)
        print("Converting to quantized model...")
        quantized_model = convert_pt2e(prepared_model)

    backend_options = generate_htp_compiler_spec(
        use_fp16= False,
        # use_weight_sharing = True
    )
    # QNN Compiler Spec
    compile_spec = generate_qnn_executorch_compiler_spec(
        soc_model=QcomChipset.SA8295,
        backend_options=backend_options,
    )
    print("Compiling model...")
    # Lower to QNN backend
    delegated_program = to_edge_transform_and_lower_to_qnn(
        quantized_model if quantized else exported_program,
        example_inputs,
        compile_spec,
        skip_mutable_buffer = True
    )
    # Export to ExecuTorch format
    executorch_program = delegated_program.to_executorch()
    # Save the compiled model
    model_name = "intern_vit.pte"
    with open(model_name, "wb") as f:
        f.write(executorch_program.buffer)
    print(f"Model successfully exported to {model_name}")

ThreeD-H avatar Jan 05 '26 09:01 ThreeD-H

@ThreeD-H, Thanks for sharing the complete code. Could you also try 16a8w and see if it works? Thanks

winskuo-quic avatar Jan 05 '26 10:01 winskuo-quic

@ThreeD-H, Thanks for sharing the complete code. Could you also try 16a8w and see if it works? Thanks

The 16a8w also reported an error, as recorded in the log.

16a8w_log.txt

Exception: An error occurred when running the 'InsertIOQDQ' pass after the following passes: ['FoldQDQ', 'InsertRequantize']

8a8w success log.

8a8w_log.txt

ThreeD-H avatar Jan 06 '26 01:01 ThreeD-H

@ThreeD-H, I think the issue here is that layer_norm and matmul could not be successfully delegated due to the SOC model you are using.

Image

For this reason, we might need to perform some custom annotation. For example, we will need to annotate 2nd input of matmul as 8a8w.

Could you save the exported model as a .pt2 file and share it with us? We will take a look and see how we can further improve the accuracy of this model by providing a patch. To save a .pt2 file, just do: captured_model = torch.export.export(model, inputs, strict=False) torch.export.save(captured_model, "my_model.pt2")

winskuo-quic avatar Jan 06 '26 09:01 winskuo-quic

@ThreeD-H, I think the issue here is that layer_norm and matmul could not be successfully delegated due to the SOC model you are using.

Image For this reason, we might need to perform some custom annotation. For example, we will need to annotate 2nd input of matmul as 8a8w.

Could you save the exported model as a .pt2 file and share it with us? We will take a look and see how we can further improve the accuracy of this model by providing a patch. To save a .pt2 file, just do: captured_model = torch.export.export(model, inputs, strict=False) torch.export.save(captured_model, "my_model.pt2")

The model file is in the following repository

https://github.com/ThreeD-H/ExecuTorch.git

I have uploaded the model. Thanks

ThreeD-H avatar Jan 07 '26 06:01 ThreeD-H

Could you try to lower the model again with 16a8w and this custom annotation? I have tried this and get cosine similarity ~96% compared to nn.Module.

quantizer = make_quantizer(quant_dtype=QuantDtype.use_16a8w,) quantizer.add_custom_quant_annotations((annotate_intern_vit,))

The formats here are a little off. I don't know why function name can't be properly displayed. Be aware and please copy the 1st line below (def annotate_intern_vit(gm: torch.fx.GraphModule):).

`def annotate_intern_vit(gm: torch.fx.GraphModule):

from torchao.quantization.pt2e import MovingAverageMinMaxObserver
quantization_config16a8w = get_16a8w_qnn_ptq_config()
for node in gm.graph.nodes:
    if node.target == torch.ops.aten.matmul.default:
        input_qspec_map = {}
        input_act = node.args[0]
        input_spec = quantization_config16a8w.input_activation
        input_qspec_map[input_act] = input_spec
        input_act1 = node.args[1]
        input_spec1 = quantization_config16a8w.weight
        input_qspec_map[input_act1] = input_spec1
        node.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation(
            input_qspec_map=input_qspec_map,
            output_qspec=quantization_config16a8w.output_activation,
            _annotated=True,
        )
    if node.target == torch.ops.aten.layer_norm.default:
        input_qspec_map = {}
        input_act = node.args[0]
        input_spec = quantization_config16a8w.input_activation
        input_qspec_map[input_act] = input_spec
        input_act1 = node.args[2]
        input_qspec_map[input_act1] = quantization_config16a8w.weight
        # bias node
        if len(node.args) > 3:
            bias_node = node.args[3]
            input_qspec_map[bias_node] = quantization_config16a8w.bias
        node.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation(
            input_qspec_map=input_qspec_map,
            output_qspec=quantization_config16a8w.output_activation,
            _annotated=True,
        )`

winskuo-quic avatar Jan 07 '26 10:01 winskuo-quic

Could you try to lower the model again with 16a8w and this custom annotation? I have tried this and get cosine similarity ~96% compared to nn.Module.

quantizer = make_quantizer(quant_dtype=QuantDtype.use_16a8w,) quantizer.add_custom_quant_annotations((annotate_intern_vit,))

The formats here are a little off. I don't know why function name can't be properly displayed. Be aware and please copy the 1st line below (def annotate_intern_vit(gm: torch.fx.GraphModule):).

`def annotate_intern_vit(gm: torch.fx.GraphModule):

from torchao.quantization.pt2e import MovingAverageMinMaxObserver
quantization_config16a8w = get_16a8w_qnn_ptq_config()
for node in gm.graph.nodes:
    if node.target == torch.ops.aten.matmul.default:
        input_qspec_map = {}
        input_act = node.args[0]
        input_spec = quantization_config16a8w.input_activation
        input_qspec_map[input_act] = input_spec
        input_act1 = node.args[1]
        input_spec1 = quantization_config16a8w.weight
        input_qspec_map[input_act1] = input_spec1
        node.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation(
            input_qspec_map=input_qspec_map,
            output_qspec=quantization_config16a8w.output_activation,
            _annotated=True,
        )
    if node.target == torch.ops.aten.layer_norm.default:
        input_qspec_map = {}
        input_act = node.args[0]
        input_spec = quantization_config16a8w.input_activation
        input_qspec_map[input_act] = input_spec
        input_act1 = node.args[2]
        input_qspec_map[input_act1] = quantization_config16a8w.weight
        # bias node
        if len(node.args) > 3:
            bias_node = node.args[3]
            input_qspec_map[bias_node] = quantization_config16a8w.bias
        node.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation(
            input_qspec_map=input_qspec_map,
            output_qspec=quantization_config16a8w.output_activation,
            _annotated=True,
        )`

I can successfully export using your method. Thanks

ThreeD-H avatar Jan 09 '26 01:01 ThreeD-H