|
| 1 | +# Copyright 2024 Arm Limited and/or its affiliates. |
| 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 copy |
| 8 | + |
| 9 | +from typing import cast, Iterable |
| 10 | + |
| 11 | +from executorch.backends.arm.tosa_quant_utils import QuantArgs |
| 12 | + |
| 13 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 14 | +from executorch.exir.dialects.edge._ops import EdgeOpOverload |
| 15 | + |
| 16 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 17 | +from torch.fx import GraphModule, Node |
| 18 | + |
| 19 | +q_op: EdgeOpOverload = exir_ops.edge.quantized_decomposed.quantize_per_tensor.default |
| 20 | +dq_op: EdgeOpOverload = exir_ops.edge.quantized_decomposed.dequantize_per_tensor.default |
| 21 | + |
| 22 | + |
| 23 | +def get_input_qparams(node: Node) -> dict[int, QuantArgs]: |
| 24 | + """ |
| 25 | + Get the input quantization parameters from a node, set by the 'FoldAndAnnotateQParamsPass'. |
| 26 | + Raises a ValueError if the node doesn't have any parameters set. |
| 27 | + """ |
| 28 | + if "input_qparams" not in node.meta.keys(): |
| 29 | + raise ValueError(f"No input quantization parameter found in node {node}") |
| 30 | + input_qparams = cast(dict[int, QuantArgs], node.meta["input_qparams"]) |
| 31 | + if len(input_qparams) == 0: |
| 32 | + raise ValueError(f"No input quantization parameter found in node {node}") |
| 33 | + return input_qparams |
| 34 | + |
| 35 | + |
| 36 | +def get_output_qparams(node: Node) -> dict[int, QuantArgs]: |
| 37 | + """ |
| 38 | + Get the output quantization parameters from a node, set by the 'FoldAndAnnotateQParamsPass'. |
| 39 | + Raises a ValueError if the node doesn't have any parameters set. |
| 40 | + """ |
| 41 | + if "output_qparams" not in node.meta.keys(): |
| 42 | + raise ValueError(f"No output quantization parameter found in node {node}") |
| 43 | + input_qparams = cast(dict[int, QuantArgs], node.meta["output_qparams"]) |
| 44 | + if len(input_qparams) == 0: |
| 45 | + raise ValueError(f"No output quantization parameter found in node {node}") |
| 46 | + return input_qparams |
| 47 | + |
| 48 | + |
| 49 | +class FoldAndAnnotateQParamsPass(ExportPass): |
| 50 | + """ |
| 51 | + A pass that walks the graph and removes any DQ and Q nodes before and after the target |
| 52 | + node in the supplied list of operators. |
| 53 | + The quantization parameters from the DQ/Q nodes are stored as meta values to be |
| 54 | + accessible for later lowering and serialization passes. |
| 55 | + The assumption is that the quantization annotatation adds DQ nodes for all tensor |
| 56 | + inputs to the target one Q node to the output. |
| 57 | +
|
| 58 | + Example ('executorch_exir_dialects_edge__ops_' prefix removed from operators for readability): |
| 59 | +
|
| 60 | + x_q: "i8[5]" = quantized_decomposed_quantize_per_tensor_default(x, 0.05487706884741783, -128, -128, 127, torch.int8) |
| 61 | +
|
| 62 | + x_dq: "f32[5]" = quantized_decomposed_dequantize_per_tensor_default(x_q, 0.05487706884741783, -128, -128, 127, torch.int8) |
| 63 | + aten_add_tensor: "f32[5]" = ops_aten_add_Tensor(x_dq, x_dq) |
| 64 | + aten_add_tensor_q: "i8[5]" = quantized_decomposed_quantize_per_tensor_default(aten_add_tensor, 0.05487706884741783, -128, -128, 127, torch.int8) |
| 65 | +
|
| 66 | + output_dq: "f32[5]" = quantized_decomposed_dequantize_per_tensor_default(aten_add_tensor_q, 0.05487706884741783, -128, -128, 127, torch.int8) |
| 67 | +
|
| 68 | + Becomes: |
| 69 | + x_q: "i8[5]" = quantized_decomposed_quantize_per_tensor_default(x, 0.05487706884741783, -128, -128, 127, torch.int8) |
| 70 | +
|
| 71 | + aten_add_tensor: "i8[5]" = aten_add_Tensor(x_q, x_q) |
| 72 | +
|
| 73 | + output_dq: "f32[5]" = quantized_decomposed_dequantize_per_tensor_default(aten_add_tensor_q, 0.05487706884741783, -128, -128, 127, torch.int8) |
| 74 | +
|
| 75 | + The quantization parameters for x_dq and aten_add_tensor_q are store in meta for the aten_add_tensor node. |
| 76 | +
|
| 77 | + """ |
| 78 | + |
| 79 | + def __init__(self, targeted_ops: Iterable[EdgeOpOverload]) -> None: |
| 80 | + super().__init__() |
| 81 | + self.targeted_ops = targeted_ops |
| 82 | + |
| 83 | + def call(self, graph_module: GraphModule) -> PassResult: |
| 84 | + |
| 85 | + # Loop over the graph nodes and find any node in the 'targeted_ops' list. |
| 86 | + for n in graph_module.graph.nodes: |
| 87 | + n = cast(Node, n) |
| 88 | + if n.op != "call_function" or n.target not in self.targeted_ops: |
| 89 | + continue |
| 90 | + |
| 91 | + # Make sure we haven't already set qparams meta information on the node |
| 92 | + assert "input_qparams" not in n.meta.keys() |
| 93 | + assert "output_qparams" not in n.meta.keys() |
| 94 | + |
| 95 | + # for the inputs and outputs search the graph for quantization info and |
| 96 | + # store the information in a dict with order of the _tensor_ inputs as key, |
| 97 | + # ignoring any other arguments to the target node. |
| 98 | + n.meta["input_qparams"] = {} |
| 99 | + n.meta["output_qparams"] = {} |
| 100 | + for i, arg in enumerate(n.args): |
| 101 | + if not isinstance(arg, Node): |
| 102 | + continue |
| 103 | + |
| 104 | + # Make sure arg has requires_grad set to False |
| 105 | + # For parameters that are not quantized, sometimes (i.e. convolution) |
| 106 | + # the Parameter(FakeTensor(...)) has requires_grad set to True, which |
| 107 | + # causes the retracing of the graph to fail with: |
| 108 | + # |
| 109 | + # E RuntimeError: isDifferentiableType(variable.scalar_type()) INTERNAL ASSERT FAILED at "/Users/runner/work/pytorch/pytorch/pytorch/torch/csrc/autograd/functions/utils.h":74, please report a bug to PyTorch. |
| 110 | + # E |
| 111 | + # E While executing %aten_convolution_default : [num_users=1] = call_function[target=executorch.exir.dialects.edge._ops.aten.convolution.default](args = (%quantized_decomposed_quantize_per_tensor_default, %b__frozen_param0, %p__param_constant1, [1, 1], [0, 0], [1, 1], False, [0, 0], 1), kwargs = {}) |
| 112 | + # E Original traceback: |
| 113 | + # E File "/Users/perast01/src/executorch/backends/arm/test/ops/test_conv2d.py", line 110, in forward |
| 114 | + # E x = conv(x) |
| 115 | + # |
| 116 | + if arg.op == "placeholder": |
| 117 | + arg.meta["val"].requires_grad = False |
| 118 | + |
| 119 | + if arg.target != dq_op: |
| 120 | + continue |
| 121 | + |
| 122 | + # arg.target for argument i is a dequant node, extract the information |
| 123 | + n.meta["input_qparams"][i] = QuantArgs.from_operator( |
| 124 | + arg.target, arg.args |
| 125 | + ) |
| 126 | + |
| 127 | + # arg.args[0] is the tensor input, replace the input usage |
| 128 | + tensor_input = cast(Node, arg.args[0]) |
| 129 | + n.replace_input_with(arg, tensor_input) |
| 130 | + graph_module.graph.erase_node(arg) |
| 131 | + |
| 132 | + # Copy the users, since we are modifying it. |
| 133 | + users_copy = copy.copy(n.users) |
| 134 | + for i, user in enumerate(users_copy): |
| 135 | + if user.target != q_op: |
| 136 | + continue |
| 137 | + |
| 138 | + # quantization node found here, store the quantization parameters in meta value |
| 139 | + n.meta["output_qparams"][i] = QuantArgs.from_operator( |
| 140 | + user.target, user.args |
| 141 | + ) |
| 142 | + |
| 143 | + user.replace_all_uses_with(n) |
| 144 | + graph_module.graph.erase_node(user) |
| 145 | + |
| 146 | + # retrace the graph to update the fake tensor types |
| 147 | + graph_module = super().call(graph_module).graph_module |
| 148 | + |
| 149 | + graph_module.recompile() |
| 150 | + return PassResult(graph_module, True) |
| 151 | + |
| 152 | + |
| 153 | +class QuantizeFullArgument(ExportPass): |
| 154 | + """ |
| 155 | + Make sure the fill_value for full.default is quantized. This pass needs to be run before |
| 156 | + the folding pass above to make sure that the retraced output of the full.default op is |
| 157 | + the right dtype. |
| 158 | + """ |
| 159 | + |
| 160 | + def call(self, graph_module: GraphModule) -> PassResult: |
| 161 | + modified = False |
| 162 | + # Loop over the graph nodes and find any node in the 'targeted_ops' list. |
| 163 | + for n in graph_module.graph.nodes: |
| 164 | + n = cast(Node, n) |
| 165 | + if n.target != exir_ops.edge.aten.full.default: |
| 166 | + continue |
| 167 | + |
| 168 | + # Make sure we have a quantized operator |
| 169 | + user = list(n.users)[0] |
| 170 | + if user.target != q_op: |
| 171 | + continue |
| 172 | + |
| 173 | + qargs = QuantArgs.from_operator(user.target, user.args) |
| 174 | + if "dtype" not in n.kwargs.keys() or n.kwargs["dtype"] != qargs.dtype: |
| 175 | + # replace the node arg with a quantized dito and also set dtype |
| 176 | + # to get the right output according to the Edge IR specification: |
| 177 | + # exir/dialects/edge/edge.yaml:3596 |
| 178 | + quantized_full_value = qargs.quantize_value(n.args[1]).item() |
| 179 | + n.update_arg(1, quantized_full_value) |
| 180 | + n.update_kwarg("dtype", qargs.dtype) |
| 181 | + modified = True |
| 182 | + |
| 183 | + return PassResult(graph_module, modified) |
0 commit comments