diff --git a/backends/transforms/addmm_mm_to_linear.py b/backends/transforms/addmm_mm_to_linear.py index 358cbb7ac14..cb4b8e36001 100644 --- a/backends/transforms/addmm_mm_to_linear.py +++ b/backends/transforms/addmm_mm_to_linear.py @@ -9,6 +9,7 @@ from executorch.exir.pass_base import ExportPass, PassResult from executorch.exir.sym_util import eval_shape, eval_shape_upper_bound +from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq _int64_max_dim_val = torch.iinfo(torch.int64).max - 1 @@ -66,35 +67,35 @@ def replace_linear_view_copy_input_output(graph: torch.fx.Graph) -> torch.fx.Gra """ ops = exir_ops.edge for node in graph.nodes: - if node.op == "call_function" and (node.target == ops.aten.linear.default): - input_node = node.args[0] - dqlinear_input = get_dqlinear_input(input_node) - if dqlinear_input is not None and dqlinear_input != input_node: - if len(input_node.args[0].users) == 1: - input_node.replace_all_uses_with(dqlinear_input) - else: - print( - f"{input_node} has more than one user. Users: {input_node.users}" - ) - if len(node.users) == 1: - users = list(node.users) - maybe_view_copy = users[0] - if maybe_view_copy.op == "call_function" and ( - maybe_view_copy.target == ops.aten.view_copy.default - ): - # Must update the input node since replaced the original node - input_node = node.args[0] - input_shape = list(get_shape(input_node)) - weight_node = node.args[1] - if "val" not in weight_node.meta: - raise ValueError(f"Val not found meta of node {weight_node}") - weight_val = weight_node.meta["val"] - output_channels = weight_val.shape[0] - output_shape = input_shape - output_shape[-1] = output_channels - view_copy_out_shape = list(get_shape(maybe_view_copy)) - if output_shape == view_copy_out_shape: - maybe_view_copy.replace_all_uses_with(node) + if node.op != "call_function" or node.target != ops.aten.linear.default: + continue + if len(node.users) != 1: + continue + view_copy = next(iter(node.users)) + if view_copy.target != ops.aten.view_copy.default: + continue + weight_node = node.args[1] + if "val" not in weight_node.meta: + raise ValueError(f"Val not found meta of node {weight_node}") + output_channels = weight_node.meta["val"].shape[0] + input_node = node.args[0] + dqlinear_input = get_dqlinear_input(input_node) + # Reading the dequantized input before its views changes the shape of the + # linear output, so it is done only when the view after the linear goes. + for new_input in (dqlinear_input, input_node): + if new_input is None: + continue + output_shape = list(new_input.meta["val"].shape) + output_shape[-1] = output_channels + # Compare the symbolic shapes, since different dynamic shapes can + # have equal upper bounds. + if statically_known_true( + sym_eq(output_shape, list(view_copy.meta["val"].shape)) + ): + node.replace_input_with(input_node, new_input) + node.meta["val"] = view_copy.meta["val"] + view_copy.replace_all_uses_with(node) + break graph.eliminate_dead_code() return graph diff --git a/backends/transforms/targets.bzl b/backends/transforms/targets.bzl index 37aa83a0985..c5aa23a8054 100644 --- a/backends/transforms/targets.bzl +++ b/backends/transforms/targets.bzl @@ -33,6 +33,17 @@ def define_common_targets(): ], ) + runtime.python_test( + name = "test_addmm_mm_to_linear", + srcs = ["test/test_addmm_mm_to_linear.py"], + deps = [ + ":addmm_mm_to_linear", + "//caffe2:torch", + "//executorch/exir:lib", + "//executorch/exir/dialects:lib", + ], + ) + runtime.python_library( name = "decompose_sdpa", srcs = ["decompose_sdpa.py"], diff --git a/backends/transforms/test/test_addmm_mm_to_linear.py b/backends/transforms/test/test_addmm_mm_to_linear.py new file mode 100644 index 00000000000..2b3fbf4e4fa --- /dev/null +++ b/backends/transforms/test/test_addmm_mm_to_linear.py @@ -0,0 +1,180 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import unittest + +import torch +from executorch.backends.transforms.addmm_mm_to_linear import ( + apply_addmm_mm_to_linear_transform, +) +from executorch.exir import to_edge +from executorch.exir.dialects._ops import ops as exir_ops +from torch.export import Dim + + +def _dequantize(xq: torch.Tensor) -> torch.Tensor: + return torch.ops.quantized_decomposed.dequantize_per_tensor.tensor( + xq, torch.tensor(0.1), torch.tensor(0), -128, 127, torch.int8 + ) + + +def _int8(*shape: int) -> torch.Tensor: + return torch.randint(-128, 127, shape, dtype=torch.int8) + + +class _DequantizeLinearView(torch.nn.Module): + def __init__(self, swap: bool) -> None: + super().__init__() + self.linear = torch.nn.Linear(16, 8) + self.swap = swap + + def forward(self, xq: torch.Tensor) -> torch.Tensor: + a, b = xq.shape[0], xq.shape[1] + y = self.linear(_dequantize(xq).view(-1, 16)) + return y.view(b, a, 8) if self.swap else y.view(a, b, 8) + + +class _DequantizeLinear(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(16, 8) + + def forward(self, xq: torch.Tensor) -> torch.Tensor: + return self.linear(_dequantize(xq).view(-1, 16)) + + +class _DequantizeLinearNoOpView(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(16, 8) + + def forward(self, xq: torch.Tensor) -> torch.Tensor: + return self.linear(_dequantize(xq).view(-1, 16)).view(-1, 8) + + +class _DequantizeLinearViewAndFlatInput(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(16, 8) + + def forward(self, xq: torch.Tensor): + flat = _dequantize(xq).view(-1, 16) + y = self.linear(flat).view(xq.shape[0], xq.shape[1], 8) + return y, flat * 2 + + +class _DequantizeTwoLinearViews(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + self.q = torch.nn.Linear(16, 8) + self.k = torch.nn.Linear(16, 8) + + def forward(self, xq: torch.Tensor): + x = _dequantize(xq) + a, b = xq.shape[0], xq.shape[1] + return ( + self.q(x.view(-1, 16)).view(a, b, 8), + self.k(x.view(-1, 16)).view(a, b, 8), + ) + + +_BOUNDED = ({0: Dim("a", min=2, max=8), 1: Dim("b", min=2, max=8)},) +_UNBOUNDED = ({0: Dim("a"), 1: Dim("b")},) + + +_DEQUANTIZE = exir_ops.edge.quantized_decomposed.dequantize_per_tensor.tensor +_LINEAR = exir_ops.edge.aten.linear.default +_VIEW = exir_ops.edge.aten.view_copy.default + + +class TestAddmmMmToLinear(unittest.TestCase): + def _transform(self, model, example, dynamic_shapes=None): + ep = torch.export.export(model, (example,), dynamic_shapes=dynamic_shapes) + program = to_edge(ep).exported_program() + apply_addmm_mm_to_linear_transform(program.graph_module.graph) + return program + + def _linears(self, program): + return [n for n in program.graph_module.graph.nodes if n.target == _LINEAR] + + def test_view_to_the_linear_output_shape_is_removed(self): + model = _DequantizeLinearView(swap=False) + for name, dynamic_shapes in ( + ("static", None), + ("bounded", _BOUNDED), + ("unbounded", _UNBOUNDED), + ): + with self.subTest(name): + ep = torch.export.export( + model, (_int8(2, 3, 16),), dynamic_shapes=dynamic_shapes + ) + program = to_edge(ep).exported_program() + graph = program.graph_module.graph + view_val = graph.output_node().args[0][0].meta["val"] + apply_addmm_mm_to_linear_transform(graph) + output = graph.output_node().args[0][0] + self.assertEqual(output.target, _LINEAR) + self.assertEqual(output.args[0].target, _DEQUANTIZE) + self.assertIs(output.meta["val"], view_val) + x = _int8(2, 3, 16) + torch.testing.assert_close(program.module()(x), model(x)) + + def test_view_to_another_shape_with_equal_bounds_is_kept(self): + model = _DequantizeLinearView(swap=True) + # [b, a, 8] and the linear output [a, b, 8] have the same upper bounds, + # and without upper bounds the same example sizes. + for name, example, dynamic_shapes in ( + ("bounded", _int8(2, 3, 16), _BOUNDED), + ("unbounded", _int8(3, 3, 16), _UNBOUNDED), + ): + with self.subTest(name): + program = self._transform(model, example, dynamic_shapes) + output = program.graph_module.graph.output_node().args[0][0] + self.assertEqual(output.target, _VIEW) + (linear,) = self._linears(program) + self.assertEqual(linear.args[0].target, _VIEW) + x = _int8(2, 3, 16) + torch.testing.assert_close(program.module()(x), model(x)) + + def test_linear_reads_the_dequantized_input_only_when_its_view_goes(self): + # The first linear has no view after it, so it keeps reading the + # flattened input. The second has a view only to its own output shape, + # which goes, while the linear keeps reading the flattened input. The + # third reads the dequantized tensor once its view goes, while the other + # reader of the flattened input keeps its shape. + for model, reads in ( + (_DequantizeLinear(), _VIEW), + (_DequantizeLinearNoOpView(), _VIEW), + (_DequantizeLinearViewAndFlatInput(), _DEQUANTIZE), + ): + for name, dynamic_shapes in (("static", None), ("bounded", _BOUNDED)): + with self.subTest(type(model).__name__, shapes=name): + x = _int8(2, 3, 16) + program = self._transform(model, x, dynamic_shapes) + (linear,) = self._linears(program) + self.assertEqual(linear.args[0].target, reads) + self.assertIs( + program.graph_module.graph.output_node().args[0][0], linear + ) + torch.testing.assert_close(program.module()(x), model(x)) + + def test_linears_sharing_a_dequantized_input_both_lose_their_views(self): + model = _DequantizeTwoLinearViews() + for name, dynamic_shapes in (("static", None), ("bounded", _BOUNDED)): + with self.subTest(name): + x = _int8(2, 3, 16) + program = self._transform(model, x, dynamic_shapes) + linears = self._linears(program) + self.assertEqual(len(linears), 2) + self.assertTrue(all(n.args[0].target == _DEQUANTIZE for n in linears)) + self.assertFalse( + any(n.target == _VIEW for n in program.graph_module.graph.nodes) + ) + torch.testing.assert_close(program.module()(x), model(x)) + + +if __name__ == "__main__": + unittest.main() diff --git a/backends/xnnpack/_passes/convert_to_linear.py b/backends/xnnpack/_passes/convert_to_linear.py index 8259aae4e98..91481da60ce 100644 --- a/backends/xnnpack/_passes/convert_to_linear.py +++ b/backends/xnnpack/_passes/convert_to_linear.py @@ -142,8 +142,7 @@ def create_linear( exir_ops.edge.aten.linear.default, # HACK not edge_op/CATen args, ) - # TODO - calculate output even when dynamic_shape=True - linear_node.meta["val"] = torch.zeros(get_shape(output)) + linear_node.meta["val"] = output.meta["val"] logger.debug( f"Replacing {output}{get_shape(output)} node with {linear_node}{get_shape(linear_node)}" ) diff --git a/backends/xnnpack/test/passes/test_convert_to_linear.py b/backends/xnnpack/test/passes/test_convert_to_linear.py index 0e7bc7d01c4..67fb6819920 100644 --- a/backends/xnnpack/test/passes/test_convert_to_linear.py +++ b/backends/xnnpack/test/passes/test_convert_to_linear.py @@ -41,3 +41,57 @@ def test_fp32_convert_to_linear(self): ) .run_method_and_compare_outputs() ) + + def test_fp32_view_after_two_linears_with_dynamic_shapes(self): + class Model(torch.nn.Module): + def __init__(self): + super().__init__() + self.fc1 = torch.nn.Linear(16, 16) + self.fc2 = torch.nn.Linear(16, 8) + + def forward(self, x): + return self.fc2(self.fc1(x)).view(-1, 8) + + dynamic_shapes = ({0: torch.export.Dim("batch", min=1, max=32)},) + ( + Tester(Model(), (torch.randn(4, 16),), dynamic_shapes=dynamic_shapes) + .export() + .to_edge() + .run_passes(self.PassStage) + .check_count({"executorch_exir_dialects_edge__ops_aten_linear_default": 2}) + # The view does not change the shape, so it goes. + .check_not(["executorch_exir_dialects_edge__ops_aten_view_copy_default"]) + .run_method_and_compare_outputs() + ) + + def test_fp32_view_to_another_shape_with_equal_bounds_is_kept(self): + class Model(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(16, 8) + + def forward(self, x): + return self.linear(x).view(x.shape[1], x.shape[0], 8) + + x = torch.randn(2, 5, 16) + dynamic_shapes = ( + { + 0: torch.export.Dim("a", min=2, max=8), + 1: torch.export.Dim("b", min=2, max=8), + }, + ) + ( + Tester(Model(), (x,), dynamic_shapes=dynamic_shapes) + .export() + .to_edge() + .run_passes(self.PassStage) + .check_count( + { + "executorch_exir_dialects_edge__ops_aten_linear_default": 1, + # [b, a, 8] has the bounds of the linear output [a, b, 8], but + # not its shape, so the view stays. + "executorch_exir_dialects_edge__ops_aten_view_copy_default": 1, + } + ) + .run_method_and_compare_outputs(inputs=(x,)) + )