|
| 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 | +from operator import attrgetter |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +# Also registers torch.ops.qnn_custom.hadamard_transform. |
| 11 | +from executorch.backends.qualcomm.builders.custom_ops import _hadamard_matrix |
| 12 | +from executorch.backends.qualcomm.utils.check_qnn_version import ( |
| 13 | + is_qnn_sdk_version_less_than, |
| 14 | +) |
| 15 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 16 | +from executorch.exir.passes import dead_code_elimination_pass |
| 17 | + |
| 18 | +from .utils import copy_meta |
| 19 | + |
| 20 | + |
| 21 | +def _is_power_of_2_sqare_matrix(weight: torch.Tensor) -> bool: |
| 22 | + dim = weight.shape[0] |
| 23 | + # Shape gate: non-square / non-2D / non-power-of-2 weight can never match. |
| 24 | + return ( |
| 25 | + weight.dim() != 2 or weight.shape[0] != weight.shape[1] or dim & (dim - 1) != 0 |
| 26 | + ) |
| 27 | + |
| 28 | + |
| 29 | +def _match_hadamard_weight(weight: torch.Tensor) -> bool: |
| 30 | + # Returns True if `weight == _hadamard_matrix(dim) * s` for some scale s. |
| 31 | + # A linear/matmul with such a weight is equivalent to a QNN HadamardTransform. |
| 32 | + if _is_power_of_2_sqare_matrix(weight): |
| 33 | + return False |
| 34 | + |
| 35 | + w = weight.detach().to(torch.float64) |
| 36 | + nonzero = w[w != 0] |
| 37 | + if nonzero.numel() == 0: |
| 38 | + return False |
| 39 | + # The Hadamard weight is H * s for a single global scale s; infer s from any |
| 40 | + # nonzero entry (all |H_ij| == 1). For per-channel quant this only matches |
| 41 | + # when every channel's dequantized scale reconstructs the same H * s. |
| 42 | + scale = float(nonzero.flatten()[0].abs()) |
| 43 | + hadamard = _hadamard_matrix(w.shape[0], w.device, w.dtype) * scale |
| 44 | + return torch.allclose(w, hadamard, rtol=0, atol=1e-4) |
| 45 | + |
| 46 | + |
| 47 | +class RecomposeHadamard(ExportPass): |
| 48 | + """ |
| 49 | + Rewrite a bias-less linear / matmul / 1x1 conv whose weight is a Hadamard |
| 50 | + matrix into a single qnn_custom.hadamard_transform op, so it is annotated and |
| 51 | + lowered as a first-class HadamardTransform instead of being detected late in |
| 52 | + the builder and validated as FullyConnected / MatMul / Conv. |
| 53 | +
|
| 54 | + Runs in the annotation pipeline (before quantization), where the weight is a |
| 55 | + real tensor and can be inspected. hadamard_transform acts on the last dim, so |
| 56 | + linear / matmul rewrite directly, while conv (which mixes the channel dim) is |
| 57 | + wrapped in permutes that move the channel to the last dim and back. |
| 58 | + """ |
| 59 | + |
| 60 | + def __init__(self): |
| 61 | + super().__init__() |
| 62 | + self.hadamard_target = torch.ops.qnn_custom.hadamard_transform.default |
| 63 | + |
| 64 | + def _is_pointwise_conv(self, node, weight: torch.Tensor) -> bool: |
| 65 | + # Only a 1x1, stride-1, no-pad, dilation-1, groups-1 conv is a pure |
| 66 | + # channel-mixing matmul equivalent to a Hadamard transform. conv2d args: |
| 67 | + # (input, weight, bias, stride, padding, dilation, groups) with defaults. |
| 68 | + stride = node.args[3] if len(node.args) > 3 else [1, 1] |
| 69 | + padding = node.args[4] if len(node.args) > 4 else [0, 0] |
| 70 | + dilation = node.args[5] if len(node.args) > 5 else [1, 1] |
| 71 | + groups = node.args[6] if len(node.args) > 6 else 1 |
| 72 | + return ( |
| 73 | + weight.dim() == 4 |
| 74 | + and all(k == 1 for k in weight.shape[2:]) |
| 75 | + and all(s == 1 for s in stride) |
| 76 | + and all(p == 0 for p in padding) |
| 77 | + and all(d == 1 for d in dilation) |
| 78 | + and groups == 1 |
| 79 | + ) |
| 80 | + |
| 81 | + def _get_hadamard_scale(self, weight: torch.Tensor) -> float: |
| 82 | + # weight == H * s (all |H_ij| == 1); linear/matmul(x) = x @ H. The op |
| 83 | + # applies the orthonormal H / sqrt(dim), so fold the remaining factor |
| 84 | + # s * sqrt(dim) into the op's scale (== 1 for an orthonormal Hadamard). |
| 85 | + dim = weight.shape[0] |
| 86 | + return float(weight.detach().abs().flatten()[0]) * (dim**0.5) |
| 87 | + |
| 88 | + def _rewrite_last_dim(self, graph, node, scale): |
| 89 | + # linear / matmul already transform the last dim: replace in place. |
| 90 | + with graph.inserting_before(node): |
| 91 | + hadamard_node = graph.create_node( |
| 92 | + "call_function", |
| 93 | + self.hadamard_target, |
| 94 | + (node.args[0], scale), |
| 95 | + ) |
| 96 | + hadamard_node.meta = copy_meta(node.meta) |
| 97 | + for user in node.users.copy(): |
| 98 | + user.replace_input_with(node, hadamard_node) |
| 99 | + |
| 100 | + def _rewrite_channel_dim(self, graph, node, scale): |
| 101 | + # conv mixes the channel dim (dim 1). Move it to the last dim, run the |
| 102 | + # transform there, then move it back. |
| 103 | + input_node = node.args[0] |
| 104 | + input_val = input_node.meta["val"] |
| 105 | + rank = input_val.dim() |
| 106 | + to_last = [0, *range(2, rank), 1] |
| 107 | + from_last = [0, rank - 1, *range(1, rank - 1)] |
| 108 | + with graph.inserting_before(node): |
| 109 | + pre = graph.create_node( |
| 110 | + "call_function", torch.ops.aten.permute.default, (input_node, to_last) |
| 111 | + ) |
| 112 | + pre.meta = copy_meta(node.meta) |
| 113 | + pre.meta["val"] = input_val.permute(to_last) |
| 114 | + hadamard_node = graph.create_node( |
| 115 | + "call_function", self.hadamard_target, (pre, scale) |
| 116 | + ) |
| 117 | + hadamard_node.meta = copy_meta(node.meta) |
| 118 | + post = graph.create_node( |
| 119 | + "call_function", |
| 120 | + torch.ops.aten.permute.default, |
| 121 | + (hadamard_node, from_last), |
| 122 | + ) |
| 123 | + post.meta = copy_meta(node.meta) |
| 124 | + for user in node.users.copy(): |
| 125 | + user.replace_input_with(node, post) |
| 126 | + |
| 127 | + def _is_hadamard_transform(self, graph_module, node): |
| 128 | + if node.op != "call_function": |
| 129 | + return False |
| 130 | + |
| 131 | + is_conv = node.target == torch.ops.aten.conv2d.default |
| 132 | + is_last_dim = node.target in ( |
| 133 | + torch.ops.aten.linear.default, |
| 134 | + torch.ops.aten.matmul.default, |
| 135 | + ) |
| 136 | + if not (is_conv or is_last_dim): |
| 137 | + return False |
| 138 | + |
| 139 | + # linear/conv carry an optional bias in args[2]; matmul never does. |
| 140 | + has_bias = len(node.args) >= 3 and node.args[2] is not None |
| 141 | + if has_bias: |
| 142 | + return False |
| 143 | + |
| 144 | + weight_node = node.args[1] |
| 145 | + if weight_node.op != "get_attr": |
| 146 | + return False |
| 147 | + weight = attrgetter(weight_node.target)(graph_module) |
| 148 | + if is_conv and not self._is_pointwise_conv(node, weight): |
| 149 | + return False |
| 150 | + # A 1x1 conv filter is [out, in, 1, 1]; squeeze to [out, in] to match. |
| 151 | + squeezed = weight.reshape(weight.shape[:2]) if is_conv else weight |
| 152 | + if not _match_hadamard_weight(squeezed): |
| 153 | + return False |
| 154 | + return True |
| 155 | + |
| 156 | + def call(self, graph_module: torch.fx.GraphModule): |
| 157 | + # HadamardTransform is only supported by QNN 2.47+. On older SDKs skip the |
| 158 | + # rewrite so the op keeps its normal lowering path. |
| 159 | + if is_qnn_sdk_version_less_than("2.47"): |
| 160 | + return PassResult(graph_module, False) |
| 161 | + |
| 162 | + graph = graph_module.graph |
| 163 | + modified = False |
| 164 | + for node in graph.nodes: |
| 165 | + if not self._is_hadamard_transform(graph_module, node): |
| 166 | + continue |
| 167 | + weight_node = node.args[1] |
| 168 | + weight = attrgetter(weight_node.target)(graph_module) |
| 169 | + is_conv = node.target == torch.ops.aten.conv2d.default |
| 170 | + squeezed = weight.reshape(weight.shape[:2]) if is_conv else weight |
| 171 | + scale = self._get_hadamard_scale(squeezed) |
| 172 | + if is_conv: |
| 173 | + self._rewrite_channel_dim(graph, node, scale) |
| 174 | + else: |
| 175 | + self._rewrite_last_dim(graph, node, scale) |
| 176 | + modified = True |
| 177 | + |
| 178 | + if modified: |
| 179 | + dead_code_elimination_pass(graph_module) |
| 180 | + return PassResult(graph_module, modified) |
0 commit comments