|
| 1 | +# Copyright (c) Meta Platforms, Inc. and 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 unittest |
| 8 | + |
| 9 | +import torch |
| 10 | +from executorch.exir.graph_module import contains_any_call_fn_target_op |
| 11 | + |
| 12 | + |
| 13 | +class TestContainsAnyCallFnTargetOp(unittest.TestCase): |
| 14 | + @staticmethod |
| 15 | + def _add_graph() -> tuple[torch.fx.GraphModule, torch.fx.Node]: |
| 16 | + graph = torch.fx.Graph() |
| 17 | + lhs = graph.placeholder("lhs") |
| 18 | + rhs = graph.placeholder("rhs") |
| 19 | + add = graph.call_function(torch.ops.aten.add.Tensor, (lhs, rhs)) |
| 20 | + graph.output(add) |
| 21 | + return torch.fx.GraphModule({}, graph), add |
| 22 | + |
| 23 | + def test_matches_aten_op(self) -> None: |
| 24 | + graph_module, _ = self._add_graph() |
| 25 | + |
| 26 | + self.assertTrue( |
| 27 | + contains_any_call_fn_target_op(graph_module, {torch.ops.aten.add.Tensor}) |
| 28 | + ) |
| 29 | + self.assertFalse( |
| 30 | + contains_any_call_fn_target_op(graph_module, {torch.ops.aten.mul.Tensor}) |
| 31 | + ) |
| 32 | + |
| 33 | + def test_matches_wrapped_edge_op(self) -> None: |
| 34 | + graph_module, add = self._add_graph() |
| 35 | + |
| 36 | + class EdgeOp: |
| 37 | + _op = torch.ops.aten.add.Tensor |
| 38 | + |
| 39 | + add.target = EdgeOp() |
| 40 | + |
| 41 | + self.assertTrue( |
| 42 | + contains_any_call_fn_target_op(graph_module, {torch.ops.aten.add.Tensor}) |
| 43 | + ) |
| 44 | + self.assertFalse( |
| 45 | + contains_any_call_fn_target_op(graph_module, {torch.ops.aten.mul.Tensor}) |
| 46 | + ) |
| 47 | + |
| 48 | + def test_matches_op_in_control_flow_submodule(self) -> None: |
| 49 | + true_graph, _ = self._add_graph() |
| 50 | + false_graph, _ = self._add_graph() |
| 51 | + |
| 52 | + graph = torch.fx.Graph() |
| 53 | + pred = graph.placeholder("pred") |
| 54 | + lhs = graph.placeholder("lhs") |
| 55 | + rhs = graph.placeholder("rhs") |
| 56 | + true_branch = graph.get_attr("true_graph") |
| 57 | + false_branch = graph.get_attr("false_graph") |
| 58 | + result = graph.call_function( |
| 59 | + torch.ops.higher_order.cond, |
| 60 | + (pred, true_branch, false_branch, [lhs, rhs]), |
| 61 | + ) |
| 62 | + graph.output(result) |
| 63 | + graph_module = torch.fx.GraphModule( |
| 64 | + {"true_graph": true_graph, "false_graph": false_graph}, graph |
| 65 | + ) |
| 66 | + |
| 67 | + self.assertTrue( |
| 68 | + contains_any_call_fn_target_op(graph_module, {torch.ops.aten.add.Tensor}) |
| 69 | + ) |
| 70 | + self.assertFalse( |
| 71 | + contains_any_call_fn_target_op(graph_module, {torch.ops.aten.mul.Tensor}) |
| 72 | + ) |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + unittest.main() |
0 commit comments