Lunderberg commented on code in PR #15806:
URL: https://github.com/apache/tvm/pull/15806#discussion_r1337320164


##########
python/tvm/relax/transform/remove_redundant_reshape.py:
##########
@@ -0,0 +1,83 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# pylint: disable=invalid-name, unused-argument, missing-function-docstring, 
abstract-method
+"""Relax Remove Redundant Reshape ops"""
+import tvm
+from tvm import IRModule, relax
+from tvm.ir.transform import PassContext
+from tvm.ir import structural_equal
+from tvm.relax import Expr, Function
+from tvm.relax.dpl import is_op, rewrite_call, wildcard
+from . import function_pass
+
+
+@function_pass(opt_level=0)
+class RemoveRedundantReshape:
+    """
+    Transformation pass to remove redundant reshape operator
+    """
+
+    def __init__(self):
+        self.input1 = wildcard()
+        shape1 = wildcard()
+        pattern_redundant_reshape = is_op("relax.reshape")(self.input1, shape1)
+        self.pattern1 = pattern_redundant_reshape
+        shape2 = wildcard()
+        self.pattern2 = is_op("relax.reshape")(pattern_redundant_reshape, 
shape2)
+        self.pattern = self.pattern2 | self.pattern1
+
+    def transform_function(self, func: Expr, mod: IRModule, ctx: PassContext) 
-> IRModule:
+        """
+        Tarnsformation function to remove redundant reshape
+        where tensors before and after reshape are of same dimentions.
+
+        Parameters
+        --------------
+        func: Expr
+            The relax function to be optimized
+
+        mod: IRModule
+            The IR module
+
+        ctx: PassContext
+            Relax pass context
+        """
+
+        updated_func = func
+        for _, funct in mod.functions.items():
+            # Skip non-relax functions
+            if not isinstance(funct, Function):
+                continue
+            # Skip primitive functions
+            if "Primitive" in funct.attrs.keys() and funct.attrs["Primitive"] 
!= 0:
+                continue
+
+            def rewriter(expr, matches):
+                args = matches[self.pattern]
+                if self.pattern2 in matches and args == matches[self.pattern2]:

Review Comment:
   Nit: The `args == matches[self.pattern2]` is unnecessary, as a pattern is 
only contained in the `matches` lookup if that subpattern was part of the match.



##########
python/tvm/relax/transform/remove_redundant_reshape.py:
##########
@@ -0,0 +1,83 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# pylint: disable=invalid-name, unused-argument, missing-function-docstring, 
abstract-method
+"""Relax Remove Redundant Reshape ops"""
+import tvm
+from tvm import IRModule, relax
+from tvm.ir.transform import PassContext
+from tvm.ir import structural_equal
+from tvm.relax import Expr, Function
+from tvm.relax.dpl import is_op, rewrite_call, wildcard
+from . import function_pass
+
+
+@function_pass(opt_level=0)
+class RemoveRedundantReshape:
+    """
+    Transformation pass to remove redundant reshape operator
+    """
+
+    def __init__(self):
+        self.input1 = wildcard()
+        shape1 = wildcard()
+        pattern_redundant_reshape = is_op("relax.reshape")(self.input1, shape1)
+        self.pattern1 = pattern_redundant_reshape

Review Comment:
   Nitpick: Can `self.pattern1` and `self.pattern2` be renamed to 
`self.no_op_reshape` and `self.repeated_reshape`?  That would make it easier 
for future readers to understand why each case is considered redundant.



##########
tests/python/relax/test_remove_redundant_reshape.py:
##########
@@ -0,0 +1,94 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""
+Test relax transform - Eliminate redundant reshape operations
+"""
+import tvm.testing
+from tvm import relax
+from tvm.relax.transform import DeadCodeElimination
+from tvm.relax.transform import RemoveRedundantReshape
+from tvm.script import ir as I, relax as R
+
+
+def _run_pass_compare_output(Before, Expected):
+    fused_mod = RemoveRedundantReshape()(Before)
+    assert relax.analysis.well_formed(fused_mod), "IRModule is not well-formed"

Review Comment:
   Nitpick: I like the checks for well-formedness in general, but they are 
redundant here.  The test environment for relax unit tests already has a 
well-formed check before and after each transform.  ([location in 
`conftest.py`](https://github.com/apache/tvm/blob/unity/tests/python/relax/conftest.py#L23))



##########
python/tvm/relax/transform/remove_redundant_reshape.py:
##########
@@ -0,0 +1,83 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# pylint: disable=invalid-name, unused-argument, missing-function-docstring, 
abstract-method
+"""Relax Remove Redundant Reshape ops"""
+import tvm
+from tvm import IRModule, relax
+from tvm.ir.transform import PassContext
+from tvm.ir import structural_equal
+from tvm.relax import Expr, Function
+from tvm.relax.dpl import is_op, rewrite_call, wildcard
+from . import function_pass
+
+
+@function_pass(opt_level=0)
+class RemoveRedundantReshape:
+    """
+    Transformation pass to remove redundant reshape operator
+    """
+
+    def __init__(self):
+        self.input1 = wildcard()
+        shape1 = wildcard()
+        pattern_redundant_reshape = is_op("relax.reshape")(self.input1, shape1)
+        self.pattern1 = pattern_redundant_reshape
+        shape2 = wildcard()
+        self.pattern2 = is_op("relax.reshape")(pattern_redundant_reshape, 
shape2)
+        self.pattern = self.pattern2 | self.pattern1
+
+    def transform_function(self, func: Expr, mod: IRModule, ctx: PassContext) 
-> IRModule:
+        """
+        Tarnsformation function to remove redundant reshape
+        where tensors before and after reshape are of same dimentions.
+
+        Parameters
+        --------------
+        func: Expr
+            The relax function to be optimized
+
+        mod: IRModule
+            The IR module
+
+        ctx: PassContext
+            Relax pass context
+        """
+
+        updated_func = func
+        for _, funct in mod.functions.items():
+            # Skip non-relax functions
+            if not isinstance(funct, Function):
+                continue
+            # Skip primitive functions
+            if "Primitive" in funct.attrs.keys() and funct.attrs["Primitive"] 
!= 0:
+                continue
+
+            def rewriter(expr, matches):
+                args = matches[self.pattern]
+                if self.pattern2 in matches and args == matches[self.pattern2]:
+                    return relax.op.reshape(matches[self.input1], args.args[1])
+                elif self.pattern1 in matches and args == 
matches[self.pattern1]:
+                    if args.args[0].struct_info.shape:
+                        if structural_equal(args.args[0].struct_info.shape, 
args.args[1]):
+                            return args.args[0]
+                    else:
+                        raise Exception("Tensor of unknown dimension or full 
shape is not known")

Review Comment:
   Should this fall through to the `return expr` instead of raising an 
exception?  Since tensors are not required to have a fully-defined shape at 
compile-time, this would raise an exception for some well-defined Relax 
functions.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to