text
stringlengths
1
2.05k
import tvm.testing from tvm.script.parser
import tir as T from tvm
import ir, tir def test_tir_buffer_proxy(): buffer_0 = T.Buffer((128, 128), "float32") assert ( isinstance(buffer_0, tir.Buffer) and list(buffer_0.shape) == [128, 128] and buffer_0.dtype == "float32" ) buffer_1 = T.Buffer[(64, 64, 64), "int32"] assert ( isinstance(buffer_1, tir.Buffer) and list(buffer_1.shape) == [64, 64, 64] and buffer_1.dtype == "int32" ) def test_tir_ptr_proxy(): ptr_0 = T.Ptr("int32", "global") assert ( isinstance(ptr_0, tir.Var) and ptr_0.dtype == "handle" and isinstance(ptr_0.type_annotation, ir.PointerType) and ptr_0.type_annotation.element_type == ir.PrimType("int32") and ptr_0.type_annotation.storage_scope == "global" ) ptr_1 = T.Ptr["float32", "shared"] assert ( isinstance(ptr_1, tir.Var) and ptr_1.dtype == "handle" and isinstance(ptr_1.type_annotation, ir.PointerType) and ptr_1.type_annotation.element_type == ir.PrimType("float32") and ptr_1.type_annotation.storage_scope == "shared" ) if __name__ == "__main__": tvm.testing.main()
""" In this test file, we want to make sure the Python code can construct Doc objects, then access and modify their attributes correctly. """
import pytest
import tvm from tvm.runtime
import ObjectPath from tvm.script.printer.doc
import ( AssertDoc, AssignDoc, AttrAccessDoc, CallDoc, ClassDoc, DictDoc, ExprStmtDoc, ForDoc, FunctionDoc, IdDoc, IfDoc, IndexDoc, LambdaDoc, ListDoc, LiteralDoc, OperationDoc, OperationKind, ReturnDoc, ScopeDoc, SliceDoc, StmtBlockDoc, TupleDoc, WhileDoc, ) @pytest.mark.parametrize( "value", [None, "test", 0, 1, -2, 0.0, 1.5, -1.3, True, False], ) def test_literal_doc_construction(value): doc = LiteralDoc(value) if isinstance(value, float): assert float(doc.value) == pytest.approx(value) else: assert doc.value == value def test_id_doc(): doc = IdDoc("name") assert doc.name == "name" def test_attr_access_doc(): target = IdDoc("x") doc = AttrAccessDoc(target, "attribute") assert doc.value == target assert doc.name == "attribute" @pytest.mark.parametrize( "indices", [ [], [LiteralDoc(1)], [LiteralDoc(2), IdDoc("x")], [SliceDoc(LiteralDoc(1), LiteralDoc(2))], [SliceDoc(LiteralDoc(1)), IdDoc("y")], ], ) def test_index_doc(indices): target = IdDoc("x") doc = IndexDoc(target, indices) assert doc.value == target assert list(doc.indices) == indices @pytest.mark.parametrize( "args, kwargs", [ ([], {}), ([LiteralDoc("arg")], {}), ([LiteralDoc("arg"), IdDoc("x")], {}), ([], {"x": LiteralDoc("x")}), ([], {"x": LiteralDoc("x"), "y": LiteralDoc("y")}), ([LiteralDoc("arg")], {"x": LiteralDoc("x"), "y": LiteralDoc("y")}), ([LiteralDoc("arg"), IdDoc("x")], {"x": LiteralDoc("x"), "y": LiteralDoc("y")}), ], ) def test_call_doc(args, kwargs): target = IdDoc("x") doc = CallDoc(target, *args, **kwargs) assert doc.callee == target assert list(doc.args) == args assert dict(zip(doc.kwargs_keys, doc.kwargs_values)) == kwargs @pytest.mark.parametrize( "operands", [ [], [LiteralDoc(1)]
, [LiteralDoc(2), IdDoc("x")], [LiteralDoc(2), IdDoc("x"), LiteralDoc("y")], ], ) def test_operation_doc(operands): operator = OperationKind.Add doc = OperationDoc(OperationKind.Add, operands) assert doc.kind == operator assert list(doc.operands) == operands @pytest.mark.parametrize( "args", [ [], [IdDoc("x")], [IdDoc("x"), IdDoc("y")], ], ) def test_lambda_doc(args): body = LiteralDoc(1) doc = LambdaDoc(args, body) assert doc.body == body assert list(doc.args) == args @pytest.mark.parametrize( "elements", [ [], [IdDoc("x")], [IdDoc("x"), IdDoc("y")], ], ) def test_tuple_doc(elements): doc = TupleDoc(elements) assert list(doc.elements) == elements @pytest.mark.parametrize( "elements", [ [], [IdDoc("x")], [IdDoc("x"), IdDoc("y")], ], ) def test_list_doc(elements): doc = ListDoc(elements) assert list(doc.elements) == elements @pytest.mark.parametrize( "content", [ {}, {LiteralDoc("k"): IdDoc("v")}, {LiteralDoc("k"): IdDoc("v"), LiteralDoc("k2"): IdDoc("v2")}, ], ) def test_dict_doc(content): doc = DictDoc(content) assert dict(zip(doc.keys, doc.values)) == content @pytest.mark.parametrize("start", [LiteralDoc(1), None]) @pytest.mark.parametrize("stop", [LiteralDoc(2), None]) @pytest.mark.parametrize("step", [LiteralDoc(3), None]) def test_slice_doc(start, stop, step): doc = SliceDoc(start, stop) assert doc.start == start assert doc.stop == stop def test_expr_doc_attr_access(): target = IdDoc("x") attr = "test" doc = target.attr(attr) assert doc.value == target assert doc.name == attr @pytest.mark.parametrize( "indices", [ (), LiteralDoc(1), SliceDoc(LiteralDoc(1), LiteralDoc(2)), (LiteralDoc(1),), (LiteralDoc(2), IdDoc("x")), (SliceDoc(LiteralDoc(1), LiteralDoc(2)),), (Sli
ceDoc(LiteralDoc(1)), IdDoc("y")), ], ) def test_expr_doc_get_item(indices): target = IdDoc("x") doc = target[indices] assert doc.value == target if not isinstance(indices, tuple): indices = (indices,) assert tuple(doc.indices) == indices @pytest.mark.parametrize( "args, kwargs", [ ([], {}), ([LiteralDoc("arg")], {}), ([LiteralDoc("arg"), IdDoc("x")], {}), ([], {"x": LiteralDoc("x")}), ([], {"x": LiteralDoc("x"), "y": LiteralDoc("y")}), ([LiteralDoc("arg")], {"x": LiteralDoc("x"), "y": LiteralDoc("y")}), ([LiteralDoc("arg"), IdDoc("x")], {"x": LiteralDoc("x"), "y": LiteralDoc("y")}), ], ) def test_expr_doc_call_with(args, kwargs): target = IdDoc("x") doc = target.call(*args, **kwargs) assert doc.callee == target assert list(doc.args) == args assert dict(zip(doc.kwargs_keys, doc.kwargs_values)) == kwargs @pytest.mark.parametrize( "stmts", [ [], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) def test_stmt_block_doc(stmts): doc = StmtBlockDoc(stmts) assert list(doc.stmts) == stmts @pytest.mark.parametrize( "lhs, rhs, annotation", [ (IdDoc("x"), IdDoc("y"), None), (IdDoc("x"), None, IdDoc("int")), (IdDoc("x"), IdDoc("y"), IdDoc("int")), ], ) def test_assign_doc(lhs, rhs, annotation): doc = AssignDoc(lhs, rhs, annotation) assert doc.lhs == lhs assert doc.rhs == rhs assert doc.annotation == annotation @pytest.mark.parametrize( "lhs, rhs, annotation", [ (IdDoc("x"), None, None), (TupleDoc([IdDoc("x"), IdDoc("y")]), None, IdDoc("int")), (TupleDoc([IdDoc("x"), IdDoc("y")]), IdDoc("u"), IdDoc("int")), ], ) def test_invalid_assign_doc(lhs, rhs, annotation): with pytest.raises(ValueError) as e: AssignDoc(lhs, rhs, annotation) assert "AssignDoc" in str(e.value) @pytest.mark.parametrize( "else_branch", [
[], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) @pytest.mark.parametrize( "then_branch", [ [], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) def test_if_doc(then_branch, else_branch): predicate = IdDoc("x") if not then_branch and not else_branch: with pytest.raises(ValueError) as e: IfDoc(predicate, then_branch, else_branch) assert "IfDoc" in str(e.value) return else: doc = IfDoc(predicate, then_branch, else_branch) assert doc.predicate == predicate assert list(doc.then_branch) == then_branch assert list(doc.else_branch) == else_branch @pytest.mark.parametrize( "body", [ [], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) def test_while_doc(body): predicate = IdDoc("x") doc = WhileDoc(predicate, body) assert doc.predicate == predicate assert list(doc.body) == body @pytest.mark.parametrize( "body", [ [], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) def test_for_doc(body): lhs = IdDoc("x") rhs = IdDoc("y") doc = ForDoc(lhs, rhs, body) assert doc.lhs == lhs assert doc.rhs == rhs assert list(doc.body) == body @pytest.mark.parametrize( "lhs", [ None, IdDoc("x"), ], ) @pytest.mark.parametrize( "body", [ [], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) def test_scope_doc(lhs, body): rhs = IdDoc("y") doc = ScopeDoc(lhs, rhs, body) assert doc.lhs == lhs assert doc.rhs == rhs assert list(doc.body) == body def test_expr_stmt_doc(): expr = IdDoc("x") doc = ExprStmtDoc(expr) assert doc.expr == expr @pytest.mark.parametrize( "msg", [ None, LiteralDoc("msg"),
], ) def test_assert_doc(msg): test = IdDoc("x") doc = AssertDoc(test, msg) assert doc.test == test assert doc.msg == msg def test_return_doc(): value = IdDoc("x") doc = ReturnDoc(value) assert doc.value == value @pytest.mark.parametrize( "args", [ [], [AssignDoc(IdDoc("x"), None, IdDoc("int"))], [ AssignDoc(IdDoc("x"), None, IdDoc("int")), AssignDoc(IdDoc("y"), LiteralDoc(1), IdDoc("int")), ], ], ) @pytest.mark.parametrize( "decorators", [ [], [IdDoc("test")], [IdDoc("test"), IdDoc("test2")], ], ) @pytest.mark.parametrize( "return_type", [ None, LiteralDoc(None), ], ) @pytest.mark.parametrize( "body", [ [], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) def test_function_doc(args, decorators, return_type, body): name = IdDoc("name") doc = FunctionDoc(name, args, decorators, return_type, body) assert doc.name == name assert list(doc.args) == args assert list(doc.decorators) == decorators assert doc.return_type == return_type assert list(doc.body) == body @pytest.mark.parametrize( "decorators", [ [], [IdDoc("test")], [IdDoc("test"), IdDoc("test2")], ], ) @pytest.mark.parametrize( "body", [ [], [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], ], ) def test_class_doc(decorators, body): name = IdDoc("name") doc = ClassDoc(name, decorators, body) assert doc.name == name assert list(doc.decorators) == decorators assert list(doc.body) == body def test_stmt_doc_comment(): doc = ExprStmtDoc(IdDoc("x")) assert doc.comment is None comment = "test comment" doc.comment = comment assert "comment" not in doc.__dict__ assert doc.comment == comment def test_doc_source_paths(): doc = IdDoc("x")
assert len(doc.source_paths) == 0 source_paths = [ObjectPath.root(), ObjectPath.root().attr("x")] doc.source_paths = source_paths assert not isinstance(doc.source_paths, list) assert list(doc.source_paths) == source_paths doc.source_paths = [] assert len(doc.source_paths) == 0 if __name__ == "__main__": tvm.testing.main()
# 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. import pytest from tvm.error import TVMError from tvm.script.printer import script from tvm.tir import FloatImm def test_as_script_unknown_ir(): ir_node = FloatImm("float32", 1.0) with pytest.raises(TVMError) as e: script(ir_node, "test_xyz", {}) assert "test_xyz" in str(e.value)
# 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. from tvm.script.printer.frame import MetadataFrame def test_frame_add_callback(): frame = MetadataFrame() flag = 0 def callback1(): nonlocal flag flag += 1 def callback2(): nonlocal flag flag += 5 frame.add_exit_callback(callback1) with frame: frame.add_exit_callback(callback2) assert flag == 0 assert flag == 6 def test_frame_clear_callbacks_after_exit(): frame = MetadataFrame() flag = 0 def callback(): nonlocal flag flag += 1 frame.add_exit_callback(callback) with frame: pass assert flag == 1 with frame: pass assert flag == 1
# 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. import pytest import tvm from tvm.script import tir as T def test_highlight_script(): @tvm.script.ir_module class Module: @T.prim_func def main( # type: ignore a: T.handle, b: T.handle, c: T.handle, ) -> None: # pylint: disable=no-self-argument T.func_attr({"global_symbol": "main", "tir.noalias": True}) A = T.match_buffer(a, [16, 128, 128]) B = T.match_buffer(b, [16, 128, 128]) C = T.match_buffer(c, [16, 128, 128]) for n, i, j, k in T.grid(16, 128, 128, 128): with T.block("matmul"): vn, vi, vj, vk = T.axis.remap("SSSR", [n, i, j, k]) with T.init(): C[vn, vi, vj] = 0.0 # type: ignore C[vn, vi, vj] = C[vn, vi, vj] + A[vn, vi, vk] * B[vn, vj, vk] Module.show() Module["main"].show() Module["main"].show(style="light") Module["main"].show(style="dark") Module["main"].show(style="ansi")
import pytest from tvm.runtime
import ObjectPath from tvm.script.printer.doc
import IdDoc from tvm.script.printer.frame
import MetadataFrame, VarDefFrame from tvm.script.printer.ir_docsifier
import IRDocsifier, RootNodeContainer from tvm.tir
import Var @pytest.fixture def ir_docsifier(): """ Creates an IRDocsifier instance with a special dispatch token. """ _ir_docsifier = IRDocsifier({}) with _ir_docsifier.dispatch_token(f"{__file__}"): yield _ir_docsifier def _get_id_doc_printer(id_name): def printer(obj, object_path, ir_docsifier): return IdDoc(id_name) return printer def _root_dispatch_function(obj, ir_docsifier): doc = ir_docsifier.as_doc(obj, ObjectPath.root()) doc.source_paths = [ObjectPath.root().attr("irdocsifier_test")] return doc IRDocsifier.set_dispatch(Var, _get_id_doc_printer("x"), f"{__file__}") IRDocsifier.set_root_dispatch(f"{__file__}", _root_dispatch_function) def test_set_dispatch(ir_docsifier): IRDocsifier.set_dispatch(Var, _get_id_doc_printer("x2"), f"{__file__}-2") with ir_docsifier.dispatch_token(f"{__file__}-2"): doc = ir_docsifier.as_doc(Var("x", dtype="int8"), ObjectPath.root()) assert doc.name == "x2" doc = ir_docsifier.as_doc(Var("x", dtype="int8"), ObjectPath.root()) assert doc.name == "x" def test_set_root_dispatch(ir_docsifier): doc = ir_docsifier.as_doc(RootNodeContainer(Var("x", dtype="int8")), ObjectPath.root()) assert ObjectPath.root().attr("irdocsifier_test") in doc.source_paths def test_as_doc(ir_docsifier): object_path = ObjectPath.root() doc = ir_docsifier.as_doc(Var("x", "int8"), ObjectPath.root()) assert doc.name == "x" assert list(doc.source_paths) == [object_path] def test_with_dispatch_token(ir_docsifier): initial_token_count = len(ir_docsifier.dispatch_tokens) with ir_docsifier.dispatch_token("tir"): assert len(ir_docsifier.dispatch_tokens) == initial_token_count + 1 assert len(ir_docsifier.dispatch_tokens) == initial_token_count def test_with_frame(ir_docsifier): initial_frame_count = len(ir_docsifier.frames) frame = VarDefFrame() is_callback_called = False def callback(): nonlocal is_callback_called is_callback_cal
led = True frame.add_exit_callback(callback) with ir_docsifier.frame(frame): assert len(ir_docsifier.frames) == initial_frame_count + 1 assert not is_callback_called assert len(ir_docsifier.frames) == initial_frame_count assert is_callback_called def test_get_frame(ir_docsifier): with ir_docsifier.frame(VarDefFrame()) as frame_a: assert ir_docsifier.get_frame(MetadataFrame) is None assert ir_docsifier.get_frame(VarDefFrame) == frame_a with ir_docsifier.frame(VarDefFrame()) as frame_b: assert ir_docsifier.get_frame(MetadataFrame) is None assert ir_docsifier.get_frame(VarDefFrame) == frame_b with ir_docsifier.frame(MetadataFrame()) as frame_c: assert ir_docsifier.get_frame(MetadataFrame) == frame_c assert ir_docsifier.get_frame(VarDefFrame) == frame_b assert ir_docsifier.get_frame(MetadataFrame) is None assert ir_docsifier.get_frame(VarDefFrame) == frame_b assert ir_docsifier.get_frame(MetadataFrame) is None assert ir_docsifier.get_frame(VarDefFrame) == frame_a
import itertools
import pytest
import tvm from tvm.script.printer.doc
import ( AssertDoc, AssignDoc, CallDoc, ClassDoc, DictDoc, ExprStmtDoc, ForDoc, FunctionDoc, IdDoc, IfDoc, LambdaDoc, ListDoc, LiteralDoc, OperationDoc, OperationKind, ReturnDoc, ScopeDoc, SliceDoc, StmtBlockDoc, TupleDoc, WhileDoc, ) from tvm.script.printer.doc_printer
import to_python_script def format_script(s: str) -> str: """ Remove leading and trailing blank lines, and make the minimum idention 0 """ s = s.strip("\n") non_empty_lines = [line for line in s.splitlines() if line and not line.isspace()] if not non_empty_lines: return "\n" line_indents = [len(line) - len(line.lstrip(" ")) for line in non_empty_lines] spaces_to_remove = min(line_indents) cleaned_lines = "\n".join(line[spaces_to_remove:] for line in s.splitlines()) if not cleaned_lines.endswith("\n"): cleaned_lines += "\n" return cleaned_lines @pytest.mark.parametrize( "doc,expected", [ (LiteralDoc(None), "None"), (LiteralDoc(True), "True"), (LiteralDoc(False), "False"), (LiteralDoc("test"), '"test"'), (LiteralDoc(""), '""'), (LiteralDoc('""'), r'"\"\""'), (LiteralDoc("\n\t\\test\r"), r'"\n\t\\test\r"'), pytest.param(LiteralDoc("\x88"), r'"\x88"', marks=pytest.mark.xfail), (LiteralDoc(0), "0"), (LiteralDoc(-1), "-1"), (LiteralDoc(3.25), "3.25"), (LiteralDoc(-0.5), "-0.5"), ], ids=itertools.count(), ) def test_print_literal_doc(doc, expected): assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "name", [ "test", "_test", "TestCase", "test_case", "test123", ], ids=itertools.count(), ) def test_print_id_doc(name): doc = IdDoc(name) assert to_python_script(doc) == format_script(name) @pytest.mark.parametrize( "attr", [ "attr", "_attr", "Attr", "attr_1", ], ids=itertools.count(), ) def test_print_attr_doc(attr): doc = IdDoc("x").attr(attr) assert to_python_script(doc) == format_script(f"x.{attr}") @pytest.mark.parametrize( "indices, expected", [ ( (), "[()]", ), ( (LiteralDoc(1),), "[1]",
), ( (LiteralDoc(2), IdDoc("x")), "[2, x]", ), ( (SliceDoc(LiteralDoc(1), LiteralDoc(2)),), "[1:2]", ), ( (SliceDoc(LiteralDoc(1)), IdDoc("y")), "[1:, y]", ), ( (SliceDoc(), IdDoc("y")), "[:, y]", ), ( (IdDoc("x"), IdDoc("y"), IdDoc("z")), "[x, y, z]", ), ], ids=itertools.count(), ) def test_print_index_doc(indices, expected): doc = IdDoc("x")[indices] assert to_python_script(doc) == format_script(f"x{expected}") UNARY_OP_TOKENS = { OperationKind.USub: "-", OperationKind.Invert: "~", OperationKind.Not: "not ", } @pytest.mark.parametrize( "op_kind, expected_token", list(UNARY_OP_TOKENS.items()), ids=UNARY_OP_TOKENS.keys(), ) def test_print_unary_operation_doc(op_kind, expected_token): doc = OperationDoc(op_kind, [IdDoc("x")]) assert to_python_script(doc) == format_script(f"{expected_token}x") BINARY_OP_TOKENS = { OperationKind.Add: "+", OperationKind.Sub: "-", OperationKind.Mult: "*", OperationKind.Div: "/", OperationKind.FloorDiv: " OperationKind.Mod: "%", OperationKind.Pow: "**", OperationKind.LShift: "<<", OperationKind.RShift: ">>", OperationKind.BitAnd: "&", OperationKind.BitOr: "|", OperationKind.BitXor: "^", OperationKind.Lt: "<", OperationKind.LtE: "<=", OperationKind.Eq: "==", OperationKind.NotEq: "!=", OperationKind.Gt: ">", OperationKind.GtE: ">=", OperationKind.And: "and", OperationKind.Or: "or", } @pytest.mark.parametrize( "op_kind, expected_token", list(BINARY_OP_TOKENS.items()), ids=BINARY_OP_TOKENS.keys(), ) def test_print_binary_operation_doc(op_kind, expected_token): doc = OperationDoc(op_kind, [IdDoc("x"), IdDoc("y")]) assert to_python_script(doc) == format_script(f"x {expected_token} y") SPECIAL_OP_CASES = [ ( OperationKind
.IfThenElse, [LiteralDoc(True), LiteralDoc("true"), LiteralDoc("false")], '"true" if True else "false"', ), ( OperationKind.IfThenElse, [IdDoc("x"), LiteralDoc(None), LiteralDoc(1)], "None if x else 1", ), ] @pytest.mark.parametrize( "op_kind, operands, expected", SPECIAL_OP_CASES, ids=[kind for (kind, *_) in SPECIAL_OP_CASES] ) def test_print_special_operation_doc(op_kind, operands, expected): doc = OperationDoc(op_kind, operands) assert to_python_script(doc) == format_script(expected) def test_operation_doc_test_exhaustive(): special_op_covered = {k for k, *_ in SPECIAL_OP_CASES} for op_kind in OperationKind: if OperationKind._UnaryStart < op_kind < OperationKind._UnaryEnd: assert op_kind in UNARY_OP_TOKENS, ( f"{op_kind.name} not covered in test_print_unary_operation_doc. " f"Please add the expected token to UNARY_OP_TOKENS" ) elif OperationKind._BinaryStart < op_kind < OperationKind._BinaryEnd: assert op_kind in BINARY_OP_TOKENS, ( f"{op_kind.name} not covered in test_print_binary_operation_doc. " f"Please add the expected token to BINARY_OP_TOKENS" ) elif not op_kind.name.startswith("_"): assert op_kind in special_op_covered, ( f"{op_kind.name} not covered in test_print_special_operation_doc. " f"Please add the test cases for it to SPECIAL_OP_CASES" ) @pytest.mark.parametrize( "args, kwargs, expected", [ ( (), {}, "()", ), ( (), {"key0": IdDoc("u")}, "(key0=u)", ), ( (), {"key0": IdDoc("u"), "key1": IdDoc("v")}, "(key0=u, key1=v)", ), ( (IdDoc("x"),), {}, "(x)", ), ( (IdDoc("x"),), {"key
0": IdDoc("u")}, "(x, key0=u)", ), ( (IdDoc("x"),), {"key0": IdDoc("u"), "key1": IdDoc("v")}, "(x, key0=u, key1=v)", ), ( (IdDoc("x"), (IdDoc("y"))), {}, "(x, y)", ), ( (IdDoc("x"), (IdDoc("y"))), {"key0": IdDoc("u")}, "(x, y, key0=u)", ), ( (IdDoc("x"), (IdDoc("y"))), {"key0": IdDoc("u"), "key1": IdDoc("v")}, "(x, y, key0=u, key1=v)", ), ], ids=itertools.count(), ) def test_print_call_doc(args, kwargs, expected): doc = CallDoc(IdDoc("f"), *args, **kwargs) assert to_python_script(doc) == format_script(f"f{expected}") @pytest.mark.parametrize( "args, expected", [ ( (), "lambda : 0", ), ( (IdDoc("x"),), "lambda x: 0", ), ( (IdDoc("x"), IdDoc("y")), "lambda x, y: 0", ), ( (IdDoc("x"), IdDoc("y"), IdDoc("z")), "lambda x, y, z: 0", ), ], ids=itertools.count(), ) def test_print_lambda_doc(args, expected): doc = LambdaDoc(args, body=LiteralDoc(0)) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "elements, expected", [ ( (), "[]", ), ( [IdDoc("x")], "[x]", ), ( [IdDoc("x"), IdDoc("y")], "[x, y]", ), ( [IdDoc("x"), IdDoc("y"), IdDoc("z")], "[x, y, z]", ), ], ids=itertools.count(), ) def test_print_list_doc(elements, expected): doc = ListDoc(elements) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "elements, expected", [ ( (), "()", ), ( [IdDoc("x")], "(x,)", ),
( [IdDoc("x"), IdDoc("y")], "(x, y)", ), ( [IdDoc("x"), IdDoc("y"), IdDoc("z")], "(x, y, z)", ), ], ids=itertools.count(), ) def test_print_tuple_doc(elements, expected): doc = TupleDoc(elements) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "content, expected", [ ( {}, "{}", ), ( {LiteralDoc("key_x"): IdDoc("x")}, '{"key_x": x}', ), ( {LiteralDoc("key_x"): IdDoc("x"), LiteralDoc("key_y"): IdDoc("y")}, '{"key_x": x, "key_y": y}', ), ( { LiteralDoc("key_x"): IdDoc("x"), LiteralDoc("key_y"): IdDoc("y"), LiteralDoc("key_z"): IdDoc("z"), }, '{"key_x": x, "key_y": y, "key_z": z}', ), ], ids=itertools.count(), ) def test_print_dict_doc(content, expected): doc = DictDoc(content) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "slice_doc, expected", [ ( SliceDoc(), ":", ), ( SliceDoc(LiteralDoc(1)), "1:", ), ( SliceDoc(None, LiteralDoc(2)), ":2", ), ( SliceDoc(LiteralDoc(1), LiteralDoc(2)), "1:2", ), ( SliceDoc(None, None, LiteralDoc(3)), "::3", ), ( SliceDoc(LiteralDoc(1), None, LiteralDoc(3)), "1::3", ), ( SliceDoc(None, LiteralDoc(2), LiteralDoc(3)), ":2:3", ), ( SliceDoc(LiteralDoc(1), LiteralDoc(2), LiteralDoc(3)), "1:2:3", ), ], ids=itertools.count(), ) def test_print_slice_doc(slice_doc, expected): doc = IdDoc("x")[slice_doc] assert to_python_script(doc) == format_script
(f"x[{expected}]") @pytest.mark.parametrize( "stmts, expected", [ ( [], "", ), ( [ExprStmtDoc(IdDoc("x"))], "x", ), ( [ExprStmtDoc(IdDoc("x")), ExprStmtDoc(IdDoc("y"))], """ x y """, ), ], ids=itertools.count(), ) def test_print_stmt_block_doc(stmts, expected): doc = StmtBlockDoc(stmts) assert to_python_script(doc).strip() == format_script(expected).strip() @pytest.mark.parametrize( "doc, expected", [ ( AssignDoc(IdDoc("x"), IdDoc("y"), None), "x = y", ), ( AssignDoc(IdDoc("x"), IdDoc("y"), IdDoc("int")), "x: int = y", ), ( AssignDoc(IdDoc("x"), None, IdDoc("int")), "x: int", ), ( AssignDoc(TupleDoc([IdDoc("x"), IdDoc("y")]), IdDoc("z"), None), "x, y = z", ), ( AssignDoc(TupleDoc([IdDoc("x"), TupleDoc([IdDoc("y"), IdDoc("z")])]), IdDoc("z"), None), "x, (y, z) = z", ), ], ids=itertools.count(), ) def test_print_assign_doc(doc, expected): assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "then_branch, else_branch, expected", [ ( [ExprStmtDoc(IdDoc("x"))], [], """ if pred: x """, ), ( [], [ExprStmtDoc(IdDoc("y"))], """ if pred: pass else: y """, ), ( [ExprStmtDoc(IdDoc("x"))], [ExprStmtDoc(IdDoc("y"))], """ if pred: x else: y """, ), ], ids=itertools.count(), ) def test_print_if_doc(then_branch, else_branch, expected): doc = IfDoc(IdDoc("pre
d"), then_branch, else_branch) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "body, expected", [ ( [ExprStmtDoc(IdDoc("x"))], """ while pred: x """, ), ( [], """ while pred: pass """, ), ], ids=itertools.count(), ) def test_print_while_doc(body, expected): doc = WhileDoc(IdDoc("pred"), body) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "body, expected", [ ( [ExprStmtDoc(IdDoc("x"))], """ for x in y: x """, ), ( [], """ for x in y: pass """, ), ], ids=itertools.count(), ) def test_print_for_doc(body, expected): doc = ForDoc(IdDoc("x"), IdDoc("y"), body) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "lhs, body, expected", [ ( IdDoc("c"), [ExprStmtDoc(IdDoc("x"))], """ with context() as c: x """, ), ( IdDoc("c"), [], """ with context() as c: pass """, ), ( None, [], """ with context(): pass """, ), ( None, [ExprStmtDoc(IdDoc("x"))], """ with context(): x """, ), ], ids=itertools.count(), ) def test_print_scope_doc(lhs, body, expected): doc = ScopeDoc(lhs, CallDoc(IdDoc("context")), body) assert to_python_script(doc) == format_script(expected) def test_print_expr_stmt_doc(): doc = ExprStmtDoc(CallDoc(IdDoc("f"), IdDoc("x"))) assert to_python_scr
ipt(doc) == format_script("f(x)") @pytest.mark.parametrize( "msg, expected", [ ( None, """ assert True """, ), ( LiteralDoc("test message"), """ assert True, "test message" """, ), ], ids=itertools.count(), ) def test_print_assert_doc(msg, expected): test = LiteralDoc(True) doc = AssertDoc(test, msg) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "value, expected", [ ( LiteralDoc(None), """ return None """, ), ( IdDoc("x"), """ return x """, ), ], ids=itertools.count(), ) def test_print_return_doc(value, expected): doc = ReturnDoc(value) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "args, decorators, return_type, body, expected", [ ( [], [], None, [], """ def func(): pass """, ), ( [AssignDoc(IdDoc("x"), rhs=None, annotation=IdDoc("int"))], [], IdDoc("int"), [], """ def func(x: int) -> int: pass """, ), ( [AssignDoc(IdDoc("x"), rhs=LiteralDoc(1), annotation=IdDoc("int"))], [], LiteralDoc(None), [], """ def func(x: int = 1) -> None: pass """, ), ( [], [IdDoc("wrap")], LiteralDoc(None), [], """ @wrap def func() -> None: pass """, ), ( [], [IdDoc("wrap_outter"), IdDoc("wrap_inner")], LiteralDoc(None), [],
""" @wrap_outter @wrap_inner def func() -> None: pass """, ), ( [ AssignDoc(IdDoc("x"), rhs=None, annotation=IdDoc("int")), AssignDoc(IdDoc("y"), rhs=LiteralDoc(1), annotation=IdDoc("int")), ], [IdDoc("wrap")], LiteralDoc(None), [], """ @wrap def func(x: int, y: int = 1) -> None: pass """, ), ( [ AssignDoc(IdDoc("x"), rhs=None, annotation=IdDoc("int")), AssignDoc(IdDoc("y"), rhs=LiteralDoc(1), annotation=IdDoc("int")), ], [IdDoc("wrap")], LiteralDoc(None), [ AssignDoc(IdDoc("y"), OperationDoc(OperationKind.Add, [IdDoc("x"), LiteralDoc(1)])), AssignDoc(IdDoc("y"), OperationDoc(OperationKind.Sub, [IdDoc("y"), LiteralDoc(1)])), ], """ @wrap def func(x: int, y: int = 1) -> None: y = x + 1 y = y - 1 """, ), ], ids=itertools.count(), ) def test_print_function_doc(args, decorators, body, return_type, expected): doc = FunctionDoc(IdDoc("func"), args, decorators, return_type, body) assert to_python_script(doc) == format_script(expected) def get_func_doc_for_class(name): args = [ AssignDoc(IdDoc("x"), rhs=None, annotation=IdDoc("int")), AssignDoc(IdDoc("y"), rhs=LiteralDoc(1), annotation=IdDoc("int")), ] body = [ AssignDoc(IdDoc("y"), OperationDoc(OperationKind.Add, [IdDoc("x"), LiteralDoc(1)])), AssignDoc(IdDoc("y"), OperationDoc(OperationKind.Sub, [IdDoc("y"), LiteralDoc(1)])), ] return FunctionDoc( name=IdDoc(name), args=args, decorators=[IdDoc("wrap")], return_type=LiteralDoc(None), body=body, ) @pytest.mark.parametrize(
"decorators, body, expected", [ ( [], [], """ class TestClass: pass """, ), ( [IdDoc("wrap")], [], """ @wrap class TestClass: pass """, ), ( [IdDoc("wrap_outter"), IdDoc("wrap_inner")], [], """ @wrap_outter @wrap_inner class TestClass: pass """, ), ( [IdDoc("wrap")], [get_func_doc_for_class("f1")], """ @wrap class TestClass: @wrap def f1(x: int, y: int = 1) -> None: y = x + 1 y = y - 1 """, ), ( [IdDoc("wrap")], [get_func_doc_for_class("f1"), get_func_doc_for_class("f2")], """ @wrap class TestClass: @wrap def f1(x: int, y: int = 1) -> None: y = x + 1 y = y - 1 @wrap def f2(x: int, y: int = 1) -> None: y = x + 1 y = y - 1 """, ), ], ids=itertools.count(), ) def test_print_class_doc(decorators, body, expected): doc = ClassDoc(IdDoc("TestClass"), decorators, body) assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "doc, comment, expected", [ ( AssignDoc(IdDoc("x"), IdDoc("y"), IdDoc("int")), "comment", """ x: int = y """, ), ( IfDoc(IdDoc("x"), [ExprStmtDoc(IdDoc("y"))], [ExprStmtDoc(IdDoc("z"))]), "comment", """ if x: y else: z """, ), (
IfDoc(IdDoc("x"), [ExprStmtDoc(IdDoc("y"))], [ExprStmtDoc(IdDoc("z"))]), "comment line 1\ncomment line 2", """ if x: y else: z """, ), ( WhileDoc( LiteralDoc(True), [ AssignDoc(IdDoc("x"), IdDoc("y")), ], ), "comment", """ while True: x = y """, ), ( ForDoc(IdDoc("x"), IdDoc("y"), []), "comment", """ for x in y: pass """, ), ( ScopeDoc(IdDoc("x"), IdDoc("y"), []), "comment", """ with y as x: pass """, ), ( ExprStmtDoc(IdDoc("x")), "comment", """ x """, ), ( AssertDoc(LiteralDoc(True)), "comment", """ assert True """, ), ( ReturnDoc(LiteralDoc(1)), "comment", """ return 1 """, ), ( get_func_doc_for_class("f"), "comment", ''' @wrap def f(x: int, y: int = 1) -> None: """ comment """ y = x + 1 y = y - 1 ''', ), ( get_func_doc_for_class("f"), "comment line 1\n\ncomment line 3", ''' @wrap def f(x: int, y: int = 1) -> None: """ comment line 1 comment line 3 """ y = x + 1 y = y - 1 ''', ), ( ClassDoc(IdDoc("Tes
tClass"), decorators=[IdDoc("wrap")], body=[]), "comment", ''' @wrap class TestClass: """ comment """ pass ''', ), ( ClassDoc(IdDoc("TestClass"), decorators=[IdDoc("wrap")], body=[]), "comment line 1\n\ncomment line 3", ''' @wrap class TestClass: """ comment line 1 comment line 3 """ pass ''', ), ], ids=itertools.count(), ) def test_print_doc_comment(doc, comment, expected): doc.comment = comment assert to_python_script(doc) == format_script(expected) @pytest.mark.parametrize( "doc", [ AssignDoc(IdDoc("x"), IdDoc("y"), IdDoc("int")), ExprStmtDoc(IdDoc("x")), AssertDoc(IdDoc("x")), ReturnDoc(IdDoc("x")), ], ) def test_print_invalid_multiline_doc_comment(doc): doc.comment = "1\n2" with pytest.raises(ValueError) as e: to_python_script(doc) assert "cannot have newline" in str(e.value) def generate_expr_precedence_test_cases(): x = IdDoc("x") y = IdDoc("y") z = IdDoc("z") def negative(a): return OperationDoc(OperationKind.USub, [a]) def invert(a): return OperationDoc(OperationKind.Invert, [a]) def not_(a): return OperationDoc(OperationKind.Not, [a]) def add(a, b): return OperationDoc(OperationKind.Add, [a, b]) def sub(a, b): return OperationDoc(OperationKind.Sub, [a, b]) def mult(a, b): return OperationDoc(OperationKind.Mult, [a, b]) def div(a, b): return OperationDoc(OperationKind.Div, [a, b]) def mod(a, b): return OperationDoc(OperationKind.Mod, [a, b]) def pow(a, b): return OperationDoc(OperationKind.Pow, [a, b]) def lshift(a, b): return OperationDoc(OperationKind.LShift, [a, b]) def bit_and(a
, b): return OperationDoc(OperationKind.BitAnd, [a, b]) def bit_or(a, b): return OperationDoc(OperationKind.BitOr, [a, b]) def bit_xor(a, b): return OperationDoc(OperationKind.BitXor, [a, b]) def lt(a, b): return OperationDoc(OperationKind.Lt, [a, b]) def eq(a, b): return OperationDoc(OperationKind.Eq, [a, b]) def not_eq(a, b): return OperationDoc(OperationKind.NotEq, [a, b]) def and_(a, b): return OperationDoc(OperationKind.And, [a, b]) def or_(a, b): return OperationDoc(OperationKind.Or, [a, b]) def if_then_else(a, b, c): return OperationDoc(OperationKind.IfThenElse, [a, b, c]) test_cases = { "attr-call-index": [ ( add(x, y).attr("test"), "(x + y).test", ), ( add(x, y.attr("test")), "x + y.test", ), ( x[z].call(y), "x[z](y)", ), ( x.call(y)[z], "x(y)[z]", ), ( x.call(y).call(z), "x(y)(z)", ), ( x.call(y).attr("test"), "x(y).test", ), ( x.attr("test").call(y), "x.test(y)", ), ( x.attr("test").attr("test2"), "x.test.test2", ), ( LambdaDoc([x], x).call(y), "(lambda x: x)(y)", ), ( add(x, y)[z][add(z, z)].attr("name"), "(x + y)[z][z + z].name", ), ], "power": [ ( pow(pow(x, y), z), "(x ** y) ** z", ), ( pow(x, pow(y, z)), "x ** y ** z", ), ( pow(negative(x), negative(y)), "(
-x) ** -y", ), ( pow(add(x, y), add(y, z)), "(x + y) ** (y + z)", ), ], "unary": [ ( invert(negative(y)), "~-y", ), ( negative(y).attr("test"), "(-y).test", ), ( negative(y.attr("test")), "-y.test", ), ( mult(negative(x), negative(y)), "-x * -y", ), ( negative(add(invert(x), negative(y))), "-(~x + -y)", ), ], "add-mult": [ ( mult(x, mult(y, z)), "x * (y * z)", ), ( mult(mult(x, y), z), "x * y * z", ), ( mult(x, add(y, z)), "x * (y + z)", ), ( mult(add(y, z), x), "(y + z) * x", ), ( add(x, mod(y, z)), "x + y % z", ), ( add(mult(y, z), x), "y * z + x", ), ( add(add(x, y), add(y, z)), "x + y + (y + z)", ), ( div(add(x, y), add(y, z)), "(x + y) / (y + z)", ), ], "shift": [ ( div(x, lshift(y, z)), "x / (y << z)", ), ( mult(lshift(y, z), x), "(y << z) * x", ), ( lshift(x, mult(y, z)), "x << y * z", ), ( lshift(mult(x, y), z), "x * y << z", ), ( lshift(mult(x, y), z), "x * y << z", ), ( lsh
ift(lshift(x, y), z), "x << y << z", ), ( lshift(x, lshift(y, z)), "x << (y << z)", ), ], "bitwise": [ ( add(bit_or(x, y), bit_or(y, z)), "(x | y) + (y | z)", ), ( bit_and(bit_or(x, y), bit_or(y, z)), "(x | y) & (y | z)", ), ( bit_or(bit_and(x, y), bit_and(y, z)), "x & y | y & z", ), ( bit_and(bit_xor(x, bit_or(y, z)), z), "(x ^ (y | z)) & z", ), ], "comparison": [ ( not_eq(add(x, y), z), "x + y != z", ), ( eq(pow(x, y), z), "x ** y == z", ), ( lt(x, div(y, z)), "x < y / z", ), ( lt(x, if_then_else(y, y, y)), "x < (y if y else y)", ), ], "boolean": [ ( not_(and_(x, y)), "not (x and y)", ), ( and_(not_(x), y), "not x and y", ), ( and_(or_(x, y), z), "(x or y) and z", ), ( or_(x, or_(y, z)), "x or (y or z)", ), ( or_(or_(x, y), z), "x or y or z", ), ( or_(and_(x, y), z), "x and y or z", ), ( and_(or_(not_(x), y), z), "(not x or y) and z", ), ( and_(lt(x, y), lt(y, z)), "x < y and y < z", ), ( or_(not_(eq(x, y)), lt(y, z)),
"not x == y or y < z", ), ( and_(if_then_else(x, y, z), x), "(y if x else z) and x", ), ( not_(if_then_else(x, y, z)), "not (y if x else z)", ), ], "if-then-else": [ ( if_then_else(x, if_then_else(y, y, y), z), "y if y else y if x else z", ), ( if_then_else(if_then_else(x, x, x), y, z), "y if (x if x else x) else z", ), ( if_then_else(x, y, if_then_else(z, z, z)), "y if x else (z if z else z)", ), ( if_then_else(lt(x, x), add(y, y), mult(z, z)), "y + y if x < x else z * z", ), ( if_then_else(LambdaDoc([x], x), LambdaDoc([y], y), LambdaDoc([z], z)), "(lambda y: y) if (lambda x: x) else (lambda z: z)", ), ], "lambda": [ ( LambdaDoc([x, y], add(z, z)), "lambda x, y: z + z", ), ( add(LambdaDoc([x, y], z), z), "(lambda x, y: z) + z", ), ( LambdaDoc([x, y], add(z, z)).call(x, y), "(lambda x, y: z + z)(x, y)", ), ( LambdaDoc([x], LambdaDoc([y], z)), "lambda x: lambda y: z", ), ], } return [ pytest.param(*args, id=f"{group_name}-{i}") for group_name, cases in test_cases.items() for i, args in enumerate(cases) ] @pytest.mark.parametrize("doc, expected", generate_expr_precedence_test_cases()) def test_expr_precedence(doc, expected): assert to_python_script(doc) == format_script(expected) if __name__ == "__main__": tvm.testing.main()
from typing
import Optional
import pytest from tvm.runtime
import ObjectPath from tvm.script.printer.doc
import ( StmtBlockDoc, ExprStmtDoc, IdDoc, OperationDoc, OperationKind, ) from tvm.script.printer.doc_printer
import to_python_script def make_path(name: str) -> ObjectPath: return ObjectPath.root().attr(name) def make_id_doc(name: str, path_name: Optional[str] = None) -> IdDoc: if path_name is None: path_name = name doc = IdDoc(name) doc.source_paths = [make_path(path_name)] return doc def format_script(s: str) -> str: """ Remove leading and trailing blank lines, and make the minimum idention 0 """ s = s.strip("\n") non_empty_lines = [line for line in s.splitlines() if line and not line.isspace()] if not non_empty_lines: return "\n" line_indents = [len(line) - len(line.lstrip(" ")) for line in non_empty_lines] spaces_to_remove = min(line_indents) cleaned_lines = "\n".join(line[spaces_to_remove:] for line in s.splitlines()) if not cleaned_lines.endswith("\n"): cleaned_lines += "\n" return cleaned_lines def test_underline_basic(): doc = StmtBlockDoc( [ ExprStmtDoc(make_id_doc("foo")), ExprStmtDoc(OperationDoc(OperationKind.Add, [make_id_doc("bar"), make_id_doc("baz")])), ExprStmtDoc(make_id_doc("qux")), ] ) assert to_python_script(doc, path_to_underline=make_path("baz")) == format_script( """ foo bar + baz ^^^ qux """ ) def test_underline_multiple_spans(): doc = StmtBlockDoc( [ ExprStmtDoc(make_id_doc("foo")), ExprStmtDoc(make_id_doc("bar")), ExprStmtDoc(OperationDoc(OperationKind.Add, [make_id_doc("foo"), make_id_doc("foo")])), ] ) assert to_python_script(doc, path_to_underline=make_path("foo")) == format_script( """ foo ^^^ bar foo + foo ^^^ ^^^ """ ) def test_underline_multiple_spans_with_line_numbers(): doc = StmtBlockDoc( [ ExprStmtDoc(make_id_doc("foo")), ExprStmtDoc(make_id_doc("bar")), ExprStmtDoc(OperationDoc(OperationKi
nd.Add, [make_id_doc("foo"), make_id_doc("foo")])), ] ) assert to_python_script( doc, print_line_numbers=True, path_to_underline=make_path("foo") ) == format_script( """ 1 foo ^^^ 2 bar 3 foo + foo ^^^ ^^^ """ ) def test_underline_multiline(): doc = StmtBlockDoc( [ ExprStmtDoc(IdDoc("foo")), ExprStmtDoc(IdDoc("bar")), ] ) doc.source_paths = [make_path("whole_doc")] assert to_python_script(doc, path_to_underline=make_path("whole_doc")) == format_script( """ foo ^^^ bar ^^^ """ ) @pytest.mark.parametrize( "to_underline, expected_text", [ ( [0], """ x0 ^^ x1 x2 (... 7 lines skipped ...) """, ), ( [1], """ x0 x1 ^^ x2 x3 (... 6 lines skipped ...) """, ), ( [3], """ x0 x1 x2 x3 ^^ x4 x5 (... 4 lines skipped ...) """, ), ( [4], """ (... 2 lines skipped ...) x2 x3 x4 ^^ x5 x6 (... 3 lines skipped ...) """, ), ( [6], """ (... 4 lines skipped ...) x4 x5 x6 ^^ x7 x8 x9 """, ), ( [9], """ (... 7 lines skipped ...) x7 x8 x9
^^ """, ), ( [0, 9], """ x0 ^^ x1 x2 (... 4 lines skipped ...) x7 x8 x9 ^^ """, ), ( [0, 3, 9], """ x0 ^^ x1 x2 x3 ^^ x4 x5 x6 x7 x8 x9 ^^ """, ), ( [0, 6, 9], """ x0 ^^ x1 x2 x3 x4 x5 x6 ^^ x7 x8 x9 ^^ """, ), ( [33], """ x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 """, ), ], ) def test_print_two_context_lines(to_underline, expected_text): doc = StmtBlockDoc( [ExprStmtDoc(make_id_doc(f"x{i}", "yes" if i in to_underline else "no")) for i in range(10)] ) result = to_python_script(doc, num_context_lines=2, path_to_underline=make_path("yes")) assert result == format_script(expected_text) def test_underline_and_print_line_numbers(): doc = StmtBlockDoc([ExprStmtDoc(make_id_doc(f"line{i + 1}")) for i in range(12)]) result = to_python_script(doc, print_line_numbers=True, path_to_underline=make_path("line6")) assert result == format_script( """ 1 line1 2 line2 3 line3 4 line4 5 line5 6 line6 ^^^^^ 7 line7 8 line8 9 line
9 10 line10 11 line11 12 line12 """ ) def test_underline_and_print_line_numbers_with_context(): doc = StmtBlockDoc([ExprStmtDoc(make_id_doc(f"line{i + 1}")) for i in range(12)]) result = to_python_script( doc, print_line_numbers=True, num_context_lines=2, path_to_underline=make_path("line8") ) assert result == format_script( """ (... 5 lines skipped ...) 6 line6 7 line7 8 line8 ^^^^^ 9 line9 10 line10 (... 2 lines skipped ...) """ ) def test_underline_based_on_path_prefix(): doc = StmtBlockDoc([ExprStmtDoc(make_id_doc("foo")), ExprStmtDoc(make_id_doc("bar"))]) result = to_python_script(doc, path_to_underline=make_path("foo").attr("x").attr("y")) assert result == format_script( """ foo ^^^ bar """ ) def test_longer_prefix_must_win(): foo_x = IdDoc("foo_x") foo_x.source_paths = [make_path("foo").attr("x")] doc = StmtBlockDoc( [ExprStmtDoc(make_id_doc("foo")), ExprStmtDoc(make_id_doc("bar")), ExprStmtDoc(foo_x)] ) result = to_python_script(doc, path_to_underline=make_path("foo").attr("x").attr("y")) assert result == format_script( """ foo bar foo_x ^^^^^ """ )
""" This file tests the FFI binding of script.printer.VarTable. These only make sure parameter can be passed to the C++ functions correctly. The test for the functionality of VarTable is in C++. """ from tvm.runtime
import ObjectPath from tvm.script.printer.doc
import LiteralDoc from tvm.script.printer.frame
import VarDefFrame from tvm.script.printer.var_table
import VarTable from tvm.tir
import Var def test_define(): var_table = VarTable() var_name = "a" var_obj = Var(var_name, dtype="int32") object_path = ObjectPath.root().attr("a") frame = VarDefFrame() id_doc = var_table.define(var_obj, var_name, object_path, frame) assert id_doc.name == "a" assert list(id_doc.source_paths) == [object_path] id_doc = var_table.get_var_doc(var_obj, object_path) assert id_doc.name == "a" assert list(id_doc.source_paths) == [object_path] def test_define_by_doc(): var_table = VarTable() var_name = "a" var_obj = Var(var_name, dtype="int32") object_path = ObjectPath.root().attr("a") frame = VarDefFrame() var_table.define_by_doc(var_obj, lambda: LiteralDoc(var_name), frame) var_doc = var_table.get_var_doc(var_obj, object_path) assert isinstance(var_doc, LiteralDoc) assert var_doc.value == var_name assert list(var_doc.source_paths) == [object_path] def test_is_var_defined(): var_table = VarTable() a = Var("a", dtype="int32") object_path = ObjectPath.root().attr("a") frame = VarDefFrame() var_table.define(a, "a", object_path, frame) assert var_table.is_var_defined(a) assert a in var_table def test_var_out_of_scope(): var_table = VarTable() var_name = "a" var_obj = Var(var_name, dtype="int32") object_path = ObjectPath.root().attr("a") frame = VarDefFrame() var_table.define(var_obj, var_name, object_path, frame) with frame: assert var_obj in var_table assert var_obj not in var_table assert var_table.get_var_doc(var_obj, object_path) is None
# 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. import numpy import tvm from tvm.script import tir as T # This numpy array is used to test the comparison between the global objects and the # `tvm.script.tir` submodule. np_array = numpy.array([0, 1, 2, 3]) @T.prim_func def matmul(a: T.handle, b: T.handle, c: T.handle) -> None: A = T.match_buffer(a, [128, 128]) B = T.match_buffer(b, [128, 128]) C = T.match_buffer(c, [128, 128]) for i, j, k in T.grid(128, 128, 128): with T.block("update"): vi, vj, vk = T.axis.remap("SSR", [i, j, k]) with T.init(): C[vi, vj] = T.float32(0) C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk] def test_multi_element_array_in_outmost_namespace(): func = matmul rt_func = tvm.script.from_source(func.script(show_meta=True)) tvm.ir.assert_structural_equal(func, rt_func) if __name__ == "__main__": test_multi_element_array_in_outmost_namespace()
import sys
import pytest
import tvm
import tvm.testing from tvm
import tir from tvm.script
import tir as T
import numpy as np def opt_gemm_normalize(): @tvm.script.ir_module class Module: @T.prim_func def mmult(A: T.handle, B: T.handle, C: T.handle) -> None: T.func_attr({"global_symbol": "mmult", "tir.noalias": True}) C_global = T.buffer_decl([1024, 1024], elem_offset=0, align=64, offset_factor=1) packedB = T.buffer_decl([32, 1024, 32], elem_offset=0, align=64, offset_factor=1) A_1 = T.match_buffer(A, [1024, 1024], elem_offset=0, align=64, offset_factor=1) B_1 = T.match_buffer(B, [1024, 1024], elem_offset=0, align=64, offset_factor=1) C_1 = T.match_buffer(C, [1024, 1024], elem_offset=0, align=64, offset_factor=1) T.realize(packedB[0:32, 0:1024, 0:32], "") for x in T.parallel(0, 32): for y in T.serial(0, 1024): for z in T.vectorized(0, 32): packedB[x, y, z] = B_1[y, ((x * 32) + z)] T.realize(C_1[0:1024, 0:1024], "") for x_outer in T.parallel(0, 32): for y_outer in T.serial(0, 32): T.realize( C_global[ (x_outer * 32) : ((x_outer * 32) + 32), (y_outer * 32) : ((y_outer * 32) + 32), ], "global", ) for x_c_init in T.serial(0, 32): for y_c_init in T.vectorized(0, 32): C_global[ (x_c_init + (x_outer * 32)), (y_c_init + (y_outer * 32)) ] = T.float32(0) for k_outer in T.serial(0, 256): for x_c in T.serial(0, 32): for k_inner in T.unroll(0, 4): for y_c in T.vectorized(0, 32): C_global[ (x_c + (x_outer
* 32)), (y_c + (y_outer * 32)) ] = C_global[(x_c + (x_outer * 32)), (y_c + (y_outer * 32))] + ( A_1[(x_c + (x_outer * 32)), (k_inner + (k_outer * 4))] * packedB[ T.floordiv((y_c + (y_outer * 32)), 32), (k_inner + (k_outer * 4)), T.floormod((y_c + (y_outer * 32)), 32), ] ) for x_inner in T.serial(0, 32): for y_inner in T.serial(0, 32): C_1[(x_inner + (x_outer * 32)), (y_inner + (y_outer * 32))] = C_global[ (x_inner + (x_outer * 32)), (y_inner + (y_outer * 32)) ] return Module def opt_gemm_lower(): @tvm.script.ir_module class Module: @T.prim_func def mmult(A: T.handle, B: T.handle, C: T.handle) -> None: T.func_attr({"global_symbol": "mmult", "tir.noalias": True}) A_1 = T.match_buffer(A, [16384], elem_offset=0, align=64, offset_factor=1) B_1 = T.match_buffer(B, [1024, 1024], elem_offset=0, align=64, offset_factor=1) C_1 = T.match_buffer(C, [16384], elem_offset=0, align=64, offset_factor=1) packedB_data = T.allocate([32768], "float32", "global") packedB = T.buffer_decl( shape=[32768], dtype="float32", scope="global", data=packedB_data ) for x in T.parallel(0, 32): for y in T.serial(0, 1024): packedB[T.ramp(((x * 32768) + (y * 32)), 1, 32)] = B_1[y, T.ramp(x * 32, 1, 32)] for x_outer in T.parallel(0, 32): C_global_data = T.allocate([1024], "float32", "global") C_global = T.buffer_decl( shape=[1024], dtype=
"float32", scope="global", data=C_global_data ) for y_outer in T.serial(0, 32): for x_c_init in T.serial(0, 32): C_global[T.ramp((x_c_init * 32), 1, 32)] = T.broadcast(T.float32(0), 32) for k_outer in T.serial(0, 256): for x_c in T.serial(0, 32): C_global[T.ramp((x_c * 32), 1, 32)] = C_global[ T.ramp((x_c * 32), 1, 32) ] + ( T.broadcast( A_1[ (((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)), ], 32, ) * packedB[T.ramp(((y_outer * 32768) + (k_outer * 128)), 1, 32)] ) C_global[T.ramp((x_c * 32), 1, 32)] = C_global[ T.ramp((x_c * 32), 1, 32) ] + ( T.broadcast( A_1[ ((((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)) + 1), ], 32, ) * packedB[ T.ramp((((y_outer * 32768) + (k_outer * 128)) + 32), 1, 32) ] ) C_global[T.ramp((x_c * 32), 1, 32)] = C_global[ T.ramp((x_c * 32), 1, 32) ] + ( T.broadcast( A_1[ ((((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)) + 2), ],
32, ) * packedB[ T.ramp((((y_outer * 32768) + (k_outer * 128)) + 64), 1, 32) ] ) C_global[T.ramp((x_c * 32), 1, 32)] = C_global[ T.ramp((x_c * 32), 1, 32) ] + ( T.broadcast( A_1[ ((((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4)) + 3), ], 32, ) * packedB[ T.ramp((((y_outer * 32768) + (k_outer * 128)) + 96), 1, 32) ] ) for x_inner in T.serial(0, 32): for y_inner in T.serial(0, 32): C_1[ ( (((x_outer * 32768) + (x_inner * 1024)) + (y_outer * 32)) + y_inner ) ] = C_global[((x_inner * 32) + y_inner)] return Module def opt_gemm_mod_host(): @tvm.script.ir_module class Module: @T.prim_func def mmult( args: T.handle, arg_type_ids: T.handle, num_args: T.int32, out_ret_value: T.handle, out_ret_tcode: T.handle, ) -> T.int32: T.func_attr( { "tir.noalias": True, "global_symbol": "mmult", "tir.is_entry_func": True, "calling_conv": 1, } ) buf_type_ids = T.match_buffer(arg_type_ids, [3], dtype="int32") packedB = T.buffer_decl([32768
], dtype="float32") C_global = T.buffer_decl([1024], dtype="float32") assert num_args == 3, "mmult: num_args should be 3" arg0: T.handle = T.tvm_struct_get(args, 0, 12, dtype="handle") arg0_code: T.int32 = buf_type_ids[0] arg1: T.handle = T.tvm_struct_get(args, 1, 12, dtype="handle") arg1_code: T.int32 = buf_type_ids[1] arg2: T.handle = T.tvm_struct_get(args, 2, 12, dtype="handle") arg2_code: T.int32 = buf_type_ids[2] A_data: T.Ptr[T.int32] = T.tvm_struct_get(arg0, 0, 1, dtype="handle") T.attr(A_data, "storage_alignment", 128) A = T.buffer_decl([1024 * 1024], dtype="int32", data=A_data) buf0_shape_data: T.Ptr[T.int32] = T.tvm_struct_get(arg0, 0, 2, dtype="handle") buf0_shape = T.buffer_decl([2], dtype="int32", data=buf0_shape_data) buf0_strides_data: T.Ptr[T.int32] = T.tvm_struct_get(arg0, 0, 3, dtype="handle") buf0_strides = T.buffer_decl([2], dtype="int32", data=buf0_strides_data) dev_id: T.int32 = T.tvm_struct_get(arg0, 0, 9, dtype="int32") B_data: T.Ptr[T.int32] = T.tvm_struct_get(arg1, 0, 1, dtype="handle") T.attr(B_data, "storage_alignment", 128) B = T.buffer_decl([1024 * 1024], dtype="int32", data=B_data) buf1_shape_data: T.Ptr[T.int32] = T.tvm_struct_get(arg1, 0, 2, dtype="handle") buf1_shape = T.buffer_decl([2], dtype="int32", data=buf1_shape_data) buf1_strides_data: T.Ptr[T.int32] = T.tvm_struct_get(arg1, 0, 3, dtype="handle") buf1_strides = T.buffer_decl([2], dtype="int32", data=buf1_strides_data) C_data: T.Ptr[T.int32] = T.tvm_struct_get(arg2, 0, 1, dtype="handle") T.attr(C_data, "storage_alignment", 128) C = T.buffer_decl([1024 * 1024], dtype="int32", data=C_data) buf2_shape_data: T.Ptr[T.int32] = T.tvm_struct_get(arg2, 0, 2, d
type="handle") buf2_shape = T.buffer_decl([2], dtype="int32", data=buf2_shape_data) buf2_strides_data: T.Ptr[T.int32] = T.tvm_struct_get(arg2, 0, 3, dtype="handle") buf2_strides = T.buffer_decl([2], dtype="int32", data=buf2_strides_data) assert (((arg0_code == 3) or (arg0_code == 13)) or (arg0_code == 7)) or ( arg0_code == 4 ), "mmult: Expect arg[0] to be pointer" assert (((arg1_code == 3) or (arg1_code == 13)) or (arg1_code == 7)) or ( arg1_code == 4 ), "mmult: Expect arg[1] to be pointer" assert (((arg2_code == 3) or (arg2_code == 13)) or (arg2_code == 7)) or ( arg2_code == 4 ), "mmult: Expect arg[2] to be pointer" assert 2 == T.tvm_struct_get( arg0, 0, 4, dtype="int32" ), "arg0.ndim is expected to equal 2" assert 2 == T.tvm_struct_get( arg0, 0, 4, dtype="int32" ), "arg0.ndim is expected to equal 2" assert ( (T.tvm_struct_get(arg0, 0, 5, dtype="uint8") == T.uint8(2)) and (T.tvm_struct_get(arg0, 0, 6, dtype="uint8") == T.uint8(32)) ) and ( T.tvm_struct_get(arg0, 0, 7, dtype="uint16") == T.uint16(1) ), "arg0.dtype is expected to be float32" assert 1024 == T.cast( buf0_shape[0], "int32" ), "Argument arg0.shape[0] has an unsatisfied constraint" assert 1024 == T.cast( buf0_shape[1], "int32" ), "Argument arg0.shape[1] has an unsatisfied constraint" if not (T.isnullptr(buf0_strides.data, dtype="bool")): assert (1 == T.cast(buf0_strides[1], "int32")) and ( 1024 == T.cast(buf0_strides[0], "int32") ), "arg0.strides: expected to be compact array" T.evaluate(0) assert T.uint64(0) == T.tvm_struct_get( arg0, 0, 8, dtype="uint
64" ), "Argument arg0.byte_offset has an unsatisfied constraint" assert 1 == T.tvm_struct_get( arg0, 0, 10, dtype="int32" ), "Argument arg0.device_type has an unsatisfied constraint" assert 2 == T.tvm_struct_get( arg1, 0, 4, dtype="int32" ), "arg1.ndim is expected to equal 2" assert 2 == T.tvm_struct_get( arg1, 0, 4, dtype="int32" ), "arg1.ndim is expected to equal 2" assert ( (T.tvm_struct_get(arg1, 0, 5, dtype="uint8") == T.uint8(2)) and (T.tvm_struct_get(arg1, 0, 6, dtype="uint8") == T.uint8(32)) ) and ( T.tvm_struct_get(arg1, 0, 7, dtype="uint16") == T.uint16(1) ), "arg1.dtype is expected to be float32" assert 1024 == T.cast( buf1_shape[0], "int32" ), "Argument arg1.shape[0] has an unsatisfied constraint" assert 1024 == T.cast( buf1_shape[1], "int32" ), "Argument arg1.shape[1] has an unsatisfied constraint" if not (T.isnullptr(buf1_strides.data, dtype="bool")): assert (1 == T.cast(buf1_strides[1], "int32")) and ( 1024 == T.cast(buf1_strides[0], "int32") ), "arg1.strides: expected to be compact array" T.evaluate(0) assert T.uint64(0) == T.tvm_struct_get( arg1, 0, 8, dtype="uint64" ), "Argument arg1.byte_offset has an unsatisfied constraint" assert 1 == T.tvm_struct_get( arg1, 0, 10, dtype="int32" ), "Argument arg1.device_type has an unsatisfied constraint" assert dev_id == T.tvm_struct_get( arg1, 0, 9, dtype="int32" ), "Argument arg1.device_id has an unsatisfied constraint" assert 2 == T.tvm_struct_get( arg2, 0, 4, dtype="int32" ), "arg2.ndim is expected to equal 2" assert
2 == T.tvm_struct_get( arg2, 0, 4, dtype="int32" ), "arg2.ndim is expected to equal 2" assert ( (T.tvm_struct_get(arg2, 0, 5, dtype="uint8") == T.uint8(2)) and (T.tvm_struct_get(arg2, 0, 6, dtype="uint8") == T.uint8(32)) ) and ( T.tvm_struct_get(arg2, 0, 7, dtype="uint16") == T.uint16(1) ), "arg2.dtype is expected to be float32" assert 1024 == T.cast( buf2_shape[0], "int32" ), "Argument arg2.shape[0] has an unsatisfied constraint" assert 1024 == T.cast( buf2_shape[1], "int32" ), "Argument arg2.shape[1] has an unsatisfied constraint" if not (T.isnullptr(buf2_strides.data, dtype="bool")): assert (1 == T.cast(buf2_strides[1], "int32")) and ( 1024 == T.cast(buf2_strides[0], "int32") ), "arg2.strides: expected to be compact array" T.evaluate(0) assert T.uint64(0) == T.tvm_struct_get( arg2, 0, 8, dtype="uint64" ), "Argument arg2.byte_offset has an unsatisfied constraint" assert 1 == T.tvm_struct_get( arg2, 0, 10, dtype="int32" ), "Argument arg2.device_type has an unsatisfied constraint" assert dev_id == T.tvm_struct_get( arg2, 0, 9, dtype="int32" ), "Argument arg2.device_id has an unsatisfied constraint" T.attr(0, "compute_scope", "mmult_compute_") T.attr(packedB.data, "storage_scope", "global") T.attr(packedB.data, "storage_alignment", 128) with T.let( packedB.data, T.TVMBackendAllocWorkspace(1, dev_id, T.uint64(4194304), 2, 32, dtype="handle"), ): if T.isnullptr(packedB.data, dtype="bool"): T.evaluate(T.tvm_throw_last_error(dtype="int32")) for x in T.parallel(0, 32): for
y in T.serial(0, 1024): packedB[T.ramp(((x * 32768) + (y * 32)), 1, 32)] = B[ T.ramp(((y * 1024) + (x * 32)), 1, 32) ] for x_outer in T.parallel(0, 32): T.attr(C_global.data, "storage_scope", "global") T.attr(C_global.data, "storage_alignment", 128) with T.let( C_global.data, T.TVMBackendAllocWorkspace( 1, dev_id, T.uint64(4096), 2, 32, dtype="handle" ), ): if T.isnullptr(C_global.data, dtype="bool"): T.evaluate(T.tvm_throw_last_error(dtype="int32")) for y_outer in T.serial(0, 32): for x_c_init in T.serial(0, 32): C_global[T.ramp((x_c_init * 32), 1, 32)] = T.broadcast( T.float32(0), 32 ) for k_outer in T.serial(0, 256): for x_c in T.serial(0, 32): C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin( T.uint32(97), T.uint32(3), T.broadcast( A[ ( ((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4) ), ], 32, ), packedB[ T.ramp(((y_outer * 32768) + (k_outer * 128)), 1, 32)
], C_global[T.ramp((x_c * 32), 1, 32)], dtype="float32x32", ) C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin( T.uint32(97), T.uint32(3), T.broadcast( A[ ( ( ((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4) ) + 1 ), ], 32, ), packedB[ T.ramp( (((y_outer * 32768) + (k_outer * 128)) + 32), 1, 32 ) ], C_global[T.ramp((x_c * 32), 1, 32)], dtype="float32x32", ) C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin( T.uint32(97), T.uint32(3), T.broadcast( A[ ( ( ((x_outer * 32768) + (x_c * 1024))
+ (k_outer * 4) ) + 2 ), ], 32, ), packedB[ T.ramp( (((y_outer * 32768) + (k_outer * 128)) + 64), 1, 32 ) ], C_global[T.ramp((x_c * 32), 1, 32)], dtype="float32x32", ) C_global[T.ramp((x_c * 32), 1, 32)] = T.call_llvm_pure_intrin( T.uint32(97), T.uint32(3), T.broadcast( A[ ( ( ((x_outer * 32768) + (x_c * 1024)) + (k_outer * 4) ) + 3 ), ], 32, ), packedB[ T.ramp( (((y_outer * 32768) + (k_outer * 128)) + 96), 1, 32 ) ], C_global[T.
ramp((x_c * 32), 1, 32)], dtype="float32x32", ) for x_inner in T.serial(0, 32): for y_inner in T.serial(0, 32): C[ ( ( ((x_outer * 32768) + (x_inner * 1024)) + (y_outer * 32) ) + y_inner ) ] = C_global[((x_inner * 32) + y_inner)] if T.TVMBackendFreeWorkspace(1, dev_id, C_global.data, dtype="int32") != 0: T.evaluate(T.tvm_throw_last_error(dtype="int32")) if T.TVMBackendFreeWorkspace(1, dev_id, packedB.data, dtype="int32") != 0: T.evaluate(T.tvm_throw_last_error(dtype="int32")) return Module def opt_conv_tensorcore_normalize(): @T.prim_func def func(A: T.handle, W: T.handle, Conv: T.handle) -> None: T.func_attr({"global_symbol": "default_function", "tir.noalias": True}) bx = T.env_thread("blockIdx.x") by = T.env_thread("blockIdx.y") bz = T.env_thread("blockIdx.z") tx = T.env_thread("threadIdx.x") ty = T.env_thread("threadIdx.y") tz = T.env_thread("threadIdx.z") Apad_shared = T.buffer_decl( [16, 16, 16, 16, 16, 16], dtype="float16", elem_offset=0, align=64, offset_factor=1 ) Apad_shared_wmma_matrix_a = T.buffer_decl( [16, 16, 16, 16, 16, 16], dtype="float16", elem_offset=0, align=64, offset_factor=1 ) BA = T.buffer_decl( [16, 16], dtype="float16", scope="wmma.matrix_a", align=32, offset_factor=256 ) BB = T.buffer_decl( [16, 16], dtype="float
16", scope="wmma.matrix_b", align=32, offset_factor=256 ) BC = T.buffer_decl([16, 16], scope="wmma.accumulator", align=32, offset_factor=256) Conv_wmma_accumulator = T.buffer_decl( [16, 14, 14, 32, 16, 16], elem_offset=0, align=64, offset_factor=1 ) W_shared = T.buffer_decl( [3, 3, 16, 32, 16, 16], dtype="float16", elem_offset=0, align=64, offset_factor=1 ) W_shared_wmma_matrix_b = T.buffer_decl( [3, 3, 16, 32, 16, 16], dtype="float16", elem_offset=0, align=64, offset_factor=1 ) buffer = T.buffer_decl( [16, 16], dtype="float16", scope="shared", align=32, offset_factor=256 ) buffer_1 = T.buffer_decl( [16, 16], dtype="float16", scope="wmma.matrix_a", align=32, offset_factor=256 ) buffer_2 = T.buffer_decl( [16, 16], dtype="float16", scope="shared", align=32, offset_factor=256 ) buffer_3 = T.buffer_decl( [16, 16], dtype="float16", scope="wmma.matrix_b", align=32, offset_factor=256 ) buffer_4 = T.buffer_decl([16, 16], scope="wmma.accumulator", align=32, offset_factor=256) buffer_5 = T.buffer_decl([16, 16], align=32, offset_factor=256) A_1 = T.match_buffer( A, [16, 14, 14, 16, 16, 16], dtype="float16", elem_offset=0, align=64, offset_factor=1 ) W_1 = T.match_buffer( W, [3, 3, 16, 32, 16, 16], dtype="float16", elem_offset=0, align=64, offset_factor=1 ) Conv_1 = T.match_buffer( Conv, [16, 14, 14, 32, 16, 16], elem_offset=0, align=64, offset_factor=1 ) T.realize(Conv_1[0:16, 0:14, 0:14, 0:32, 0:16, 0:16], "") T.launch_thread(bz, 196) T.launch_thread(bx, 2) T.launch_thread(by, 4) T.launch_thread(ty, 4) T.launch_thread(tz, 2) T.realize( Conv_wmma_accumulator[ ((bx * 8) + (ty * 2)) : (((bx * 8) + (ty * 2)) + 2),
T.floordiv(bz, 14) : (T.floordiv(bz, 14) + 1), T.floormod(bz, 14) : (T.floormod(bz, 14) + 1), ((by * 8) + (tz * 4)) : (((by * 8) + (tz * 4)) + 4), 0:16, 0:16, ], "wmma.accumulator", ) for n_c_init in T.serial(0, 2): for o_c_init in T.serial(0, 4): T.attr( [BC, Conv_wmma_accumulator], "buffer_bind_scope", T.tvm_tuple( (n_c_init + ((bx * 8) + (ty * 2))), 1, T.floordiv(bz, 14), 1, T.floormod(bz, 14), 1, (o_c_init + ((by * 8) + (tz * 4))), 1, 0, 16, 0, 16, dtype="handle", ), ) T.evaluate( T.tvm_fill_fragment( BC.data, 16, 16, 16, T.floordiv(BC.elem_offset, 256), T.float32(0), dtype="handle", ) ) for ic_outer in T.serial(0, 8): for kh in T.serial(0, 3): T.realize( Apad_shared[ (bx * 8) : ((bx * 8) + 8), (T.floordiv(bz, 14) + kh) : ((T.floordiv(bz, 14) + kh) + 1), T.floormod(bz, 14) : (T.floormod(bz, 14) + 3), (ic_outer * 2) : ((ic_outer * 2) + 2), 0:16, 0:16, ], "shared", ) for ax2 in T.serial(0, 3): for ax3 in T.serial(0, 2): for ax4_ax5_fu
sed_outer in T.serial(0, 8): T.launch_thread(tx, 32) Apad_shared[ ((tz + (ty * 2)) + (bx * 8)), (T.floordiv(bz, 14) + kh), (ax2 + T.floormod(bz, 14)), (ax3 + (ic_outer * 2)), T.floordiv((tx + (ax4_ax5_fused_outer * 32)), 16), T.floormod((tx + (ax4_ax5_fused_outer * 32)), 16), ] = T.if_then_else( ( ( ( ((T.floordiv(bz, 14) + kh) >= 1) and (((T.floordiv(bz, 14) + kh) - 1) < 14) ) and ((ax2 + T.floormod(bz, 14)) >= 1) ) and (((ax2 + T.floormod(bz, 14)) - 1) < 14) ), A_1[ ((tz + (ty * 2)) + (bx * 8)), ((T.floordiv(bz, 14) + kh) - 1), ((ax2 + T.floormod(bz, 14)) - 1), (ax3 + (ic_outer * 2)), T.floordiv((tx + (ax4_ax5_fused_outer * 32)), 16), T.floormod((tx + (ax4_ax5_fused_outer * 32)), 16), ], T.float16(0), dtype="float16", ) T.realize( W_shared[ kh : (kh + 1), 0:3, (ic_outer * 2) : ((ic_outer * 2) + 2), (by * 8) : ((by * 8) + 8), 0:16,
0:16, ], "shared", ) for ax1 in T.serial(0, 3): for ax2_1 in T.serial(0, 2): T.launch_thread(tx, 32) for ax4_ax5_fused_inner in T.vectorized(0, 8): W_shared[ kh, ax1, (ax2_1 + (ic_outer * 2)), ((tz + (ty * 2)) + (by * 8)), T.floordiv((ax4_ax5_fused_inner + (tx * 8)), 16), T.floormod((ax4_ax5_fused_inner + (tx * 8)), 16), ] = W_1[ kh, ax1, (ax2_1 + (ic_outer * 2)), ((tz + (ty * 2)) + (by * 8)), T.floordiv((ax4_ax5_fused_inner + (tx * 8)), 16), T.floormod((ax4_ax5_fused_inner + (tx * 8)), 16), ] for ic_inner in T.serial(0, 2): for kw in T.serial(0, 3): T.realize( Apad_shared_wmma_matrix_a[ ((bx * 8) + (ty * 2)) : (((bx * 8) + (ty * 2)) + 2), (T.floordiv(bz, 14) + kh) : ((T.floordiv(bz, 14) + kh) + 1), (kw + T.floormod(bz, 14)) : ((kw + T.floormod(bz, 14)) + 1), ((ic_outer * 2) + ic_inner) : (((ic_outer * 2) + ic_inner) + 1), 0:16, 0:16, ], "wmma.matrix_a", ) for ax0 in T.serial(0, 2): T.attr( [buffer, Apad_shared], "buffer_bind_scope",
T.tvm_tuple( (ax0 + ((bx * 8) + (ty * 2))), 1, (T.floordiv(bz, 14) + kh), 1, (kw + T.floormod(bz, 14)), 1, ((ic_outer * 2) + ic_inner), 1, 0, 16, 0, 16, dtype="handle", ), ) T.attr( [buffer_1, Apad_shared_wmma_matrix_a], "buffer_bind_scope", T.tvm_tuple( (ax0 + ((bx * 8) + (ty * 2))), 1, (T.floordiv(bz, 14) + kh), 1, (kw + T.floormod(bz, 14)), 1, ((ic_outer * 2) + ic_inner), 1, 0, 16, 0, 16, dtype="handle", ), ) T.evaluate( T.tvm_load_matrix_sync( buffer_1.data, 16, 16, 16, T.floordiv(buffer_1.elem_offset, 256), T.tvm_access_ptr(
T.type_annotation(dtype="float16"), buffer.data, buffer.elem_offset, 256, 1, dtype="handle", ), 16, "row_major", dtype="handle", ) ) T.realize( W_shared_wmma_matrix_b[ kh : (kh + 1), kw : (kw + 1), ((ic_outer * 2) + ic_inner) : (((ic_outer * 2) + ic_inner) + 1), ((by * 8) + (tz * 4)) : (((by * 8) + (tz * 4)) + 4), 0:16, 0:16, ], "wmma.matrix_b", ) for ax3_1 in T.serial(0, 4): T.attr( [buffer_2, W_shared], "buffer_bind_scope", T.tvm_tuple( kh, 1, kw, 1, ((ic_outer * 2) + ic_inner), 1, (ax3_1 + ((by * 8) + (tz * 4))), 1, 0, 16, 0, 16, dtype="handle", ), ) T.attr( [buffer_3,
W_shared_wmma_matrix_b], "buffer_bind_scope", T.tvm_tuple( kh, 1, kw, 1, ((ic_outer * 2) + ic_inner), 1, (ax3_1 + ((by * 8) + (tz * 4))), 1, 0, 16, 0, 16, dtype="handle", ), ) T.evaluate( T.tvm_load_matrix_sync( buffer_3.data, 16, 16, 16, T.floordiv(buffer_3.elem_offset, 256), T.tvm_access_ptr( T.type_annotation(dtype="float16"), buffer_2.data, buffer_2.elem_offset, 256, 1, dtype="handle", ), 16, "row_major", dtype="handle", ) ) for n_c in T.serial(0, 2): for o_c in T.serial(0, 4): T.attr( [BA, Apad_shared_wmma_matrix_a], "buffer_bind_scope",
T.tvm_tuple( (n_c + ((bx * 8) + (ty * 2))), 1, (T.floordiv(bz, 14) + kh), 1, (T.floormod(bz, 14) + kw), 1, ((ic_outer * 2) + ic_inner), 1, 0, 16, 0, 16, dtype="handle", ), ) T.attr( [BB, W_shared_wmma_matrix_b], "buffer_bind_scope", T.tvm_tuple( kh, 1, kw, 1, ((ic_outer * 2) + ic_inner), 1, (o_c + ((by * 8) + (tz * 4))), 1, 0, 16, 0, 16, dtype="handle", ), ) T.attr( [BC, Conv_wmma_accumulator], "buffer_bind_scope", T.tvm_tuple( (n_c + ((bx * 8) + (ty * 2))), 1, T
.floordiv(bz, 14), 1, T.floormod(bz, 14), 1, (o_c + ((by * 8) + (tz * 4))), 1, 0, 16, 0, 16, dtype="handle", ), ) T.evaluate( T.tvm_mma_sync( BC.data, T.floordiv(BC.elem_offset, 256), BA.data, T.floordiv(BA.elem_offset, 256), BB.data, T.floordiv(BB.elem_offset, 256), BC.data, T.floordiv(BC.elem_offset, 256), dtype="handle", ) ) for n_inner in T.serial(0, 2): for o_inner in T.serial(0, 4): T.attr( [buffer_4, Conv_wmma_accumulator], "buffer_bind_scope", T.tvm_tuple( ((((bx * 4) + ty) * 2) + n_inner), 1, T.floordiv(bz, 14), 1, T.floormod(bz, 14), 1, ((((by * 2) + tz) * 4) + o_inner), 1, 0, 16, 0, 16, dtype="handle", ), )
T.attr( [buffer_5, Conv_1], "buffer_bind_scope", T.tvm_tuple( ((((bx * 4) + ty) * 2) + n_inner), 1, T.floordiv(bz, 14), 1, T.floormod(bz, 14), 1, ((((by * 2) + tz) * 4) + o_inner), 1, 0, 16, 0, 16, dtype="handle", ), ) T.evaluate( T.tvm_store_matrix_sync( buffer_4.data, 16, 16, 16, T.floordiv(buffer_4.elem_offset, 256), T.tvm_access_ptr( T.type_annotation(dtype="float32"), buffer_5.data, buffer_5.elem_offset, 256, 2, dtype="handle", ), 16, "row_major", dtype="handle", ) ) return func def opt_conv_tensorcore_lower(): @T.prim_func def func( A: T.Buffer[(16, 14, 14, 16, 16, 16), "float16"], W: T.Buffer[(3, 3, 16, 32, 16, 16), "float16"], Conv: T.Buffer[(16, 14, 14, 32, 16, 16), "float32"], ) -> None: T.func_attr({"global_symbol": "default_function", "tir.noalias": True}) A_1 = T.buffer_decl([12845056], dtype="float16", data=A.data) W_1 = T.buffer_decl([1179648], dtype="float16", data=W.data) Conv_1 = T.buffer_decl([25690112], data=Conv.data) bx = T.env_thread("blockIdx.x") by = T.env_thread("blockIdx.y") bz = T.env_thread("block
Idx.z") tx = T.env_thread("threadIdx.x") ty = T.env_thread("threadIdx.y") tz = T.env_thread("threadIdx.z") T.launch_thread(bz, 196) Conv_wmma_accumulator_data = T.allocate([2048], "float32", "wmma.accumulator") Conv_wmma_accumulator = T.buffer_decl( shape=[2048], dtype="float32", scope="wmma.accumulator", data=Conv_wmma_accumulator_data ) Apad_shared_data = T.allocate([12288], "float16", "shared") Apad_shared = T.buffer_decl( shape=[12288], dtype="float16", scope="shared", data=Apad_shared_data ) W_shared_data = T.allocate([12288], "float16", "shared") W_shared = T.buffer_decl(shape=[12288], dtype="float16", scope="shared", data=W_shared_data) Apad_shared_wmma_matrix_a_data = T.allocate([512], "float16", "wmma.matrix_a") Apad_shared_wmma_matrix_a = T.buffer_decl( shape=[512], dtype="float16", scope="wmma.matrix_a", data=Apad_shared_wmma_matrix_a_data ) W_shared_wmma_matrix_b_data = T.allocate([1024], "float16", "wmma.matrix_b") W_shared_wmma_matrix_b = T.buffer_decl( shape=[1024], dtype="float16", scope="wmma.matrix_b", data=W_shared_wmma_matrix_b_data ) T.launch_thread(bx, 2) T.launch_thread(by, 4) T.launch_thread(ty, 4) T.launch_thread(tz, 2) T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 0, T.float32(0), dtype="handle" ) ) T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 1, T.float32(0), dtype="handle" ) ) T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 2, T.float32(0), dtype="handle" ) ) T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 3, T.float32(0), dtype="handle" ) )
T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 4, T.float32(0), dtype="handle" ) ) T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 5, T.float32(0), dtype="handle" ) ) T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 6, T.float32(0), dtype="handle" ) ) T.evaluate( T.tvm_fill_fragment( Conv_wmma_accumulator.data, 16, 16, 16, 7, T.float32(0), dtype="handle" ) ) for ic_outer in T.serial(0, 8): for kh in T.serial(0, 3): for ax2 in T.serial(0, 3): with T.launch_thread(tx, 32): Apad_shared[ ((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632)) + (tz * 802816)
) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61440 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 32) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632)) + (tz * 802816)
) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61408 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 64) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632)) + (tz * 802816)
) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61376 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 96) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632)) + (tz * 802816
) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61344 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 128) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632)) +
(tz * 802816) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61312 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 160) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632))
+ (tz * 802816) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61280 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 192) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632))
+ (tz * 802816) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61248 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 224) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632))
+ (tz * 802816) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61216 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 256) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 1605632))
+ (tz * 802816) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61184 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 288) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) + (ty * 160563
2)) + (tz * 802816) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61152 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 320) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx * 6422528) +
(ty * 1605632)) + (tz * 802816) ) + (kh * 57344) ) + (bz * 4096) ) + (ax2 * 4096) ) + (ic_outer * 512) ) + tx ) - 61120 ), ], T.float16(0), dtype="float16", ) with T.launch_thread(tx, 32): Apad_shared[ (((((ty * 3072) + (tz * 1536)) + (ax2 * 512)) + tx) + 352) ] = T.if_then_else( ( ( ( (1 <= (T.floordiv(bz, 14) + kh)) and ((T.floordiv(bz, 14) + kh) < 15) ) and (1 <= (ax2 + T.floormod(bz, 14))) ) and ((ax2 + T.floormod(bz, 14)) < 15) ), A_1[ ( ( ( ( ( ( ( ((bx