executorch icon indicating copy to clipboard operation
executorch copied to clipboard

[Qualcomm] Buffer names changed by to_edge break QNN quantization attribute lookup

Open INHA-SW opened this issue 4 weeks ago • 2 comments

Changing only the names of per-channel scale/zero-point buffers from attn_* to self_attn_* makes to_edge_transform_and_lower_to_qnn fail in AnnotateQuantAttrs with:

AssertionError: Expect b_attn_scale to be parameter, buffer, get_attr, or lifted tensor constant

The synthetic A8/W8 graph below contains one linear operation and explicit Q/DQ. It needs no model checkpoint, calibration dataset, custom quantizer or device. The attn_ control lowers; the self_attn_ variant fails. Ordinary to_edge executes with exactly equal output to the source model for both test inputs (one seeded input per variant, the same tensor).

Environment

  • ExecuTorch main 12dac4aa042b66a7229e8d7d3af2bdde8c9f262f
  • Python3.12.3, PyTorch2.14.0+cpu, TorchAO0.18.0, Linux x86_64
  • QAIRT2.51.0.260929 and matched native adapters; target QCM6490/HTP V68
  • Relevant lowering/pass sources are unmodified. The workspace has an unrelated LayerNorm annotator candidate for #24730; this reproduction has no LayerNorm and does not invoke QnnQuantizer.

Reproduction

Configure QNN_SDK_ROOT, the SDK library path and the built ExecuTorch Python/native adapters, then run this script with --out /tmp/qnn-buffer-name-repro (new directory):

"""Synthetic QNN buffer-name regression: no detector, data, or custom quantizer."""
import argparse
import json
import os
from pathlib import Path
import traceback

import torch
import torchao.quantization.pt2e.quantize_pt2e  # Registers Q/DQ operators.
from executorch.exir import to_edge
from executorch.backends.qualcomm.serialization.qc_schema import QcomChipset
from executorch.backends.qualcomm.utils.utils import (
    generate_htp_compiler_spec, generate_qnn_executorch_compiler_spec,
    to_edge_transform_and_lower_to_qnn, qnn_edge_config,
)


class LinearWithQuantizedWeight(torch.nn.Module):
    def __init__(self, prefix):
        super().__init__()
        self.prefix = prefix
        self.register_buffer(prefix + 'scale', torch.full((8,), 0.02))
        self.register_buffer(prefix + 'zero_point', torch.zeros(8, dtype=torch.int64))
        self.register_buffer('weight', torch.randint(-100, 100, (8, 16), dtype=torch.int8))

    def forward(self, x):
        x = torch.ops.quantized_decomposed.quantize_per_tensor.default(x, 0.02, 128, 0, 255, torch.uint8)
        x = torch.ops.quantized_decomposed.dequantize_per_tensor.default(x, 0.02, 128, 0, 255, torch.uint8)
        weight = torch.ops.quantized_decomposed.dequantize_per_channel.default(
            self.weight, getattr(self, self.prefix + 'scale'),
            getattr(self, self.prefix + 'zero_point'), 0, -127, 127, torch.int8,
        )
        y = torch.nn.functional.linear(x, weight)
        y = torch.ops.quantized_decomposed.quantize_per_tensor.default(y, 0.1, 128, 0, 255, torch.uint8)
        return torch.ops.quantized_decomposed.dequantize_per_tensor.default(y, 0.1, 128, 0, 255, torch.uint8)


def main():
    p = argparse.ArgumentParser(); p.add_argument('--out', type=Path, required=True)
    a = p.parse_args(); a.out.mkdir(parents=True, exist_ok=False)
    torch.manual_seed(20261106)
    report = {'torch': torch.__version__, 'sdk': os.environ['QNN_SDK_ROOT'],
              'scope': __doc__, 'cases': []}
    inputs = (torch.randn(1, 16),)
    specs = generate_qnn_executorch_compiler_spec(soc_model=QcomChipset.QCM6490,
        backend_options=generate_htp_compiler_spec(use_fp16=False))
    for prefix in ['attn_', 'self_attn_']:
        torch.manual_seed(20261106)
        model = LinearWithQuantizedWeight(prefix).eval()
        row = {'prefix': prefix}; report['cases'].append(row)
        try:
            ep = torch.export.export(model, inputs, strict=True)
            row['export_buffers'] = dict(ep.graph_signature.inputs_to_buffers)
            edge = to_edge(ep, compile_config=qnn_edge_config()).exported_program()
            row['edge_buffers'] = dict(edge.graph_signature.inputs_to_buffers)
            row['edge_fp_exact'] = bool(torch.equal(model(*inputs), edge.module()(*inputs)))
            to_edge_transform_and_lower_to_qnn(model, inputs, specs)
            row['status'] = 'lowered'
        except Exception as exc:
            row.update(status='failed', error=repr(exc), traceback=traceback.format_exc())
    (a.out / 'summary.json').write_text(json.dumps(report, indent=2) + '\n')
    print(json.dumps(report, indent=2))


if __name__ == '__main__':
    main()

Observed results: attn_: lowered, edge_fp_exact=true; self_attn_: assertion above, edge_fp_exact=true.

Signature evidence and suspected cause

For the failing variant, ordinary to_edge consistently updates its own signature:

before: b_self_attn_scale -> self_attn_scale
after:  b_attn_scale      -> self_attn_scale

However, when entering AnnotateQuantAttrs through the QNN helper, the current graph uses the renamed b_attn_scale while self.edge_program.graph_signature still contains b_self_attn_scale. get_quant_attrs asks get_parameter to resolve a current-graph node against this saved pre-edge program.

This suggests the QNN passes need the current ExportedProgram/signature after edge conversion. I have not validated a general patch; guessing aliases in get_parameter could resolve the wrong buffer when names collide.

The failure was originally found while reducing an RF-DETR Nano export. A separate 32-dimension/4-head MultiheadAttention reduction reproduces it with default W8A8 and V68-compatible A16 operand annotations: q=k=v controls lower, whereas q/k position-offset variants after TorchAO export constant folding fail at the same lookup. The standalone linear case above removes those dependencies. This report is distinct from the LayerNorm architecture check in #24730 and makes no claim about full-detector accuracy or runtime correctness.

Prepared with assistance from OpenAI Codex; both synthetic variants were executed.

cc @cbilgin @psiddh

INHA-SW avatar Nov 06 '26 14:11 INHA-SW

@INHA-SW were this issue and #24730 resolved?

nil-is-all avatar Nov 09 '26 21:11 nil-is-all

Sorry for the late reply. An AI agent posted this and #24730 before I had reviewed them, so I closed both. The reviewed reports are #25198 and #25200. Thanks for checking!

INHA-SW avatar Nov 18 '26 08:11 INHA-SW