|
| 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 import exir |
| 11 | +from executorch.exir import CaptureConfig, EdgeCompileConfig |
| 12 | +from executorch.exir.passes import MemoryFormatOpsPass |
| 13 | +from torch.testing import FileCheck |
| 14 | + |
| 15 | + |
| 16 | +class TestMemoryFormatOpsPass(unittest.TestCase): |
| 17 | + def test_op_to_copy_replacement(self) -> None: |
| 18 | + class F(torch.nn.Module): |
| 19 | + def __init__(self): |
| 20 | + super().__init__() |
| 21 | + |
| 22 | + def forward( |
| 23 | + self, x: torch.Tensor, mem_format: torch.memory_format |
| 24 | + ) -> torch.Tensor: |
| 25 | + return x.to(dtype=torch.double, memory_format=mem_format) |
| 26 | + |
| 27 | + module = F().eval() |
| 28 | + sample_inputs = [ |
| 29 | + (torch.randn([2, 2], dtype=torch.float32), torch.contiguous_format), |
| 30 | + (torch.randn([2, 2, 2], dtype=torch.float32), torch.contiguous_format), |
| 31 | + (torch.randn([2, 2, 2, 2], dtype=torch.float32), torch.channels_last), |
| 32 | + ( |
| 33 | + torch.rand_like( |
| 34 | + torch.zeros([2, 2, 2, 2]), |
| 35 | + dtype=torch.float32, |
| 36 | + memory_format=torch.channels_last, |
| 37 | + ), |
| 38 | + torch.contiguous_format, |
| 39 | + ), |
| 40 | + ] |
| 41 | + |
| 42 | + aten_op_str = "torch.ops.aten._to_copy.default" |
| 43 | + edge_op_str = "executorch_exir_dialects_edge__ops_dim_order_ops__to_dim_order_copy_default" |
| 44 | + |
| 45 | + for sample_input in sample_inputs: |
| 46 | + before = exir.capture( |
| 47 | + module, |
| 48 | + sample_input, |
| 49 | + CaptureConfig(pt2_mode=True, enable_dynamic_shape=True), |
| 50 | + ) |
| 51 | + |
| 52 | + # check op strings before |
| 53 | + FileCheck().check_count(aten_op_str, 1, exactly=True).check_not( |
| 54 | + edge_op_str |
| 55 | + ).run(before.exported_program.graph_module.code) |
| 56 | + |
| 57 | + ep = before.to_edge( |
| 58 | + config=EdgeCompileConfig(_use_edge_ops=True) |
| 59 | + ) # Only replacing edge_ops |
| 60 | + |
| 61 | + # Run the pass - TODO move this in to_edge passes |
| 62 | + after = ep.transform(MemoryFormatOpsPass()) |
| 63 | + |
| 64 | + # check op strings |
| 65 | + FileCheck().check_not(aten_op_str).check_count( |
| 66 | + edge_op_str, 1, exactly=True |
| 67 | + ).run(after.exported_program.graph_module.code) |
| 68 | + |
| 69 | + # check EdgeOp and the new BackendOp should behave the same |
| 70 | + expected = before(*sample_input) |
| 71 | + actual = after(*sample_input) |
| 72 | + self.assertTrue(torch.allclose(actual, expected)) |
| 73 | + |
| 74 | + # TODO - more |
| 75 | + after.to_executorch() |
0 commit comments