|
| 1 | +# Copyright (c) Qualcomm Innovation Center, Inc. |
| 2 | +# All rights reserved |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +import logging |
| 8 | +from dataclasses import dataclass |
| 9 | +from typing import Callable, Dict, Optional, Union |
| 10 | + |
| 11 | +import torch |
| 12 | +from executorch.backends.qualcomm.quantizer.rules import _is_float_tensor |
| 13 | +from torchao.quantization.pt2e.quantizer import ( |
| 14 | + QuantizationAnnotation, |
| 15 | + QuantizationSpec, |
| 16 | + SharedQuantizationSpec, |
| 17 | +) |
| 18 | +from torchao.quantization.pt2e.quantizer.quantizer import Q_ANNOTATION_KEY |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class IOQuantConfig: |
| 25 | + """ |
| 26 | + Quantization config for custom op inputs and outputs. |
| 27 | +
|
| 28 | + Attributes: |
| 29 | + input_quant_specs: Maps input index to its QuantizationSpec. |
| 30 | + Only indices present in the dict are annotated. If None, no inputs |
| 31 | + are annotated. |
| 32 | + output_quant_specs: Maps output index to its QuantizationSpec. |
| 33 | + For single-output ops annotation is done on the op node. For multi-output ops, |
| 34 | + each index corresponds to a downstream getitem user. If None, no |
| 35 | + outputs are annotated. |
| 36 | + """ |
| 37 | + |
| 38 | + input_quant_specs: Optional[ |
| 39 | + Dict[int, Union[QuantizationSpec, SharedQuantizationSpec]] |
| 40 | + ] = None |
| 41 | + output_quant_specs: Optional[ |
| 42 | + Dict[int, Union[QuantizationSpec, SharedQuantizationSpec]] |
| 43 | + ] = None |
| 44 | + |
| 45 | + |
| 46 | +class CustomOpsQuantAnnotator: |
| 47 | + """ |
| 48 | + Holds op IOQuantConfigs and builds a single annotation function |
| 49 | + compatible with make_quantizer(custom_annotations=...). |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__(self): |
| 53 | + self._registry: Dict = {} # {op_target: IOQuantConfig} |
| 54 | + |
| 55 | + def register_annotation( |
| 56 | + self, |
| 57 | + op_target, |
| 58 | + io_quant_config: IOQuantConfig, |
| 59 | + ) -> "CustomOpsQuantAnnotator": |
| 60 | + """ |
| 61 | + Register quantization config for custom op. |
| 62 | +
|
| 63 | + Args: |
| 64 | + op_target: The torch op target (e.g. torch.ops.my_ops.custom_op.default). |
| 65 | + io_quant_config: IOQuantConfig specifying how to quantize inputs and outputs. |
| 66 | +
|
| 67 | + Returns self for method chaining. |
| 68 | + """ |
| 69 | + self._registry[op_target] = io_quant_config |
| 70 | + return self |
| 71 | + |
| 72 | + def build_annotation_fn(self) -> Callable[[torch.fx.GraphModule], None]: |
| 73 | + """ |
| 74 | + Build and return an annotation function for all registered ops. |
| 75 | +
|
| 76 | + The returned function has signature (gm: GraphModule) -> None and |
| 77 | + can be passed directly to make_quantizer(custom_annotations=(fn,)). |
| 78 | + """ |
| 79 | + registry = dict(self._registry) |
| 80 | + |
| 81 | + def annotate_custom_ops(gm: torch.fx.GraphModule) -> None: |
| 82 | + for node in gm.graph.nodes: |
| 83 | + if node.target not in registry: |
| 84 | + continue |
| 85 | + |
| 86 | + cfg = registry[node.target] |
| 87 | + input_qspec_map = {} |
| 88 | + if cfg.input_quant_specs is not None: |
| 89 | + for arg_idx, spec in cfg.input_quant_specs.items(): |
| 90 | + if arg_idx >= len(node.args): |
| 91 | + raise ValueError( |
| 92 | + f"IOQuantConfig error for '{node.name}' ({node.target}): " |
| 93 | + f"input_quant_specs index {arg_idx} is out of range " |
| 94 | + f"(op has {len(node.args)} args)" |
| 95 | + ) |
| 96 | + if not _is_float_tensor(node.args[arg_idx]): |
| 97 | + logger.debug( |
| 98 | + f"Skipping quantization of input {arg_idx} for " |
| 99 | + f"'{node.name}' ({node.target}): expected a float tensor." |
| 100 | + ) |
| 101 | + continue |
| 102 | + logger.debug( |
| 103 | + f"Annotating input {arg_idx} of '{node.name}' ({node.target}) " |
| 104 | + f"with {spec}" |
| 105 | + ) |
| 106 | + input_qspec_map[node.args[arg_idx]] = spec |
| 107 | + |
| 108 | + if not cfg.output_quant_specs or len(cfg.output_quant_specs) <= 1: |
| 109 | + # Single output — annotate on the op node |
| 110 | + output_spec = ( |
| 111 | + cfg.output_quant_specs.get(0) |
| 112 | + if cfg.output_quant_specs |
| 113 | + else None |
| 114 | + ) |
| 115 | + node.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation( |
| 116 | + input_qspec_map=input_qspec_map, |
| 117 | + output_qspec=output_spec, |
| 118 | + _annotated=True, |
| 119 | + ) |
| 120 | + else: |
| 121 | + # Tuple output — push quantization down to getitem users |
| 122 | + node.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation( |
| 123 | + input_qspec_map=input_qspec_map, |
| 124 | + output_qspec=None, |
| 125 | + _annotated=True, |
| 126 | + ) |
| 127 | + for user in node.users: |
| 128 | + output_idx = user.args[1] |
| 129 | + spec = cfg.output_quant_specs.get(output_idx) |
| 130 | + |
| 131 | + if spec is not None: |
| 132 | + user.meta[Q_ANNOTATION_KEY] = QuantizationAnnotation( |
| 133 | + output_qspec=spec, |
| 134 | + _annotated=True, |
| 135 | + ) |
| 136 | + |
| 137 | + return annotate_custom_ops |
0 commit comments