|
| 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 torch |
| 8 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 9 | +from executorch.exir.passes import dead_code_elimination_pass |
| 10 | + |
| 11 | +from .utils import merge_decomposed_graph |
| 12 | + |
| 13 | + |
| 14 | +class PDist(torch.nn.Module): |
| 15 | + def __init__(self, N): |
| 16 | + super().__init__() |
| 17 | + # Precompute row and column indices for upper triangle pairs |
| 18 | + pairs = [(i, j) for i in range(N) for j in range(i + 1, N)] |
| 19 | + self.register_buffer( |
| 20 | + "rows", torch.tensor([i for i, _ in pairs], dtype=torch.int32) |
| 21 | + ) |
| 22 | + self.register_buffer( |
| 23 | + "cols", torch.tensor([j for _, j in pairs], dtype=torch.int32) |
| 24 | + ) |
| 25 | + |
| 26 | + def forward(self, x): |
| 27 | + # Select paired rows directly — only N*(N-1)/2 differences computed |
| 28 | + diff = torch.index_select(x, 0, self.rows) - torch.index_select(x, 0, self.cols) |
| 29 | + |
| 30 | + # Square differences |
| 31 | + sq_diff = diff**2 |
| 32 | + |
| 33 | + # Sum of squares |
| 34 | + sum_sq_diff = sq_diff.sum(dim=-1) |
| 35 | + |
| 36 | + # Square root |
| 37 | + return torch.sqrt(sum_sq_diff) |
| 38 | + |
| 39 | + |
| 40 | +class DecomposePDist(ExportPass): |
| 41 | + """ |
| 42 | + Decompose aten.pdist and aten._pdist_forward into supported primitives. |
| 43 | +
|
| 44 | + torch.pdist(x, p=2) computes pairwise Euclidean distances between all |
| 45 | + row pairs of a 2D input tensor x of shape [N, M], returning a condensed |
| 46 | + 1D vector of length N*(N-1)/2 (upper triangle, row-major order). |
| 47 | +
|
| 48 | + Decomposition (p=2 only): |
| 49 | + 1. diff = x[rows] - x[cols] # index_select paired rows: [N*(N-1)/2, M] |
| 50 | + 2. sq_diff = diff ** 2 # element-wise square |
| 51 | + 3. sum_sq = sq_diff.sum(dim=-1) # sum over feature dim -> [N*(N-1)/2] |
| 52 | + 4. out = sqrt(sum_sq) # Euclidean distances [N*(N-1)/2] |
| 53 | +
|
| 54 | + Row and column indices for upper triangle pairs are precomputed at |
| 55 | + decomposition time (requires static N). This avoids materializing the |
| 56 | + full [N, N, M] difference tensor. |
| 57 | +
|
| 58 | + Only p=2 is supported. |
| 59 | + """ |
| 60 | + |
| 61 | + pdist_targets = { |
| 62 | + torch.ops.aten.pdist.default, |
| 63 | + torch.ops.aten._pdist_forward.default, |
| 64 | + } |
| 65 | + |
| 66 | + def __init__(self) -> None: |
| 67 | + super().__init__() |
| 68 | + |
| 69 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 70 | + graph = graph_module.graph |
| 71 | + for node in list(graph.nodes): |
| 72 | + if node.target in self.pdist_targets: |
| 73 | + # Check p value - only p=2 is supported |
| 74 | + if len(node.args) > 1: |
| 75 | + p = node.args[1] |
| 76 | + elif "p" in node.kwargs: |
| 77 | + p = node.kwargs["p"] |
| 78 | + else: |
| 79 | + p = 2.0 |
| 80 | + assert ( |
| 81 | + p == 2 or p == 2.0 |
| 82 | + ), "Currently only p=2 is supported for PDist Decomposition" |
| 83 | + |
| 84 | + input_val = node.args[0].meta["val"] |
| 85 | + N = input_val.shape[0] |
| 86 | + assert isinstance(N, int), ( |
| 87 | + f"DecomposePDist requires static shapes but got symbolic " |
| 88 | + f"dimension N={N}. Dynamic shapes are not supported." |
| 89 | + ) |
| 90 | + |
| 91 | + model = PDist(N) |
| 92 | + decomposed_module = torch.export.export( |
| 93 | + model, |
| 94 | + (input_val,), |
| 95 | + strict=True, |
| 96 | + ).module() |
| 97 | + |
| 98 | + rows_attr = f"_pdist_rows_{node.name}" |
| 99 | + cols_attr = f"_pdist_cols_{node.name}" |
| 100 | + graph_module.register_buffer(rows_attr, model.rows) |
| 101 | + graph_module.register_buffer(cols_attr, model.cols) |
| 102 | + |
| 103 | + for decomposed_node in decomposed_module.graph.nodes: |
| 104 | + if decomposed_node.op == "get_attr": |
| 105 | + if decomposed_node.target == "rows": |
| 106 | + decomposed_node.target = rows_attr |
| 107 | + elif decomposed_node.target == "cols": |
| 108 | + decomposed_node.target = cols_attr |
| 109 | + |
| 110 | + with graph.inserting_before(node): |
| 111 | + # remap is used to map original node values to new node values, |
| 112 | + # which ensures that reference to nodes are correctly updated in the new graph |
| 113 | + remap = {"x": node.args[0]} |
| 114 | + merge_decomposed_graph( |
| 115 | + remap=remap, |
| 116 | + target_node=node, |
| 117 | + target_graph=graph, |
| 118 | + decomposed_graph_module=decomposed_module, |
| 119 | + ) |
| 120 | + graph.erase_node(node) |
| 121 | + |
| 122 | + dead_code_elimination_pass(graph_module) |
| 123 | + return PassResult(graph_module, True) |
0 commit comments