text
stringlengths
1
2.05k
import pytest def _tile_nd(s, tensor, tile): outer_indices = [] inner_indices = [] for i, size in enumerate(tile): outer, inner = s[tensor].split(tensor.op.axis[i], size) outer_indices.append(outer) inner_indices.append(inner) s[tensor].reorder(*outer_indices, *inner_indices) return outer_indices, inner_indices @tvm.tir.transform.prim_func_pass(opt_level=0) def remove_rolling_buffer_attr(func, mod, ctx): def unwrap(node): if isinstance(node, tvm.tir.AttrStmt) and node.attr_key == "rolling_buffer_scope": return node.body else: return node return func.with_body( tvm.tir.stmt_functor.ir_transform( func.body, None, postorder=unwrap, only_enable=["tir.AttrStmt"] ) ) @tvm.tir.transform.prim_func_pass(opt_level=0) def verify_no_rolling_buffer_attr(func, mod, ctx): def verify(node): if isinstance(node, tvm.tir.AttrStmt): assert node.attr_key != "rolling_buffer_scope", "Failed to lower rolling buffers" tvm.tir.stmt_functor.post_order_visit(func.body, verify) return func def _verify_schedule(sch, inputs, output): user_pass_lists = [ [(0, remove_rolling_buffer_attr), (0, verify_no_rolling_buffer_attr)], [(0, tvm.tir.transform.InjectRollingBuffer()), (0, verify_no_rolling_buffer_attr)], ] built_funcs = [] for user_pass_list in user_pass_lists: with tvm.transform.PassContext(config={"tir.add_lower_pass": user_pass_list}): built_funcs.append(tvm.build(sch, inputs + [output])) outputs = [] ctx = tvm.cpu(0) input_data = [] for tensor in inputs: shape = [i.value for i in tensor.shape] input_data.append( tvm.nd.array(np.random.randint(low=-100, high=100, size=shape).astype("int8"), ctx) ) shape = [i.value for i in output.shape] out = tvm.nd.array(np.zeros(shape, dtype="int8"), ctx) for func in built_funcs: func(*input_data, out) output
s.append(out.numpy()) np.testing.assert_equal(outputs[0], outputs[1]) @pytest.mark.parametrize("tile_shape", [(1, 4, 8, 16), (1, 8, 7, 11), (1, 8, 3, 8), (1, 7, 5, 3)]) def test_tile_shapes(tile_shape): A = te.placeholder((1, 12, 14, 16), name="A", dtype="int8") pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") pool_b = topi.nn.pool2d(pool_a, (3, 5), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") sch = tvm.te.create_schedule([pool_b.op]) oi, ii = _tile_nd(sch, pool_b, tile_shape) sch[pool_a].compute_at(sch[pool_b], oi[-1]) sch[pool_a].rolling_buffer() _verify_schedule(sch, [A], pool_b) def test_implied_split(): A = te.placeholder((1, 12, 12, 16), name="A", dtype="int8") pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") pool_b = topi.nn.pool2d(pool_a, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") sch = tvm.te.create_schedule([pool_b.op]) n, h, w, c = pool_b.op.axis oi, ii = sch[pool_b].split(w, 4) sch[pool_a].compute_at(sch[pool_b], oi) sch[pool_a].rolling_buffer() _verify_schedule(sch, [A], pool_b) @pytest.mark.parametrize("kernel_shape", [(1, 1), (3, 3)]) def test_upscale(kernel_shape): output_shape = (1, 24, 24, 16) input_shape = ( output_shape[0], output_shape[1] output_shape[2] output_shape[3], ) A = te.placeholder(input_shape, name="A", dtype="int8") pool_a = topi.nn.pool2d(A, kernel_shape, (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") pool_b = topi.nn.pool2d( pool_a, kernel_shape, (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC" ) upscale = te.compute((1, 24, 24, 16), lambda nn, hh, ww, cc: pool_b[nn, hh sch = tvm.te.create_schedule([upscale.op]) oi, ii = _tile_nd(sch, upscale, (1, 5, 5, 16)) sch[pool_b].compute_at(sch[upscale], oi[-1]) sch[pool_b].rolling_buffer() sch[pool_a].compute_at(sch[upscale], oi[-1]) sch[pool_a].rolling
_buffer() _verify_schedule(sch, [A], upscale) @pytest.mark.parametrize("tile_shape", [(1, 4, 8, 16), (1, 8, 7, 11), (1, 8, 3, 8), (1, 7, 5, 3)]) def test_3_tiled_poolings(tile_shape): A = te.placeholder((1, 14, 14, 16), name="A", dtype="int8") pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") pool_b = topi.nn.pool2d(pool_a, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") pool_c = topi.nn.pool2d(pool_b, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") sch = tvm.te.create_schedule([pool_c.op]) oi, ii = _tile_nd(sch, pool_c, tile_shape) sch[pool_b].compute_at(sch[pool_c], oi[-1]) sch[pool_b].rolling_buffer() sch[pool_a].compute_at(sch[pool_c], oi[-1]) sch[pool_a].rolling_buffer() _verify_schedule(sch, [A], pool_c) @pytest.mark.parametrize("tile_shape", [(1, 4, 8, 16), (1, 8, 7, 11), (1, 8, 3, 8), (1, 7, 5, 3)]) def test_tiled_added_poolings(tile_shape): A = te.placeholder((1, 12, 12, 16), name="A", dtype="int8") B = te.placeholder((1, 14, 14, 16), name="A", dtype="int8") pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") pool_b = topi.nn.pool2d(B, (5, 5), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") add = topi.add(pool_a, pool_b) pool_c = topi.nn.pool2d(add, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") sch = tvm.te.create_schedule([pool_c.op]) oi, ii = _tile_nd(sch, pool_c, tile_shape) sch[add].compute_at(sch[pool_c], oi[-1]) sch[add].rolling_buffer() sch[pool_b].compute_at(sch[pool_c], oi[-1]) sch[pool_b].rolling_buffer() sch[pool_a].compute_at(sch[pool_c], oi[-1]) sch[pool_a].rolling_buffer() _verify_schedule(sch, [A, B], pool_c) @pytest.mark.parametrize("make_rolling", [(0, 0), (1, 0), (0, 1), (1, 1)]) def test_mixed_buffers(make_rolling): A = te.placeholder((1, 14, 14, 16), name="A", dtype="int8") pool_a = topi.nn.pool2d(A, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", lay
out="NHWC") pool_b = topi.nn.pool2d(pool_a, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") pool_c = topi.nn.pool2d(pool_b, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), "max", layout="NHWC") sch = tvm.te.create_schedule([pool_c.op]) oi, ii = _tile_nd(sch, pool_c, (1, 4, 8, 16)) sch[pool_b].compute_at(sch[pool_c], oi[-1]) if make_rolling[0]: sch[pool_b].rolling_buffer() sch[pool_a].compute_at(sch[pool_c], oi[-1]) if make_rolling[1]: sch[pool_a].rolling_buffer() _verify_schedule(sch, [A], pool_c) @tvm.script.ir_module class PreRollingBuffer: @T.prim_func def main(A: T.handle, tensor: T.handle) -> None: T.func_attr({"from_legacy_te_schedule": True, "global_symbol": "main", "tir.noalias": True}) tensor_2 = T.buffer_decl([1, 10, 12, 16], dtype="int8", elem_offset=0, align=64, offset_factor=1) A_1 = T.match_buffer(A, [1, 12, 14, 16], dtype="int8", elem_offset=0, align=64, offset_factor=1) tensor_1 = T.match_buffer(tensor, [1, 8, 8, 16], dtype="int8", elem_offset=0, align=64, offset_factor=1) T.realize(tensor_1[0:1, 0:8, 0:8, 0:16], "") for ax1_outer in T.serial(0, 2): T.realize(tensor_2[0:1, (ax1_outer*4):((ax1_outer*4) + 6), 0:12, 0:16], "") T.attr(tensor_2, "rolling_buffer_scope", True) for ax1 in T.serial(0, 6): for ax2 in T.serial(0, 12): for ax3 in T.serial(0, 16): tensor_2[0, (ax1 + (ax1_outer*4)), ax2, ax3] = T.int8(0) for dh in T.serial(0, 3): for dw in T.serial(0, 3): tensor_2[0, (ax1 + (ax1_outer*4)), ax2, ax3] = T.max(tensor_2[0, (ax1 + (ax1_outer*4)), ax2, ax3], A_1[0, ((ax1 + (ax1_outer*4)) + dh), (ax2 + dw), ax3]) for ax1_inner in T.serial(0, 4): for ax2_inner in T.serial(0, 8): for ax3_inner in T.serial(0, 16): ten
sor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.int8(0) for dh_1 in T.serial(0, 3): for dw_1 in T.serial(0, 5): tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.max(tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner], tensor_2[0, ((ax1_inner + (ax1_outer*4)) + dh_1), (ax2_inner + dw_1), ax3_inner]) __tvm_meta__ = None @tvm.script.ir_module class PostRollingBuffer: @T.prim_func def main(A: T.handle, tensor: T.handle) -> None: T.func_attr({"from_legacy_te_schedule": True, "global_symbol": "main", "tir.noalias": True}) tensor_2 = T.buffer_decl([1, 10, 12, 16], dtype="int8", elem_offset=0, align=64, offset_factor=1) A_1 = T.match_buffer(A, [1, 12, 14, 16], dtype="int8", elem_offset=0, align=64, offset_factor=1) tensor_1 = T.match_buffer(tensor, [1, 8, 8, 16], dtype="int8", elem_offset=0, align=64, offset_factor=1) T.realize(tensor_1[0:1, 0:8, 0:8, 0:16], "") T.realize(tensor_2[0:1, 0:6, 0:12, 0:16], "") for ax1_outer in T.serial(0, 2): for ax1 in T.serial(0, 6): for ax2 in T.serial(0, 12): for ax3 in T.serial(0, 16): if T.likely(((ax1_outer < 1) or (ax1 >= 2)), dtype='bool') : tensor_2[0, T.floormod((ax1 + (ax1_outer*4)), 6), ax2, ax3] = T.int8(0) for dh in T.serial(0, 3): for dw in T.serial(0, 3): if T.likely(((ax1_outer < 1) or (ax1 >= 2)), dtype='bool'): tensor_2[0, T.floormod((ax1 + (ax1_outer*4)), 6), ax2, ax3] = T.max(tensor_2[0, T.floormod((ax1 + (ax1_outer*4)), 6), ax2, ax3], A_1[0, ((ax1 + (ax1_outer*4)) + dh), (ax2 + dw), ax3]) for ax1_inner in T.serial(0, 4): for ax2_inner in T.serial(0, 8): for ax3_inner in T.serial(0, 1
6): tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.int8(0) for dh_1 in T.serial(0, 3): for dw_1 in T.serial(0, 5): tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner] = T.max(tensor_1[0, (ax1_inner + (ax1_outer*4)), ax2_inner, ax3_inner], tensor_2[0, T.floormod(((ax1_inner + (ax1_outer*4)) + dh_1), 6), (ax2_inner + dw_1), ax3_inner]) __tvm_meta__ = None def test_rolling_buffer_ir_transform(): mod = PreRollingBuffer mod = tvm.tir.transform.InjectRollingBuffer()(mod) script = mod.script(show_meta=True) mod = tvm.script.from_source(script) tvm.ir.assert_structural_equal(mod["main"], PostRollingBuffer["main"], True) if __name__ == "__main__": pytest.main([__file__])
import sys
import numpy as np
import pytest
import tvm
import tvm.testing
import tvm.tir.tensor_intrin.cuda from tvm
import TVMError, te, tir from tvm.meta_schedule.testing
import te_workload from tvm.script
import tir as T from tvm.testing.tir
import mma_schedule from tvm.tir.tensor_intrin.cuda
import ( LDMATRIX_16x16_A_DYN_INTRIN, LDMATRIX_16x16_B_DYN_INTRIN, MMA_f16f16f32_INTRIN, MMA_fill_16x16_f32_INTRIN, MMA_store_16x16_f32_global_INTRIN, shared_16x16_to_ldmatrix_32x8_layout, ) def _check(original, transformed): func = original mod = tvm.IRModule.from_expr(func) mod = tvm.tir.transform.InjectSoftwarePipeline()(mod) mod = tvm.tir.transform.Simplify()(mod) tvm.ir.assert_structural_equal(mod["main"], transformed, True) def _check_error(func): mod = tvm.IRModule.from_expr(func) with pytest.raises(ValueError): tvm.tir.transform.InjectSoftwarePipeline()(mod) @T.prim_func def trivial_pipeline(A: T.Buffer[(16, 1), "float32"], C: T.Buffer[(16, 1), "float32"]): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 1, annotations={"software_pipeline_stage": [0, 1], "software_pipeline_order": [0, 1]} ): with T.block(): T.reads(A[tx, i]) T.writes(C[tx, i]) B = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(B[tx, 0]) B[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(C[tx, i]) C[tx, i] = B[tx, 0] + T.float32(1) @T.prim_func def transformed_trivial_pipeline( A: T.Buffer[(16, 1), "float32"], C: T.Buffer[(16, 1), "float32"] ) -> None: for tx in T.thread_binding(16, thread="threadIdx.x"): with T.block(): T.reads(A[tx, 0]) T.writes(C[tx, 0]) B = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads(A[tx, 0]) T.writes(B[0, tx, 0]) B[0, tx, 0] = A[tx, 0] * T.float32(2) with T.block(): T.reads() T.writes() T.evalu
ate(0) with T.block(): T.reads(B[0, tx, 0]) T.writes(C[tx, 0]) C[tx, 0] = B[0, tx, 0] + T.float32(1) def gen_simple_compute(num_stages): @T.prim_func def simple_compute(A: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"]): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, num_stages], "software_pipeline_order": [0, 1], }, ): with T.block("compute"): T.reads(A[tx, i]) T.writes(C[tx, i]) B = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(B[tx, 0]) B[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(C[tx, i]) C[tx, i] = B[tx, 0] + T.float32(1) return simple_compute @T.prim_func def transformed_simple_compute( A: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"] ) -> None: for tx in T.thread_binding(0, 16, thread="threadIdx.x"): with T.block(): T.reads([A[tx, 0:16]]) T.writes([C[tx, 0:16]]) B = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads([A[tx, 0]]) T.writes([B[0, tx, 0]]) B[0, tx, 0] = A[tx, 0] * T.float32(2) with T.block(): T.reads([A[tx, 1:16], B[0:2, tx, 0]]) T.writes([B[0:2, tx, 0], C[tx, 0:15]]) for i in T.serial(0, 15): with T.block(): T.reads([A[tx, i + 1]]) T.writes([B[(i + 1) % 2, tx, 0
]]) B[(i + 1) % 2, tx, 0] = A[tx, i + 1] * T.float32(2) with T.block(): T.reads([B[i % 2, tx, 0]]) T.writes([C[tx, i]]) C[tx, i] = B[i % 2, tx, 0] + T.float32(1) with T.block(): T.reads([B[1, tx, 0]]) T.writes([C[tx, 15]]) C[tx, 15] = B[1, tx, 0] + T.float32(1) @T.prim_func def simple_compute_with_other_annotation( A: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1], "software_pipeline_order": [0, 1], "pragma_loop_partition_hint": True, }, ): with T.block("compute"): T.reads(A[tx, i]) T.writes(C[tx, i]) B = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(B[tx, 0]) B[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(C[tx, i]) C[tx, i] = B[tx, 0] + T.float32(1) @T.prim_func def transformed_simple_compute_with_other_annotation( A: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"] ) -> None: for tx in T.thread_binding(0, 16, thread="threadIdx.x"): with T.block(): T.reads([A[tx, 0:16]]) T.writes([C[tx, 0:16]]) B = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads([A[tx, 0]]) T.writes([B[0, tx, 0]]) B[0, tx, 0] = A[tx, 0] * T.float32(2) with T.block(): T.reads([A[tx, 1:16], B[0:2, tx, 0]]) T.wr
ites([B[0:2, tx, 0], C[tx, 0:15]]) for i in T.serial( 0, 15, annotations={"pragma_loop_partition_hint": True}, ): with T.block(): T.reads([A[tx, i + 1]]) T.writes([B[(i + 1) % 2, tx, 0]]) B[(i + 1) % 2, tx, 0] = A[tx, i + 1] * T.float32(2) with T.block(): T.reads([B[i % 2, tx, 0]]) T.writes([C[tx, i]]) C[tx, i] = B[i % 2, tx, 0] + T.float32(1) with T.block(): T.reads([B[1, tx, 0]]) T.writes([C[tx, 15]]) C[tx, 15] = B[1, tx, 0] + T.float32(1) @T.prim_func def three_stage_compute(A: T.Buffer[(16, 16), "float32"], D: T.Buffer[(16, 16), "float32"]): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1, 2], "software_pipeline_order": [0, 1, 2], }, ): with T.block("compute"): T.reads(A[tx, i]) T.writes(D[tx, i]) B = T.alloc_buffer((16, 1), dtype="float32", scope="shared") C = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(B[tx, 0]) B[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(C[tx, 0]) C[tx, 0] = B[tx, 0] + T.float32(2) with T.block(): T.reads(C[tx, 0]) T.writes(D[tx, i]) D[tx, i] = C[tx, 0] + T.float32(1) @T.prim_func def transformed_three_stage_compute( A: T.Buffer[(16, 16), "float32"], D: T.Buffer[(16, 16), "float32"] ) ->
None: for tx in T.thread_binding(16, thread="threadIdx.x"): with T.block(): T.reads(A[tx, 0:16]) T.writes(D[tx, 0:16]) B = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") C = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads(A[tx, 0:2], B[0:2, tx, 0]) T.writes(B[0:2, tx, 0], C[0:2, tx, 0]) for i in T.unroll(2): with T.block(): T.reads(A[tx, i]) T.writes(B[0:2, tx, 0]) B[i, tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.where(i == 1) T.reads(B[0:2, tx, 0]) T.writes(C[0:2, tx, 0]) C[(i + 1) % 2, tx, 0] = B[(i + 1) % 2, tx, 0] + T.float32(2) with T.block(): T.reads(A[tx, 2:16], B[0:2, tx, 0], C[0:2, tx, 0]) T.writes(B[0:2, tx, 0], C[0:2, tx, 0], D[tx, 0:14]) for i in T.serial(14): with T.block(): T.reads(A[tx, i + 2]) T.writes(B[0:2, tx, 0]) B[i % 2, tx, 0] = A[tx, i + 2] * T.float32(2) with T.block(): T.reads(B[0:2, tx, 0]) T.writes(C[0:2, tx, 0]) C[(i + 1) % 2, tx, 0] = B[(i + 1) % 2, tx, 0] + T.float32(2) with T.block(): T.reads(C[0:2, tx, 0]) T.writes(D[tx, i]) D[tx, i] = C[i % 2, tx, 0] + T.float32(1) with T.block(): T.reads(B[0:2, tx, 0], C[0:2, tx, 0]) T.writes(C[0:2, tx, 0], D[tx, 14:16]) for i in T.unroll(2): with T.block(): T.where(i < 1) T.reads(B[0:2, tx, 0])
T.writes(C[0:2, tx, 0]) C[(i + 1) % 2, tx, 0] = B[(i + 1) % 2, tx, 0] + T.float32(2) with T.block(): T.reads(C[0:2, tx, 0]) T.writes(D[tx, i + 14]) D[tx, i + 14] = C[i, tx, 0] + T.float32(1) @T.prim_func def dag_interleaving( A: T.Buffer[(16, 16), "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ) -> None: for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 0, 0, 0, 1], "software_pipeline_order": [0, 2, 1, 3, 4], }, ): with T.block(): T.reads(A[tx, i]) T.writes(C[tx, i]) AS = T.alloc_buffer((16, 1), dtype="float32", scope="shared") BS = T.alloc_buffer((16, 1), dtype="float32", scope="shared") AL = T.alloc_buffer((1, 1), dtype="float32", scope="local") BL = T.alloc_buffer((1, 1), dtype="float32", scope="local") with T.block(): T.reads(A[tx, i]) T.writes(AS[tx, 0]) AS[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(AS[tx, 0]) T.writes(AL[0, 0]) AL[0, 0] = AS[tx, 0] with T.block(): T.reads(B[tx, i]) T.writes(BS[tx, 0]) BS[tx, 0] = B[tx, i] + T.float32(2) with T.block(): T.reads(BS[tx, 0]) T.writes(BL[0, 0]) BL[0, 0] = BS[tx, 0] with T.block(): T.reads(AL[0, 0], BL[0, 0]) T.writes(C[tx, i]) C[tx, i] = AL[0, 0] * BL[0, 0] @T.prim_func def transformed_dag_interleaving( A: T.Buffer[(16, 16)
, "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ) -> None: for tx in T.thread_binding(16, thread="threadIdx.x"): with T.block(): T.reads(A[tx, 0:16], B[tx, 0:16]) T.writes(C[tx, 0:16]) AS = T.alloc_buffer([16, 1], dtype="float32", scope="shared") BS = T.alloc_buffer([16, 1], dtype="float32", scope="shared") AL = T.alloc_buffer([2, 1, 1], dtype="float32", scope="local") BL = T.alloc_buffer([2, 1, 1], dtype="float32", scope="local") with T.block(): T.reads(A[tx, 0], B[tx, 0], AS[tx, 0], BS[tx, 0]) T.writes(AS[tx, 0], BS[tx, 0], AL[0, 0, 0], BL[0, 0, 0]) with T.block(): T.reads(A[tx, 0]) T.writes(AS[tx, 0]) AS[tx, 0] = A[tx, 0] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(BS[tx, 0]) BS[tx, 0] = B[tx, 0] + T.float32(2) with T.block(): T.reads(AS[tx, 0]) T.writes(AL[0, 0, 0]) AL[0, 0, 0] = AS[tx, 0] with T.block(): T.reads(BS[tx, 0]) T.writes(BL[0, 0, 0]) BL[0, 0, 0] = BS[tx, 0] with T.block(): T.reads( A[tx, 1:16], B[tx, 1:16], AS[tx, 0], BS[tx, 0], AL[0:2, 0, 0], BL[0:2, 0, 0] ) T.writes(AS[tx, 0], BS[tx, 0], AL[0:2, 0, 0], BL[0:2, 0, 0], C[tx, 0:15]) for i in T.serial(15): with T.block(): T.reads(A[tx, i + 1]) T.writes(AS[tx, 0]) AS[tx, 0] = A[tx, i + 1] * T.float32(2) with T.block(): T.reads(B[tx, i + 1]) T.writes(BS[tx, 0]) BS[tx, 0] = B[tx, i + 1] + T.float32(
2) with T.block(): T.reads(AS[tx, 0]) T.writes(AL[(i + 1) % 2, 0, 0]) AL[(i + 1) % 2, 0, 0] = AS[tx, 0] with T.block(): T.reads(BS[tx, 0]) T.writes(BL[(i + 1) % 2, 0, 0]) BL[(i + 1) % 2, 0, 0] = BS[tx, 0] with T.block(): T.reads(AL[i % 2, 0, 0], BL[i % 2, 0, 0]) T.writes(C[tx, i]) C[tx, i] = AL[i % 2, 0, 0] * BL[i % 2, 0, 0] with T.block(): T.reads(AL[1, 0, 0], BL[1, 0, 0]) T.writes(C[tx, 15]) C[tx, 15] = AL[1, 0, 0] * BL[1, 0, 0] @T.prim_func def nested_pipeline_simple( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffer[(16, 16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1, 1, 1], "software_pipeline_order": [0, 1, 2, 3], }, ): with T.block(): T.reads(A[tx, i, 0:16]) T.writes(C[tx, i, 0:16]) A_shared = T.alloc_buffer((16, 1, 16), dtype="float32", scope="shared") for j in T.serial(0, 16): with T.block(): T.reads(A[tx, i, j]) T.writes(A_shared[tx, 0, j]) A_shared[tx, 0, j] = A[tx, i, j] for j in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1], "software_pipeline_order": [0, 1], }, ): with T.block(): T.reads(A_shared[tx, 0, j]) T.writes(C[tx, i, j]) B =
T.alloc_buffer((16, 1, 1), dtype="float32", scope="shared") with T.block(): T.reads(A_shared[tx, i, j]) T.writes(B[tx, i, 0]) B[tx, i, 0] = A_shared[tx, 0, j] * T.float32(2) with T.block(): T.reads(B[tx, i, 0]) T.writes(C[tx, i, j]) C[tx, i, j] = B[tx, i, 0] + T.float32(1) @T.prim_func def transformed_nested_pipeline_simple( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffer[(16, 16, 16), "float32"] ) -> None: for tx in T.thread_binding(0, 16, thread="threadIdx.x"): with T.block(): T.reads([A[tx, 0:16, 0:16]]) T.writes([C[tx, 0:16, 0:16]]) A_shared = T.alloc_buffer([2, 16, 1, 16], dtype="float32", scope="shared") B = T.alloc_buffer([2, 16, 1, 1], dtype="float32", scope="shared") with T.block(): T.reads([A[tx, 0, 0:16]]) T.writes([A_shared[0, tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A[tx, 0, j]]) T.writes([A_shared[0, tx, 0, j]]) A_shared[0, tx, 0, j] = A[tx, 0, j] with T.block(): T.reads([A[tx, 1:16, 0:16], A_shared[0:2, tx, 0:15, 0:16], B[0:2, tx, 0:15, 0]]) T.writes([A_shared[0:2, tx, 0, 0:16], B[0:2, tx, 0:15, 0], C[tx, 0:15, 0:16]]) for i in T.serial(0, 15): with T.block(): T.reads([A[tx, i + 1, 0:16]]) T.writes([A_shared[(i + 1) % 2, tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A[tx, i + 1, j]]) T.writes([A_shared[(i + 1) % 2, tx, 0, j]]) A_shared[(i + 1) % 2, tx, 0,
j] = A[tx, i + 1, j] with T.block(): T.reads([A_shared[i % 2, tx, i, 0]]) T.writes([B[0, tx, i, 0]]) B[0, tx, i, 0] = A_shared[i % 2, tx, 0, 0] * T.float32(2) with T.block(): T.reads([A_shared[i % 2, tx, i, 1:16], B[0:2, tx, i, 0]]) T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_shared[i % 2, tx, i, j + 1]]) T.writes([B[(j + 1) % 2, tx, i, 0]]) B[(j + 1) % 2, tx, i, 0] = A_shared[ i % 2, tx, 0, j + 1 ] * T.float32(2) with T.block(): T.reads([B[j % 2, tx, i, 0]]) T.writes([C[tx, i, j]]) C[tx, i, j] = B[j % 2, tx, i, 0] + T.float32(1) with T.block(): T.reads([B[1, tx, i, 0]]) T.writes([C[tx, i, 15]]) C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1) with T.block(): T.reads([A_shared[1, tx, 15, 0:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]]) with T.block(): T.reads([A_shared[1, tx, 15, 0]]) T.writes([B[0, tx, 15, 0]]) B[0, tx, 15, 0] = A_shared[1, tx, 0, 0] * T.float32(2) with T.block(): T.reads([A_shared[1, tx, 15, 1:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_shared[1, tx, 15, j + 1]]) T.writes([B[(j + 1) % 2, t
x, 15, 0]]) B[(j + 1) % 2, tx, 15, 0] = A_shared[1, tx, 0, j + 1] * T.float32(2) with T.block(): T.reads([B[j % 2, tx, 15, 0]]) T.writes([C[tx, 15, j]]) C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1) with T.block(): T.reads([B[1, tx, 15, 0]]) T.writes([C[tx, 15, 15]]) C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1) @T.prim_func def nested_pipeline_prefetch_inner( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffer[(16, 16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 0, 1, 1], "software_pipeline_order": [0, 2, 1, 3], }, ): with T.block(): T.reads(A[tx, i, 0:16]) T.writes(C[tx, i, 0:16]) A_shared = T.alloc_buffer((16, 1, 16), dtype="float32", scope="shared") for j in T.serial(0, 16): with T.block(): T.reads(A[tx, i, j]) T.writes(A_shared[tx, 0, j]) A_shared[tx, 0, j] = A[tx, i, j] for j in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1], "software_pipeline_order": [0, 1], }, ): with T.block(): T.reads(A_shared[tx, 0, j]) T.writes(C[tx, i, j]) B = T.alloc_buffer((16, 1, 1), dtype="float32", scope="shared") with T.block(): T.reads(A_shared[tx, i, j]) T.writes(B[tx, i, 0])
B[tx, i, 0] = A_shared[tx, 0, j] * T.float32(2) with T.block(): T.reads(B[tx, i, 0]) T.writes(C[tx, i, j]) C[tx, i, j] = B[tx, i, 0] + T.float32(1) @T.prim_func def transformed_nested_pipeline_prefetch_inner( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffer[(16, 16, 16), "float32"] ) -> None: for tx in T.thread_binding(0, 16, thread="threadIdx.x"): with T.block(): T.reads([A[tx, 0:16, 0:16]]) T.writes([C[tx, 0:16, 0:16]]) A_shared = T.alloc_buffer([2, 16, 1, 16], dtype="float32", scope="shared") B = T.alloc_buffer([2, 16, 1, 1], dtype="float32", scope="shared") with T.block(): T.reads([A[tx, 0, 0:16], A_shared[0, tx, 0, 0]]) T.writes([A_shared[0, tx, 0, 0:16], B[0, tx, 0, 0]]) with T.block(): T.reads([A[tx, 0, 0:16]]) T.writes([A_shared[0, tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A[tx, 0, j]]) T.writes([A_shared[0, tx, 0, j]]) A_shared[0, tx, 0, j] = A[tx, 0, j] with T.block(): T.reads([A_shared[0, tx, 0, 0]]) T.writes([B[0, tx, 0, 0]]) B[0, tx, 0, 0] = A_shared[0, tx, 0, 0] * T.float32(2) with T.block(): T.reads([A[tx, 1:16, 0:16], A_shared[0:2, tx, 0:16, 0:16], B[0:2, tx, 0:15, 0]]) T.writes([A_shared[0:2, tx, 0, 0:16], B[0:2, tx, 0:16, 0], C[tx, 0:15, 0:16]]) for i in T.serial(0, 15): with T.block(): T.reads([A[tx, i + 1, 0:16]]) T.writes([A_shared[(i + 1) % 2, tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block():
T.reads([A[tx, i + 1, j]]) T.writes([A_shared[(i + 1) % 2, tx, 0, j]]) A_shared[(i + 1) % 2, tx, 0, j] = A[tx, i + 1, j] with T.block(): T.reads([A_shared[i % 2, tx, i, 1:16], B[0:2, tx, i, 0]]) T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_shared[i % 2, tx, i, j + 1]]) T.writes([B[(j + 1) % 2, tx, i, 0]]) B[(j + 1) % 2, tx, i, 0] = A_shared[ i % 2, tx, 0, j + 1 ] * T.float32(2) with T.block(): T.reads([B[j % 2, tx, i, 0]]) T.writes([C[tx, i, j]]) C[tx, i, j] = B[j % 2, tx, i, 0] + T.float32(1) with T.block(): T.reads([A_shared[(i + 1) % 2, tx, i + 1, 0]]) T.writes([B[0, tx, i + 1, 0]]) B[0, tx, i + 1, 0] = A_shared[(i + 1) % 2, tx, 0, 0] * T.float32(2) with T.block(): T.reads([B[1, tx, i, 0]]) T.writes([C[tx, i, 15]]) C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1) with T.block(): T.reads([A_shared[1, tx, 15, 1:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]]) with T.block(): T.reads([A_shared[1, tx, 15, 1:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_shared[1, tx, 15, j + 1]]) T.writes([B[(j + 1) % 2, tx, 15, 0]
]) B[(j + 1) % 2, tx, 15, 0] = A_shared[1, tx, 0, j + 1] * T.float32(2) with T.block(): T.reads([B[j % 2, tx, 15, 0]]) T.writes([C[tx, 15, j]]) C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1) with T.block(): T.reads([B[1, tx, 15, 0]]) T.writes([C[tx, 15, 15]]) C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1) @T.prim_func def nested_pipeline_interleaving( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffer[(16, 16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 0, 0, 1, 1], "software_pipeline_order": [0, 2, 3, 1, 4], }, ): with T.block(): T.reads(A[tx, i, 0:16]) T.writes(C[tx, i, 0:16]) A_shared = T.alloc_buffer((16, 1, 16), dtype="float32", scope="shared") A_local = T.alloc_buffer((1, 1, 16), dtype="float32", scope="local") for j in T.serial(0, 16): with T.block(): T.reads(A[tx, i, j]) T.writes(A_shared[tx, 0, j]) A_shared[tx, 0, j] = A[tx, i, j] for j in T.serial(0, 16): with T.block(): T.reads(A_shared[tx, 0, j]) T.writes(A_local[0, 0, j]) A_local[0, 0, j] = A_shared[tx, i, j] for j in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1], "software_pipeline_order": [0, 1], }, ): with T.block(): T.reads(A_
local[0, 0, j]) T.writes(C[tx, i, j]) B = T.alloc_buffer((16, 1, 1), dtype="float32", scope="shared") with T.block(): T.reads(A_local[tx, i, j]) T.writes(B[tx, i, 0]) B[tx, i, 0] = A_local[0, 0, j] * T.float32(2) with T.block(): T.reads(B[tx, i, 0]) T.writes(C[tx, i, j]) C[tx, i, j] = B[tx, i, 0] + T.float32(1) @T.prim_func def transformed_nested_pipeline_interleaving( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffer[(16, 16, 16), "float32"] ) -> None: for tx in T.thread_binding(0, 16, thread="threadIdx.x"): with T.block(): T.reads([A[tx, 0:16, 0:16]]) T.writes([C[tx, 0:16, 0:16]]) A_shared = T.alloc_buffer([16, 1, 16], dtype="float32", scope="shared") A_local = T.alloc_buffer([1, 1, 16], dtype="float32", scope="local") B = T.alloc_buffer([2, 16, 1, 1], dtype="float32", scope="shared") with T.block(): T.reads([A[tx, 0, 0:16], A_shared[tx, 0, 0:16], A_local[tx, 0, 0]]) T.writes([A_shared[tx, 0, 0:16], A_local[0, 0, 0:16], B[0, tx, 0, 0]]) with T.block(): T.reads([A[tx, 0, 0:16]]) T.writes([A_shared[tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A[tx, 0, j]]) T.writes([A_shared[tx, 0, j]]) A_shared[tx, 0, j] = A[tx, 0, j] with T.block(): T.reads([A_shared[tx, 0, 0:16]]) T.writes([A_local[0, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A_shared[tx, 0, j]]) T.writes([A
_local[0, 0, j]]) A_local[0, 0, j] = A_shared[tx, 0, j] with T.block(): T.reads([A_local[tx, 0, 0]]) T.writes([B[0, tx, 0, 0]]) B[0, tx, 0, 0] = A_local[0, 0, 0] * T.float32(2) with T.block(): T.reads( [ A[tx, 1:16, 0:16], A_local[tx, 0:16, 0:16], B[0:2, tx, 0:15, 0], A_shared[tx, 0, 0:16], ] ) T.writes( [ A_shared[tx, 0, 0:16], B[0:2, tx, 0:16, 0], C[tx, 0:15, 0:16], A_local[0, 0, 0:16], ] ) for i in T.serial(0, 15): with T.block(): T.reads([A[tx, i + 1, 0:16]]) T.writes([A_shared[tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A[tx, i + 1, j]]) T.writes([A_shared[tx, 0, j]]) A_shared[tx, 0, j] = A[tx, i + 1, j] with T.block(): T.reads([A_local[tx, i, 1:16], B[0:2, tx, i, 0]]) T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_local[tx, i, j + 1]]) T.writes([B[(j + 1) % 2, tx, i, 0]]) B[(j + 1) % 2, tx, i, 0] = A_local[0, 0, j + 1] * T.float32(2) with T.block(): T.reads([B[j % 2, tx, i, 0]]) T.writes([C[tx, i, j]]) C[tx, i, j] = B[j % 2, tx, i,
0] + T.float32(1) with T.block(): T.reads([A_shared[tx, 0, 0:16]]) T.writes([A_local[0, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A_shared[tx, 0, j]]) T.writes([A_local[0, 0, j]]) A_local[0, 0, j] = A_shared[tx, i + 1, j] with T.block(): T.reads([A_local[tx, i + 1, 0]]) T.writes([B[0, tx, i + 1, 0]]) B[0, tx, i + 1, 0] = A_local[0, 0, 0] * T.float32(2) with T.block(): T.reads([B[1, tx, i, 0]]) T.writes([C[tx, i, 15]]) C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1) with T.block(): T.reads([A_local[tx, 15, 1:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]]) with T.block(): T.reads([A_local[tx, 15, 1:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_local[tx, 15, j + 1]]) T.writes([B[(j + 1) % 2, tx, 15, 0]]) B[(j + 1) % 2, tx, 15, 0] = A_local[0, 0, j + 1] * T.float32(2) with T.block(): T.reads([B[j % 2, tx, 15, 0]]) T.writes([C[tx, 15, j]]) C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1) with T.block(): T.reads([B[1, tx, 15, 0]]) T.writes([C[tx, 15, 15]]) C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1) @T.prim_func def nested_pipeline_double_buffer( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffe
r[(16, 16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 0, 0, 1, 1], "software_pipeline_order": [0, 2, 3, 1, 4], }, ): with T.block(): T.reads(A[tx, i, 0:16]) T.writes(C[tx, i, 0:16]) A_shared = T.alloc_buffer((16, 1, 16), dtype="float32", scope="shared") A_local = T.alloc_buffer((1, 1, 16), dtype="float32", scope="local") for j in T.serial(0, 16): with T.block(): T.reads(A[tx, i, j]) T.writes(A_shared[tx, 0, j]) A_shared[tx, 0, j] = A[tx, i, j] for j in T.serial(0, 16): with T.block(): T.block_attr({"double_buffer_scope": 0}) T.reads(A_shared[tx, 0, j]) T.writes(A_local[0, 0, j]) A_local[0, 0, j] = A_shared[tx, i, j] for j in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1], "software_pipeline_order": [0, 1], }, ): with T.block(): T.reads(A_local[0, 0, j]) T.writes(C[tx, i, j]) B = T.alloc_buffer((16, 1, 1), dtype="float32", scope="shared") with T.block(): T.reads(A_local[tx, i, j]) T.writes(B[tx, i, 0]) B[tx, i, 0] = A_local[0, 0, j] * T.float32(2) with T.block(): T.reads(B[tx, i, 0]) T.writes(C[tx, i, j]) C[tx, i, j] = B[tx, i,
0] + T.float32(1) @T.prim_func def transformed_nested_pipeline_double_buffer( A: T.Buffer[(16, 16, 16), "float32"], C: T.Buffer[(16, 16, 16), "float32"] ) -> None: for tx in T.thread_binding(0, 16, thread="threadIdx.x"): with T.block(): T.reads([A[tx, 0:16, 0:16]]) T.writes([C[tx, 0:16, 0:16]]) A_shared = T.alloc_buffer([16, 1, 16], dtype="float32", scope="shared") A_local = T.alloc_buffer([2, 1, 1, 16], dtype="float32", scope="local") B = T.alloc_buffer([2, 16, 1, 1], dtype="float32", scope="shared") with T.block(): T.reads([A[tx, 0, 0:16], A_shared[tx, 0, 0:16], A_local[0, tx, 0, 0]]) T.writes([A_shared[tx, 0, 0:16], A_local[0, 0, 0, 0:16], B[0, tx, 0, 0]]) with T.block(): T.reads([A[tx, 0, 0:16]]) T.writes([A_shared[tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A[tx, 0, j]]) T.writes([A_shared[tx, 0, j]]) A_shared[tx, 0, j] = A[tx, 0, j] with T.block(): T.reads([A_shared[tx, 0, 0:16]]) T.writes([A_local[0, 0, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A_shared[tx, 0, j]]) T.writes([A_local[0, 0, 0, j]]) T.block_attr({"double_buffer_scope": 0}) A_local[0, 0, 0, j] = A_shared[tx, 0, j] with T.block(): T.reads([A_local[0, tx, 0, 0]]) T.writes([B[0, tx, 0, 0]]) B[0, tx, 0, 0] = A_local[0, 0, 0, 0] * T.float32(2) with T.block(): T.reads( [ A[tx, 1:16, 0:16], A_local[0:2, tx, 0:16, 0:16],
B[0:2, tx, 0:15, 0], A_shared[tx, 0, 0:16], ] ) T.writes( [ A_shared[tx, 0, 0:16], B[0:2, tx, 0:16, 0], C[tx, 0:15, 0:16], A_local[0:2, 0, 0, 0:16], ] ) for i in T.serial(0, 15): with T.block(): T.reads([A[tx, i + 1, 0:16]]) T.writes([A_shared[tx, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A[tx, i + 1, j]]) T.writes([A_shared[tx, 0, j]]) A_shared[tx, 0, j] = A[tx, i + 1, j] with T.block(): T.reads([A_local[i % 2, tx, i, 1:16], B[0:2, tx, i, 0]]) T.writes([B[0:2, tx, i, 0], C[tx, i, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_local[i % 2, tx, i, j + 1]]) T.writes([B[(j + 1) % 2, tx, i, 0]]) B[(j + 1) % 2, tx, i, 0] = A_local[i % 2, 0, 0, j + 1] * T.float32( 2 ) with T.block(): T.reads([B[j % 2, tx, i, 0]]) T.writes([C[tx, i, j]]) C[tx, i, j] = B[j % 2, tx, i, 0] + T.float32(1) with T.block(): T.reads([A_shared[tx, 0, 0:16]]) T.writes([A_local[(i + 1) % 2, 0, 0, 0:16]]) for j in T.serial(0, 16): with T.block(): T.reads([A_shared[tx, 0, j]])
T.writes([A_local[(i + 1) % 2, 0, 0, j]]) T.block_attr({"double_buffer_scope": 0}) A_local[(i + 1) % 2, 0, 0, j] = A_shared[tx, i + 1, j] with T.block(): T.reads([A_local[(i + 1) % 2, tx, i + 1, 0]]) T.writes([B[0, tx, i + 1, 0]]) B[0, tx, i + 1, 0] = A_local[(i + 1) % 2, 0, 0, 0] * T.float32(2) with T.block(): T.reads([B[1, tx, i, 0]]) T.writes([C[tx, i, 15]]) C[tx, i, 15] = B[1, tx, i, 0] + T.float32(1) with T.block(): T.reads([A_local[1, tx, 15, 1:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:16]]) with T.block(): T.reads([A_local[1, tx, 15, 1:16], B[0:2, tx, 15, 0]]) T.writes([B[0:2, tx, 15, 0], C[tx, 15, 0:15]]) for j in T.serial(0, 15): with T.block(): T.reads([A_local[1, tx, 15, j + 1]]) T.writes([B[(j + 1) % 2, tx, 15, 0]]) B[(j + 1) % 2, tx, 15, 0] = A_local[1, 0, 0, j + 1] * T.float32(2) with T.block(): T.reads([B[j % 2, tx, 15, 0]]) T.writes([C[tx, 15, j]]) C[tx, 15, j] = B[j % 2, tx, 15, 0] + T.float32(1) with T.block(): T.reads([B[1, tx, 15, 0]]) T.writes([C[tx, 15, 15]]) C[tx, 15, 15] = B[1, tx, 15, 0] + T.float32(1) @T.prim_func def simple_compute_incorrect_reorder( A: T.Buffer[(16, 16), "float32"], D: T.Buffer[(16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage":
[0, 1, 1], "software_pipeline_order": [0, 2, 1], }, ): with T.block(): T.reads(A[tx, i]) T.writes(D[tx, i]) B = T.alloc_buffer((16, 1), dtype="float32", scope="shared") C = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(B[tx, 0]) B[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(C[tx, 0]) C[tx, 0] = B[tx, 0] + T.float32(2) with T.block(): T.reads(C[tx, 0]) T.writes(D[tx, i]) D[tx, i] = C[tx, 0] + T.float32(1) @T.prim_func def simple_compute_conflicting_order( A: T.Buffer[(16, 16), "float32"], D: T.Buffer[(16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial( 0, 16, annotations={ "software_pipeline_stage": [0, 1, 1], "software_pipeline_order": [0, 1, 1], }, ): with T.block(): T.reads(A[tx, i]) T.writes(D[tx, i]) B = T.alloc_buffer((16, 1), dtype="float32", scope="shared") C = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(B[tx, 0]) B[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(C[tx, 0]) C[tx, 0] = B[tx, 0] + T.float32(2) with T.block(): T.reads(C[tx, 0]) T.writes(D[tx, i]) D[tx, i] = C[tx, 0] + T.float32(1) @T.prim_func def simple_compute_missing_annotation( A: T.Bu
ffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"] ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in T.serial(0, 16, annotations={"software_pipeline_stage": [0, 1]}): with T.block(): T.reads(A[tx, i]) T.writes(C[tx, i]) B = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(B[tx, 0]) B[tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(B[tx, 0]) T.writes(C[tx, i]) C[tx, i] = B[tx, 0] + T.float32(1) def test_simple_compute(): _check(gen_simple_compute(1), transformed_simple_compute) def test_simple_compute_with_other_annotation(): _check(simple_compute_with_other_annotation, transformed_simple_compute_with_other_annotation) def test_trivial_pipeline(): _check(trivial_pipeline, transformed_trivial_pipeline) def test_three_stage_compute(): _check(three_stage_compute, transformed_three_stage_compute) def test_dag_interleaving(): _check(dag_interleaving, transformed_dag_interleaving) def test_nest_pipeline_simple(): _check(nested_pipeline_simple, transformed_nested_pipeline_simple) def test_nest_pipeline_prefetch_inner(): _check(nested_pipeline_prefetch_inner, transformed_nested_pipeline_prefetch_inner) def test_nest_pipeline_interleaving(): _check(nested_pipeline_interleaving, transformed_nested_pipeline_interleaving) def test_nest_pipeline_double_buffer(): _check(nested_pipeline_double_buffer, transformed_nested_pipeline_double_buffer) def test_error_reorder(): _check_error(simple_compute_incorrect_reorder) def test_error_conflicting_order(): _check_error(simple_compute_conflicting_order) def test_error_missing_annotation(): _check_error(simple_compute_missing_annotation) def test_simple_compute_async(): mod = tvm.IRModule.from_expr(gen_s
imple_compute(1)) sch = tvm.tir.Schedule(mod) _, loop = sch.get_loops(sch.get_block("compute")) sch.annotate(loop, ann_key="software_pipeline_async_stages", ann_val=[0]) mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod) @T.prim_func def ref(A: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"]): for tx in T.thread_binding(16, thread="threadIdx.x"): with T.block(): T.reads(A[tx, 0:16]) T.writes(C[tx, 0:16]) B = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads(A[tx, 0]) T.writes(B[0, tx, 0]) with T.attr(0, "async_commit_queue_scope", 0): with T.attr(0, "async_scope", 1): B[T.FloorMod(0, 2), tx, 0] = A[tx, 0] * T.float32(2) with T.block(): T.reads(A[tx, 1:16], B[0:2, tx, 0]) T.writes(B[0:2, tx, 0], C[tx, 0:15]) for i in T.serial(15): with T.block(): T.where(i + 1 < 16) T.reads(A[tx, i + 1]) T.writes(B[(i + 1) % 2, tx, 0]) with T.attr(0, "async_commit_queue_scope", 0): with T.attr(0, "async_scope", 1): B[(i + 1) % 2, tx, 0] = A[tx, i + 1] * T.float32(2) with T.block(): T.where(i + 1 - 1 < 16) T.reads(B[(i - 1 + 1) % 2, tx, 0]) T.writes(C[tx, i - 1 + 1]) with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 1): C[tx, i - 1 + 1] = B[(i - 1 + 1) % 2, tx, 0] + T.float32(1) with T.block(): T.reads(B[T.Flo
orMod(15, 2), tx, 0]) T.writes(C[tx, 15]) with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 0): C[tx, 15] = B[T.FloorMod(15, 2), tx, 0] + T.float32(1) tvm.ir.assert_structural_equal(mod["main"], ref, True) mod = tvm.IRModule.from_expr(gen_simple_compute(3)) sch = tvm.tir.Schedule(mod) _, loop = sch.get_loops(sch.get_block("compute")) sch.annotate(loop, ann_key="software_pipeline_async_stages", ann_val=[0]) mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod) @T.prim_func def ref(A: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"]) -> None: for tx in T.thread_binding(16, thread="threadIdx.x"): with T.block(): T.reads(A[tx, 0:16]) T.writes(C[tx, 0:16]) B = T.alloc_buffer([4, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads(A[tx, 0:3]) T.writes(B[0:3, tx, 0]) for i in T.unroll(3): with T.block(): T.where(i < 16) T.reads(A[tx, i]) T.writes(B[i % 4, tx, 0]) T.attr(0, "async_commit_queue_scope", 0) T.attr(0, "async_scope", 1) B[i % 4, tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.reads(A[tx, 3:16], B[0:4, tx, 0]) T.writes(B[0:4, tx, 0], C[tx, 0:13]) for i in T.serial(13): with T.block(): T.where(i + 3 < 16) T.reads(A[tx, i + 3]) T.writes(B[(i + 3) % 4, tx, 0]) T.attr(0, "async_commit_queue_scope", 0) T.attr(0, "async_scope", 1)
B[(i + 3) % 4, tx, 0] = A[tx, i + 3] * T.float32(2) with T.block(): T.where(i + 3 - 3 < 16) T.reads(B[0:4, tx, 0]) T.writes(C[tx, i - 3 + 3]) with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 3): C[tx, i - 3 + 3] = B[(i - 3 + 3) % 4, tx, 0] + T.float32(1) with T.block(): T.reads(B[0:4, tx, 0]) T.writes(C[tx, 13:16]) for i in T.unroll(3): with T.block(): T.where(i + 16 - 3 < 16) T.reads(B[0:4, tx, 0]) T.writes(C[tx, i - 3 + 16]) with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 2 - i): C[tx, i - 3 + 16] = B[(i - 3 + 16) % 4, tx, 0] + T.float32(1) tvm.ir.assert_structural_equal(mod["main"], ref, True) def test_async_producer_interleaving(): @T.prim_func def simple_compute( A: T.Buffer[(16, 16), "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ): for tx in T.thread_binding(0, 16, thread="threadIdx.x"): for i in range(16): with T.block("compute"): T.reads(A[tx, i]) T.writes(C[tx, i]) A_shared = T.alloc_buffer((16, 1), dtype="float32", scope="shared") B_shared = T.alloc_buffer((16, 1), dtype="float32", scope="shared") with T.block(): T.reads(A[tx, i]) T.writes(A_shared[tx, 0]) A_shared[tx, 0] = A[tx, i] with T.block(): T.reads(B[tx, i])
T.writes(B_shared[tx, 0]) B_shared[tx, 0] = B[tx, i] with T.block(): T.reads(A_shared[tx, 0], B_shared[tx, 0]) T.writes(C[tx, i]) C[tx, i] = A_shared[tx, 0] + B_shared[tx, 0] mod = tvm.IRModule.from_expr(simple_compute) sch = tvm.tir.Schedule(mod) _, loop = sch.get_loops(sch.get_block("compute")) sch.annotate(loop, ann_key="software_pipeline_stage", ann_val=[0, 0, 3]) sch.annotate(loop, ann_key="software_pipeline_order", ann_val=[0, 2, 1]) sch.annotate(loop, ann_key="software_pipeline_async_stages", ann_val=[0]) mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod) @T.prim_func def ref( A: T.Buffer[(16, 16), "float32"], B: T.Buffer[(16, 16), "float32"], C: T.Buffer[(16, 16), "float32"], ) -> None: for tx in T.thread_binding(16, thread="threadIdx.x"): with T.block(): T.reads(A[tx, 0:16], B[tx, 0:16]) T.writes(C[tx, 0:16]) A_shared = T.alloc_buffer([4, 16, 1], dtype="float32", scope="shared") B_shared = T.alloc_buffer([4, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads(A[tx, 0:3], B[tx, 0:3]) T.writes(A_shared[0:3, tx, 0], B_shared[0:3, tx, 0]) for i in T.unroll(3): with T.block(): T.where(i < 16) T.reads(A[tx, i], B[tx, i]) T.writes(A_shared[i % 4, tx, 0], B_shared[i % 4, tx, 0]) with T.attr(0, "async_commit_queue_scope", 0): with T.attr(0, "async_scope", 1): A_shared[i % 4, tx, 0] = A[tx, i] with T.attr(0, "async_scope", 1): B_shared[i % 4, tx, 0] = B[tx, i]
with T.block(): T.reads(A[tx, 3:16], A_shared[0:4, tx, 0], B_shared[0:4, tx, 0], B[tx, 3:16]) T.writes(A_shared[0:4, tx, 0], C[tx, 0:13], B_shared[0:4, tx, 0]) for i in T.serial(13): with T.block(): T.where(i + 3 < 16) T.reads(A[tx, i + 3]) T.writes(A_shared[(i + 3) % 4, tx, 0]) with T.attr(0, "async_commit_queue_scope", 0): with T.attr(0, "async_scope", 1): A_shared[(i + 3) % 4, tx, 0] = A[tx, i + 3] with T.block(): T.where(i + 3 - 3 < 16) T.reads(A_shared[0:4, tx, 0], B_shared[0:4, tx, 0]) T.writes(C[tx, i - 3 + 3]) with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 5): C[tx, i - 3 + 3] = ( A_shared[(i - 3 + 3) % 4, tx, 0] + B_shared[(i - 3 + 3) % 4, tx, 0] ) with T.block(): T.where(i + 3 < 16) T.reads(B[tx, i + 3]) T.writes(B_shared[(i + 3) % 4, tx, 0]) with T.attr(0, "async_commit_queue_scope", 0): with T.attr(0, "async_scope", 1): B_shared[(i + 3) % 4, tx, 0] = B[tx, i + 3] with T.block(): T.reads(A_shared[0:4, tx, 0], B_shared[0:4, tx, 0]) T.writes(C[tx, 13:16]) for i in T.unroll(3): with T.block(): T.where(i + 16 - 3 < 16) T.reads(A_share
d[0:4, tx, 0], B_shared[0:4, tx, 0]) T.writes(C[tx, i - 3 + 16]) with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 2 - i): C[tx, i - 3 + 16] = ( A_shared[(i - 3 + 16) % 4, tx, 0] + B_shared[(i - 3 + 16) % 4, tx, 0] ) tvm.ir.assert_structural_equal(mod["main"], ref, True) def test_three_stage_compute_two_stage_async(): mod = tvm.IRModule.from_expr(three_stage_compute) sch = tvm.tir.Schedule(mod) _, loop = sch.get_loops(sch.get_block("compute")) sch.annotate(loop, ann_key="software_pipeline_async_stages", ann_val=[0, 1]) mod = tvm.tir.transform.InjectSoftwarePipeline()(sch.mod) @T.prim_func def ref(A: T.Buffer[(16, 16), "float32"], D: T.Buffer[(16, 16), "float32"]) -> None: for tx in T.thread_binding(16, thread="threadIdx.x"): with T.block(): T.reads(A[tx, 0:16]) T.writes(D[tx, 0:16]) B = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") C = T.alloc_buffer([2, 16, 1], dtype="float32", scope="shared") with T.block(): T.reads(A[tx, 0:2], B[0:2, tx, 0]) T.writes(B[0:2, tx, 0], C[0:2, tx, 0]) for i in T.unroll(2): with T.block(): T.where(i < 16) T.reads(A[tx, i]) T.writes(B[i % 2, tx, 0]) with T.attr(0, "async_commit_queue_scope", 0): with T.attr(0, "async_scope", 1): B[i % 2, tx, 0] = A[tx, i] * T.float32(2) with T.block(): T.where(i == 1 and i - 1 < 16) T.reads
(B[(i + 1) % 2, tx, 0]) T.writes(C[(i + 1) % 2, tx, 0]) with T.attr(0, "async_commit_queue_scope", 1): with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 1): with T.attr(0, "async_scope", 1): C[(i - 1) % 2, tx, 0] = B[ (i - 1) % 2, tx, 0 ] + T.float32(2) with T.block(): T.reads(A[tx, 2:16], B[0:2, tx, 0], C[0:2, tx, 0]) T.writes(B[0:2, tx, 0], C[0:2, tx, 0], D[tx, 0:14]) for i in T.serial(14): with T.block(): T.where(i + 2 < 16) T.reads(A[tx, i + 2]) T.writes(B[i % 2, tx, 0]) with T.attr(0, "async_commit_queue_scope", 0): with T.attr(0, "async_scope", 1): B[(i + 2) % 2, tx, 0] = A[tx, i + 2] * T.float32(2) with T.block(): T.where(i + 2 - 1 < 16) T.reads(B[(i + 1) % 2, tx, 0]) T.writes(C[(i + 1) % 2, tx, 0]) with T.attr(0, "async_commit_queue_scope", 1): with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 1): with T.attr(0, "async_scope", 1): C[(i - 1 + 2) % 2, tx, 0] = B[ (i - 1 + 2) % 2, tx, 0 ] + T.float32(2) with T.block(): T.where(i + 2 - 2 <
16) T.reads(C[0:2, tx, 0]) T.writes(D[tx, i - 2 + 2]) with T.attr(0, "async_wait_queue_scope", 1): with T.attr(0, "async_wait_inflight_count", 1): D[tx, i - 2 + 2] = C[(i - 2 + 2) % 2, tx, 0] + T.float32(1) with T.block(): T.reads(B[0:2, tx, 0], C[0:2, tx, 0]) T.writes(C[0:2, tx, 0], D[tx, 14:16]) for i in T.unroll(2): with T.block(): T.where(i + 16 - 1 < 16) T.reads(B[(i + 1) % 2, tx, 0]) T.writes(C[(i + 1) % 2, tx, 0]) with T.attr(0, "async_commit_queue_scope", 1): with T.attr(0, "async_wait_queue_scope", 0): with T.attr(0, "async_wait_inflight_count", 0 - i): with T.attr(0, "async_scope", 1): C[(i - 1 + 16) % 2, tx, 0] = B[ (i - 1 + 16) % 2, tx, 0 ] + T.float32(2) with T.block(): T.where(i + 16 - 2 < 16) T.reads(C[0:2, tx, 0]) T.writes(D[tx, i - 2 + 16]) with T.attr(0, "async_wait_queue_scope", 1): with T.attr( 0, "async_wait_inflight_count", T.if_then_else(i + 16 - 1 < 16, 1, 0, dtype="int32"), ): D[tx, i - 2 + 16] = C[(i - 2 + 16) % 2, tx, 0] + T.float32(1) tvm.ir.assert_structural_equal(mod["main"], ref, True) N = K = M = 4096 def get_mma_schedule(): i_factors,
j_factors, k_factors = [1, 32, 1, 4, 2], [16, 2, 4, 1, 2], [128, 2, 1] def index_map(i, j): return ( i j *shared_16x16_to_ldmatrix_32x8_layout(i % 16, j % 16), ) workload = te.create_prim_func( te_workload.matmul(N, M, K, in_dtype="float16", out_dtype="float32") ) return mma_schedule( workload, 16, "float16", False, i_factors, j_factors, k_factors, index_map, index_map, index_map, LDMATRIX_16x16_A_DYN_INTRIN, LDMATRIX_16x16_B_DYN_INTRIN, MMA_f16f16f32_INTRIN, MMA_fill_16x16_f32_INTRIN, MMA_store_16x16_f32_global_INTRIN, "shared.dyn", ) def build_and_run(sch): if tvm.testing.is_ampere_or_newer(): with tvm.transform.PassContext(config={"tir.use_async_copy": 1}): f = tvm.build(sch.mod["main"], target="cuda") dev = tvm.device("cuda", 0) a_np = np.random.uniform(size=(N, K)).astype("float16") b_np = np.random.uniform(size=(K, M)).astype("float16") c_np = np.dot(a_np.astype("float32"), b_np.astype("float32")) a = tvm.nd.array(a_np, dev) b = tvm.nd.array(b_np, dev) c = tvm.nd.array(np.zeros((N, M), dtype="float32"), dev) f(a, b, c) tvm.testing.assert_allclose(c.numpy(), c_np, rtol=1e-3) @tvm.testing.requires_cuda def test_async_pipelined_mma_gemm_simple(): sch = get_mma_schedule() k0 = sch.get_loops(sch.get_block("C_o_update"))[3] sch.annotate(k0, ann_key="software_pipeline_stage", ann_val=[0, 0, 3]) sch.annotate(k0, ann_key="software_pipeline_order", ann_val=[0, 1, 2]) sch.annotate(k0, ann_key="software_pipeline_async_stages", ann_val=[0]) seq = tvm.transform.Sequential( [ tvm.tir.transform.PlanAndUpdateBufferAllocationLocation(), tvm.tir.transform.ConvertBlocksToOpaque(), tvm.tir.transform.UnifyThreadBinding(), tvm.tir.transfor
m.LowerMatchBuffer(), tvm.tir.transform.InjectSoftwarePipeline(), ] ) mod = seq(sch.mod) pipeline = mod["main"].body.block.body.body.body.body.body.block.body[1].block.body prologue, body, epilogue = pipeline commit_queue_scope = prologue.block.body.body.block.body assert len(commit_queue_scope.body) == 2 assert commit_queue_scope.value == 0 commit_queue_scope = body.block.body.body[0].block.body assert len(commit_queue_scope.body) == 2 assert commit_queue_scope.value == 0 assert body.block.body.body[1].block.body.body.attr_key == "async_wait_inflight_count" assert body.block.body.body[1].block.body.body.value == 3 assert epilogue.block.body.body.block.body.body.attr_key == "async_wait_inflight_count" assert str(epilogue.block.body.body.block.body.body.value) == "(2 - i2_0_0: int32)" build_and_run(sch) @tvm.testing.requires_cuda def test_async_nested_pipeline_mma_gemm_ideal_annotation(): sch = get_mma_schedule() k0 = sch.get_loops(sch.get_block("C_o_update"))[3] k1 = sch.get_loops(sch.get_block("C_o_update"))[4] sch.annotate(k0, ann_key="software_pipeline_stage", ann_val=[0, 0, 2, 3, 3]) sch.annotate(k0, ann_key="software_pipeline_order", ann_val=[0, 1, 3, 2, 4]) sch.annotate(k0, ann_key="software_pipeline_async_stages", ann_val=[0]) sch.annotate(k1, ann_key="software_pipeline_stage", ann_val=[0, 0, 1]) sch.annotate(k1, ann_key="software_pipeline_order", ann_val=[0, 1, 2]) seq = tvm.transform.Sequential( [ tvm.tir.transform.PlanAndUpdateBufferAllocationLocation(), tvm.tir.transform.ConvertBlocksToOpaque(), tvm.tir.transform.UnifyThreadBinding(), tvm.tir.transform.LowerMatchBuffer(), tvm.tir.transform.InjectSoftwarePipeline(), ] ) mod = seq(sch.mod) pipeline = mod["main"].body.block.body.body.body.body.body.block.body[1].block.body prologue, body, epilogue = pipeline commit_queue_scope = prol
ogue.block.body.body[0].block.body assert len(commit_queue_scope.body) == 2 assert commit_queue_scope.value == 0 assert prologue.block.body.body[1].block.body.body.attr_key == "async_wait_inflight_count" assert prologue.block.body.body[1].block.body.body.value == 2 commit_queue_scope = body.block.body.body[0].block.body assert len(commit_queue_scope.body) == 2 assert commit_queue_scope.value == 0 assert body.block.body.body[1].block.body.body.attr_key == "async_wait_inflight_count" assert body.block.body.body[1].block.body.body.value == 2 assert str(epilogue.block.body.body[0].block.body.body.value) == "(1 - i2_0_0: int32)" build_and_run(sch) if __name__ == "__main__": tvm.testing.main()
import tvm
import tvm.testing from tvm
import te from tvm.script
import tir as T vthread_name = tvm.testing.parameter("vthread", "cthread") def test_vthread(vthread_name): dtype = "int64" n = 100 m = 4 nthread = 2 def get_vthread(name): tx = te.thread_axis(name) ty = te.thread_axis(name) ib = tvm.tir.ir_builder.create() A = ib.pointer("float32", name="A") C = ib.pointer("float32", name="C") with ib.for_range(0, n) as i: ib.scope_attr(tx, "virtual_thread", nthread) ib.scope_attr(ty, "virtual_thread", nthread) B = ib.allocate("float32", m, name="B", scope="shared") B[i] = A[i * nthread + tx] bbuffer = B.asobject() ib.emit( tvm.tir.call_extern( "int32", "Run", bbuffer.access_ptr("r"), tvm.tir.call_intrin("int32", "tir.tvm_context_id"), ) ) C[i * nthread + tx] = B[i] + 1 return ib.get() if vthread_name == "vthread": B_expected_alloc = m * nthread elif vthread_name == "cthread": B_expected_alloc = m * nthread * nthread stmt = tvm.tir.transform.InjectVirtualThread()( tvm.IRModule.from_expr(tvm.tir.PrimFunc([], get_vthread(vthread_name))) )["main"] assert list(stmt.body.body.extents) == [B_expected_alloc] def test_vthread_extern(vthread_name): dtype = "int64" n = 100 m = 4 nthread = 2 def get_vthread(name): tx = te.thread_axis(name) ty = te.thread_axis(name) ib = tvm.tir.ir_builder.create() with ib.for_range(0, n) as i: ib.scope_attr(tx, "virtual_thread", nthread) ib.scope_attr(ty, "virtual_thread", nthread) A = ib.allocate("float32", m, name="A", scope="shared") B = ib.allocate("float32", m, name="B", scope="shared") C = ib.allocate("float32", m, name="C", scope="shared") abuffer = A.asobject() bbuffer = B.asobject()
cbuffer = C.asobject() A[tx] = tx + 1.0 B[ty] = ty + 1.0 ib.emit( tvm.tir.call_extern( "int32", "Run", abuffer.access_ptr("r"), bbuffer.access_ptr("r"), cbuffer.access_ptr("rw"), ) ) return ib.get() if vthread_name == "vthread": A_expected_alloc = m * nthread elif vthread_name == "cthread": A_expected_alloc = m * nthread * nthread C_expected_alloc = m * nthread * nthread stmt = tvm.tir.transform.InjectVirtualThread()( tvm.IRModule.from_expr(tvm.tir.PrimFunc([], get_vthread(vthread_name))) )["main"] assert list(stmt.body.body.extents) == [A_expected_alloc] assert list(stmt.body.body.body.body.extents) == [C_expected_alloc] def test_vthread_if_then_else(): nthread = 2 tx = te.thread_axis("vthread") ib = tvm.tir.ir_builder.create() A = ib.pointer("float32", name="A") with ib.for_range(0, 100) as i: ib.scope_attr(tx, "virtual_thread", nthread) B = ib.allocate("float32", 128, name="B", scope="shared") with ib.if_scope(i == 0): B[i] = A[i * nthread + tx] with ib.else_scope(): B[i] = A[i * nthread + tx] + 1 with ib.if_scope(i == 0): B[i] = A[i * nthread + tx] + 2 stmt = ib.get() stmt = tvm.tir.transform.InjectVirtualThread()( tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) )["main"] assert stmt.body.body.body[0].else_case != None assert stmt.body.body.body[1].else_case == None def test_vthread_simplified(): """Indices resulting from vthread injection should simplified This ensures that downstream passes that check for Ramp nodes do not need to each simplify the indices. """ @T.prim_func def before_func(): vthread = T.env_thread("vthread") T.launch_thread(vthread, 4) B_data = T.allocate([4]
, "int32", scope="shared") B = T.buffer_decl([4], "int32", data=B_data, scope="shared") B[0:4] = T.broadcast(vthread, 4) @T.prim_func def expected_func(): B_data = T.allocate([16], "int32", scope="shared") B = T.buffer_decl([16], "int32", data=B_data, scope="shared") B[T.Mul(0, 4) : T.Mul(0, 4) + 4] = T.broadcast(0, 4) B[T.Mul(1, 4) : T.Mul(1, 4) + 4] = T.broadcast(1, 4) B[T.Mul(2, 4) : T.Mul(2, 4) + 4] = T.broadcast(2, 4) B[T.Mul(3, 4) : T.Mul(3, 4) + 4] = T.broadcast(3, 4) before_mod = tvm.IRModule.from_expr(before_func) after_mod = tvm.tir.transform.InjectVirtualThread()(before_mod) after_func = after_mod["main"] tvm.ir.assert_structural_equal(after_func, expected_func) def test_vthread_vectorized(): """Use of vthread is compatible with vector allocations""" @T.prim_func def before_func(): vthread = T.env_thread("vthread") T.launch_thread(vthread, 4) B_data = T.allocate([4], "int32", "shared") B = T.buffer_decl([4], "int32", data=B_data, scope="shared") B[0:4] = T.broadcast(vthread, 4) @T.prim_func def expected_func(): B_data = T.allocate([4], "int32x4", "shared") B = T.buffer_decl([4], "int32x4", data=B_data, scope="shared") B[T.Mul(0, 4) / 4] = T.broadcast(0, 4) B[T.Mul(1, 4) / 4] = T.broadcast(1, 4) B[T.Mul(2, 4) / 4] = T.broadcast(2, 4) B[T.Mul(3, 4) / 4] = T.broadcast(3, 4) before_mod = tvm.IRModule.from_expr(before_func) intermediate_mod = tvm.tir.transform.InjectVirtualThread()(before_mod) after_mod = tvm.tir.transform.StorageRewrite()(intermediate_mod) after_func = after_mod["main"] tvm.ir.assert_structural_equal(after_func, expected_func) if __name__ == "__main__": tvm.testing.main()
import pytest
import tvm
import tvm.testing from tvm
import te
import numpy as np def collect_visit(stmt, f): ret = [] tvm.tir.stmt_functor.post_order_visit(stmt, lambda x: ret.append(f(x))) return ret @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_llvm(index_a, index_b): n = te.size_var("n") A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") C = te.compute(A.shape, lambda i: A[i + index_a] + B[i + index_b], name="C") s = te.create_schedule(C.op) tgt = "llvm" tgt_host = "llvm" stmt = tvm.lower(s, [A, B, C], simple_mode=True) print(stmt) tgt = tvm.target.Target(tgt, tgt_host) fadd = tvm.build(s, [A, B, C], target=tgt, name="myadd") dev = tvm.device(tgt.kind.name, 0) a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=1024).astype(B.dtype), dev) c = tvm.nd.array(np.zeros(1024, dtype=C.dtype), dev) fadd(a, b, c) @tvm.testing.requires_llvm def test_in_bounds_llvm(): n = te.size_var("n") A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") C = te.compute(A.shape, lambda i: A[i] + B[i], name="C") s = te.create_schedule(C.op) tgt = "llvm" tgt_host = "llvm" stmt = tvm.lower(s, [A, B, C], simple_mode=True) tgt = tvm.target.Target(tgt, tgt_host) fadd = tvm.build(s, [A, B, C], target=tgt, name="myadd") dev = tvm.device(tgt.kind.name, 0) a = tvm.nd.array(np.random.uniform(size=1024).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=1024).astype(B.dtype), dev) c = tvm.nd.array(np.zeros(1024, dtype=C.dtype), dev) fadd(a, b, c) @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_vectorize_llvm(nn, index_a, index_b): n = tvm.runtime.convert(nn) a = te.placeholder((n), name="a") b = te.placeholder((n), name="b") c = te.compute((n,), lambda i: a[i + index_a] + b[i + index_b], name="c") s = te.create_schedule(c.op) xo, xi = s[c].split(c.op.axis[0], factor=8) s[c].parallel(xo) s[c]
.vectorize(xi) tgt = "llvm" tgt_host = "llvm" stmt = tvm.lower(s, [a, b, c], simple_mode=True) tgt = tvm.target.Target(tgt, tgt_host) f = tvm.build(s, [a, b, c], target=tgt, name="myaddvec") dev = tvm.cpu(0) n = nn a = tvm.nd.array(np.random.uniform(size=(n)).astype(a.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(n)).astype(a.dtype), dev) c = tvm.nd.array(np.zeros(n, dtype=c.dtype), dev) f(a, b, c) @tvm.testing.requires_llvm def test_in_bounds_vectorize_llvm(): n = 512 lanes = 2 A = te.placeholder((n,), name="A", dtype="float32x%d" % lanes) B = te.compute((n,), lambda i: A[i], name="B") C = te.compute((n,), lambda i: B[i] + tvm.tir.const(1, A.dtype), name="C") s = te.create_schedule(C.op) xo, xi = s[C].split(C.op.axis[0], nparts=2) _, xi = s[C].split(xi, factor=2) s[C].parallel(xo) s[C].vectorize(xi) s[B].compute_at(s[C], xo) xo, xi = s[B].split(B.op.axis[0], factor=2) s[B].vectorize(xi) lowered_func = tvm.lower(s, [A, C], "llvm", simple_mode=False) f = tvm.build(s, [A, C], "llvm") dev = tvm.cpu(0) a = tvm.nd.empty((n,), A.dtype).copyfrom( np.random.uniform(size=[n] + ([] if lanes == 1 else [lanes])) ) c = tvm.nd.empty((n,), C.dtype, dev) f(a, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + 1) @tvm.testing.requires_llvm def test_in_bounds_loop_partition_basic_llvm(): n = te.size_var("n") A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i] + B[i]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(32,)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(32,)).astype(B.dtype), dev) t = tvm.nd.empty((32,), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm
@pytest.mark.xfail def test_out_of_bounds_loop_partition_basic_llvm(index_a, index_b): n = te.size_var("n") A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i + index_a] + B[i + index_b]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(32,)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(32,)).astype(B.dtype), dev) t = tvm.nd.empty((32,), T.dtype, dev) f(a, b, t) def test_in_bounds_const_loop_partition_ir(): def check_attr_stmt(x): if ( isinstance(x, tvm.tir.AttrStmt) and x.attr_key == "buffer_bound" and tvm.ir.structural_equal(x.value.args, [n]) ): return True return False def check_branch_stmt(x): if isinstance(x, tvm.tir.IfThenElse): return True return False def assert_bound_instrumentation(stmt, f, nums): count = 0 for i in collect_visit(stmt, f): if i is True: count = count + 1 assert count == nums def collect_branch_stmt(x): if isinstance(x, tvm.tir.IfThenElse): branch_collector.append(x) n = 21 A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i] + B[i]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) with tvm.transform.PassContext( config={ "tir.instrument_bound_checkers": True, "tir.LoopPartition": {"partition_const_loop": True}, } ): mod = tvm.driver.lower(s, [A, B, T], name="main") stmt = mod["main"].body assert_bound_instrumentation(stmt, check_attr_stmt, 2 * 3) assert_bound_instrumentation(stmt, check_branch_stmt, 2) branch_co
llector = list() collect_visit(stmt, collect_branch_stmt) assert len(branch_collector) == 2 @tvm.testing.requires_llvm def test_in_bounds_const_loop_partition_llvm(): with tvm.transform.PassContext( config={ "tir.instrument_bound_checkers": True, "tir.LoopPartition": {"partition_const_loop": True}, } ): n = 21 A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i] + B[i]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(n,)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(n,)).astype(B.dtype), dev) t = tvm.nd.empty((n,), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_const_loop_partition_llvm(index_a, index_b): with tvm.transform.PassContext( config={ "tir.instrument_bound_checkers": True, "tir.LoopPartition": {"partition_const_loop": True}, } ): n = 21 A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i + index_a] + B[i + index_b]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(n,)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(n,)).astype(B.dtype), dev) t = tvm.nd.empty((n,), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm def test_in_bounds_conv_llvm(loop_tiling=False): HSTR = WSTR = 1 in_channel = 128 kernel_height = kernel_width = 3
out_channel = 64 batch_size = 1 in_height = in_width = 64 out_height = out_width = in_height - kernel_height + 1 data = te.placeholder((batch_size, in_channel, in_height, in_width), name="data") kernel = te.placeholder((kernel_height, kernel_width, in_channel, out_channel), name="kernel") ic = te.reduce_axis((0, in_channel), name="ic") kh = te.reduce_axis((0, kernel_height), name="kh") kw = te.reduce_axis((0, kernel_width), name="kw") conv = te.compute( (batch_size, out_channel, out_height, out_width), lambda n, oc, oh, ow: te.sum( data[n, ic, oh * HSTR + kh, ow * WSTR + kw] * kernel[kh, kw, ic, oc], axis=[ic, kh, kw] ), name="conv2d", ) s = te.create_schedule(conv.op) n, oc, oh, ow = conv.op.axis if loop_tiling: oho, owo, ohi, owi = s[conv].tile(oh, ow, 16, 16) lowered_func = tvm.lower(s, [data, kernel, conv], simple_mode=True) dev = tvm.cpu(0) f = tvm.build(s, [data, kernel, conv], "llvm") data_input = tvm.nd.array( np.random.uniform(size=(batch_size, in_channel, in_height, in_width)).astype("float32"), dev ) kernel_input = tvm.nd.array( np.random.uniform(size=(kernel_height, kernel_width, in_channel, out_channel)).astype( "float32" ), dev, ) conv_out = tvm.nd.empty((batch_size, out_channel, out_height, out_width), "float32", dev) f(data_input, kernel_input, conv_out) @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_conv_llvm(data_offsets, kernel_offsets, loop_tiling=False): HSTR = WSTR = 1 in_channel = 128 kernel_height = kernel_width = 3 out_channel = 64 batch_size = 1 in_height = in_width = 64 out_height = out_width = in_height - kernel_height + 1 data = te.placeholder((batch_size, in_channel, in_height, in_width), name="data") kernel = te.placeholder((kernel_height, kernel_width, in_channel, out_channel), name="kernel") ic = te.reduce_axis((0, in_channel), name
="ic") kh = te.reduce_axis((0, kernel_height), name="kh") kw = te.reduce_axis((0, kernel_width), name="kw") conv = te.compute( (batch_size, out_channel, out_height, out_width), lambda n, oc, oh, ow: te.sum( data[ n + data_offsets[0], ic + data_offsets[1], oh * HSTR + kh + data_offsets[2], ow * WSTR + kw + data_offsets[3], ] * kernel[ kh + kernel_offsets[0], kw + kernel_offsets[1], ic + kernel_offsets[2], oc + kernel_offsets[3], ], axis=[ic, kh, kw], ), name="conv2d", ) s = te.create_schedule(conv.op) n, oc, oh, ow = conv.op.axis if loop_tiling: oho, owo, ohi, owi = s[conv].tile(oh, ow, 16, 16) lowered_func = tvm.lower(s, [data, kernel, conv], simple_mode=True) dev = tvm.cpu(0) f = tvm.build(s, [data, kernel, conv], "llvm") data_input = tvm.nd.array( np.random.uniform(size=(batch_size, in_channel, in_height, in_width)).astype("float32"), dev ) kernel_input = tvm.nd.array( np.random.uniform(size=(kernel_height, kernel_width, in_channel, out_channel)).astype( "float32" ), dev, ) conv_out = tvm.nd.empty((batch_size, out_channel, out_height, out_width), "float32", dev) f(data_input, kernel_input, conv_out) @tvm.testing.requires_llvm def test_in_bounds_tensors_with_same_shapes1D_llvm(): n = te.size_var("n") k = te.size_var("k") m = te.size_var("m") A = te.placeholder((n,), name="A") B = te.placeholder((k,), name="B") T = te.compute((m,), lambda i: A[i] * B[i]) s = te.create_schedule(T.op) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(32,)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(32,)).astype(B.dtype),
dev) t = tvm.nd.empty((32,), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_tensors_with_diff_shapes1D_llvm(a_shape, b_shape, c_shape): n = te.size_var("n") k = te.size_var("k") m = te.size_var("m") A = te.placeholder((n,), name="A") B = te.placeholder((k,), name="B") T = te.compute((m,), lambda i: A[i] * B[i]) s = te.create_schedule(T.op) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(a_shape,)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(b_shape,)).astype(B.dtype), dev) t = tvm.nd.empty((c_shape,), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm def test_in_bounds_tensors_with_same_shapes2D_llvm(): n = te.size_var("n") k = te.size_var("k") m = te.size_var("m") A = te.placeholder((n, n), name="A") B = te.placeholder((k, k), name="B") T = te.compute((m, m), lambda i, j: A[i][j] * B[i][j]) s = te.create_schedule(T.op) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(32, 32)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(32, 32)).astype(B.dtype), dev) t = tvm.nd.empty((32, 32), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_tensors_with_diff_shapes2D_llvm(a_shape, b_shape, c_shape): n = te.size_var("n") k = te.size_var("k") m = te.size_var("m") A = te.placeholder((n, n), name="A") B = te.placeholder((k, k), name="B") T = te.compute((m, m), lambda i, j: A[i][j] * B[i][j]) s = te.create_schedule(T.op) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(a_shape[0], a_shape[1])).astype(A.d
type), dev) b = tvm.nd.array(np.random.uniform(size=(b_shape[0], b_shape[1])).astype(B.dtype), dev) t = tvm.nd.empty((c_shape[0], c_shape[1]), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm def test_in_bounds_tensors_with_same_shapes3D_llvm(): n = te.size_var("n") k = te.size_var("k") m = te.size_var("m") A = te.placeholder((n, n, n), name="A") B = te.placeholder((k, k, k), name="B") T = te.compute((m, m, m), lambda i, j, p: A[i][j][p] * B[i][j][p]) s = te.create_schedule(T.op) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array(np.random.uniform(size=(32, 32, 32)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(32, 32, 32)).astype(B.dtype), dev) t = tvm.nd.empty((32, 32, 32), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_tensors_with_diff_shapes3D_llvm(a_shape, b_shape, c_shape): n = te.size_var("n") k = te.size_var("k") m = te.size_var("m") A = te.placeholder((n, n, n), name="A") B = te.placeholder((k, k, k), name="B") T = te.compute((m, m, m), lambda i, j, p: A[i][j][p] * B[i][j][p]) s = te.create_schedule(T.op) lowered_func = tvm.lower(s, [A, B, T], "llvm", simple_mode=False) dev = tvm.cpu(0) f = tvm.build(s, [A, B, T], "llvm") a = tvm.nd.array( np.random.uniform(size=(a_shape[0], a_shape[1], c_shape[2])).astype(A.dtype), dev ) b = tvm.nd.array( np.random.uniform(size=(b_shape[0], b_shape[1], b_shape[2])).astype(B.dtype), dev ) t = tvm.nd.empty((c_shape[0], c_shape[1], c_shape[2]), T.dtype, dev) f(a, b, t) @tvm.testing.requires_llvm @pytest.mark.xfail def test_out_of_bounds_tensors_with_zero_shape_op_with_not_zero_shape_llvm(): n = 64 A = te.placeholder((n,), name="A") scale = te.placeholder((), name="scale") k = te.reduce_axis((0, n), name="k") C = te.compute((), lambda: te.sum(A[k
+ k + k] * scale, axis=k), name="C") D = te.compute((), lambda: C + 1) s = te.create_schedule(D.op) stmt = tvm.lower(s, [A, scale, D], simple_mode=True) f = tvm.build(s, [A, scale, D], "llvm") dev = tvm.cpu(0) a = tvm.nd.array(np.random.randint(0, 2, size=(n,)).astype(A.dtype), dev) sc = tvm.nd.array(np.random.randint(0, 2, size=()).astype(scale.dtype), dev) d = tvm.nd.empty((), D.dtype, dev) f(a, sc, d) d_np = np.sum(a.numpy()) * sc.numpy() + 1 tvm.testing.assert_allclose(d.numpy(), d_np) if __name__ == "__main__": with tvm.transform.PassContext( config={ "tir.instrument_bound_checkers": True, } ): test_out_of_bounds_tensors_with_zero_shape_op_with_not_zero_shape_llvm() test_in_bounds_llvm() test_out_of_bounds_llvm(1, 0) test_out_of_bounds_llvm(0, 1) test_out_of_bounds_llvm(1, 1) test_out_of_bounds_llvm(10000, 0) test_out_of_bounds_llvm(0, 10000) test_out_of_bounds_llvm(10000, 10000) test_out_of_bounds_llvm(-1, 0) test_out_of_bounds_llvm(0, -1) test_out_of_bounds_llvm(-1, -1) test_out_of_bounds_llvm(-10000, 0) test_out_of_bounds_llvm(0, -10000) test_out_of_bounds_llvm(-10000, -10000) test_in_bounds_vectorize_llvm() test_out_of_bounds_vectorize_llvm(1024, 1000, 0) test_out_of_bounds_vectorize_llvm(1024, 0, 10000) test_out_of_bounds_vectorize_llvm(1024, -1000, 0) test_out_of_bounds_vectorize_llvm(1024, 0, -10000) test_in_bounds_const_loop_partition_llvm() test_out_of_bounds_const_loop_partition_llvm(1, 0) test_out_of_bounds_const_loop_partition_llvm(0, 1) test_out_of_bounds_const_loop_partition_llvm(-1, 0) test_out_of_bounds_const_loop_partition_llvm(0, -1) test_in_bounds_loop_partition_basic_llvm() test_out_of_bounds_loop_partition_basic_llvm(32, 0)
test_out_of_bounds_loop_partition_basic_llvm(0, 32) test_out_of_bounds_loop_partition_basic_llvm(-32, 0) test_out_of_bounds_loop_partition_basic_llvm(0, -32) test_in_bounds_conv_llvm() test_out_of_bounds_conv_llvm([1, 0, 0, 0], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 1, 0, 0], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 1, 0], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 1], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([-1, 0, 0, 0], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, -1, 0, 0], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, -1, 0], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, -1], [0, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [1, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 1, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 1, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, 1]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [-1, 0, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, -1, 0, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, -1, 0]) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, -1]) test_in_bounds_conv_llvm(True) test_out_of_bounds_conv_llvm([1, 0, 0, 0], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 1, 0, 0], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, 1, 0], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, 1], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([-1, 0, 0, 0], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, -1, 0, 0], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, -1, 0], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, -1], [0, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [1, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 1, 0, 0], True) test_out_o
f_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 1, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, 1], True) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [-1, 0, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, -1, 0, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, -1, 0], True) test_out_of_bounds_conv_llvm([0, 0, 0, 0], [0, 0, 0, -1], True) test_out_of_bounds_tensors_with_diff_shapes1D_llvm(32, 64, 64) test_out_of_bounds_tensors_with_diff_shapes1D_llvm(64, 32, 64) test_out_of_bounds_tensors_with_diff_shapes2D_llvm([64, 64], [32, 32], [64, 64]) test_out_of_bounds_tensors_with_diff_shapes2D_llvm([32, 32], [64, 64], [64, 64]) test_out_of_bounds_tensors_with_diff_shapes3D_llvm([64, 64, 64], [32, 32, 32], [64, 64, 64]) test_out_of_bounds_tensors_with_diff_shapes3D_llvm([32, 32, 32], [64, 64, 64], [64, 64, 64]) test_in_bounds_tensors_with_same_shapes1D_llvm() test_in_bounds_tensors_with_same_shapes2D_llvm() test_in_bounds_tensors_with_same_shapes3D_llvm() test_in_bounds_const_loop_partition_ir()
# 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 import tir, ir def test_convert_ssa(): dtype = "int32" zero = tir.const(0) nop = tir.Evaluate(zero) var_type = ir.PointerType(ir.PrimType(dtype)) v = tir.Var("i1", var_type) buf = tir.decl_buffer([16], dtype=dtype, data=v) let = tir.LetStmt(v, v, nop) load = tir.Evaluate(tir.BufferLoad(buf, [zero])) seq = tir.SeqStmt([let, let, load]) func = tir.PrimFunc([], seq) mod = tvm.IRModule({"main": func}) mod = tir.transform.InjectVirtualThread()( mod ) # Use pass InjectVirtualThread to invoke ConvertSSA if __name__ == "__main__": pytest.main([__file__])
import tvm from tvm
import te def test_coproc_lift(): ib = tvm.tir.ir_builder.create() n = te.var("n") cp = te.thread_axis((0, 1), "cop") value = tvm.tir.StringImm("xxx") A = ib.allocate("float32", n, name="A", scope="global") with ib.for_range(0, n, name="i") as i: with ib.for_range(0, 10, name="j") as j: ib.scope_attr(cp, "coproc_uop_scope", value) A[i] = A[i] + 1 with ib.if_scope(i.equal(0)): with ib.for_range(0, 10, name="j") as j: ib.scope_attr(cp, "coproc_uop_scope", value) A[j] = A[j] + 2 A[j] = A[j] + 3 A[j] = A[j] + 3 body = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body)) body = tvm.tir.transform.LiftAttrScope("coproc_uop_scope")(mod)["main"] assert body.body.body.node == cp ib = tvm.tir.ir_builder.create() A = ib.allocate("float32", n, name="A", scope="global") with ib.for_range(0, n, name="i") as i: with ib.for_range(0, 10, name="j") as j: A[j] = A[j] + 1 with ib.for_range(0, 10, name="j") as j: ib.scope_attr(cp, "coproc_uop_scope", value) A[i] = A[i] + 1 with ib.for_range(0, 10, name="j") as j: ib.scope_attr(cp, "coproc_uop_scope", value) A[i] = A[i] + 2 body = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], body)) body = tvm.tir.transform.LiftAttrScope("coproc_uop_scope")(mod)["main"] assert body.body.body.body[1].node == cp assert len(body.body.body.body) == 2 if __name__ == "__main__": test_coproc_lift()
import tvm
import tvm.testing from tvm
import te from tvm.ir.module
import IRModule from tvm.script
import tir as T
import numpy def collect_visit(stmt, f): ret = [] tvm.tir.stmt_functor.post_order_visit(stmt, lambda x: ret.append(f(x))) return ret def test_basic(): n = te.size_var("n") A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i] + B[i]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n], stmt)) mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"] assert not any(collect_visit(stmt.body.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse))) assert any(collect_visit(stmt.body.body[1], lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_const_loop(): n = 21 A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i] + B[i]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_no_unroll_loop(): n = 21 A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i] + B[i]) s = te.create_schedule(T.op) xo, xi = s[T].split(T.op.axis[0], factor=4) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) with tvm.transform.PassContext( config={ "tir.LoopPartition": {
"partition_const_loop": True, "no_unroll_loop_with_extent_one": True, } } ): mod = tvm.tir.transform.LoopPartition()(mod) mod = tvm.tir.transform.Simplify()(mod) stmt = tvm.tir.transform.RemoveNoOp()(mod)["main"].body assert sum(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.For))) == 4 def test_multi_loop(): ib = tvm.tir.ir_builder.create() m = te.size_var("m") n = te.size_var("n") with ib.for_range(0, 4, "i") as i: with ib.for_range(0, n, "j") as j: with ib.for_range(0, m, "k") as k: with ib.if_scope(ib.likely(i * m + j + k < n)): ib.emit(tvm.tir.Evaluate(m)) with ib.else_scope(): ib.emit(tvm.tir.Evaluate(n)) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([n, m], stmt)) mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_multi_if(): ib = tvm.tir.ir_builder.create() m = te.size_var("m") n = te.size_var("n") with ib.for_range(0, 4, "i") as i: with ib.for_range(0, n, "j") as j: with ib.for_range(0, m, "k") as k: with ib.if_scope(ib.likely(i * m + j + k < n)): ib.emit(tvm.tir.Evaluate(m)) with ib.else_scope(): ib.emit(tvm.tir.Evaluate(n)) with ib.if_scope(ib.likely(i * m + j - k < n)): ib.emit(tvm.tir.Evaluate(m)) with ib.else_scope(): ib.emit(tvm.tir.Evaluate(n)) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_thread_axis():
m = te.size_var("m") l = te.size_var("l") A = te.placeholder((m, l), name="A") B = te.compute((m, l), lambda i, j: A[i, j] + 3, name="B") s = te.create_schedule(B.op) s[B].set_scope("shared") num_thread = 16 xo, xi = s[B].split(B.op.axis[0], 32) xi0, xi1 = s[B].split(xi, nparts=num_thread) s[B].bind(xi0, te.thread_axis("threadIdx.x")) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"] assert not any(collect_visit(stmt.body.body[0], lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_vectorize(): n = te.size_var("n") A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") bias = te.size_var("bias", dtype="float32") scale = te.size_var("scale", dtype="float32") C = te.compute(A.shape, lambda *i: A(*i) + B(*i) * scale + bias, name="C") s = te.create_schedule(C.op) num_thread = 32 bx, x = s[C].split(C.op.axis[0], factor=num_thread * 4) tx, x = s[C].split(x, nparts=num_thread) _, x = s[C].split(x, factor=4) s[C].bind(bx, te.thread_axis("blockIdx.x")) s[C].bind(tx, te.thread_axis("threadIdx.x")) s[C].vectorize(x) stmt = tvm.lower(s, [A, B], name="main")["main"] body = stmt.body.body.body.body assert x.var.name not in str(body.condition) assert any(collect_visit(body.then_case, lambda x: isinstance(x, tvm.tir.Ramp))) def test_condition(): ib = tvm.tir.ir_builder.create() m = te.size_var("m") n = te.size_var("n") with ib.for_range(0, tvm.tir.truncdiv(n + 3, 4), "i") as i: with ib.for_range(0, 4, "j") as j: ib.emit(tvm.tir.Evaluate(tvm.tir.Select(ib.likely(i * 4 + j < n), m, n))) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, n], stmt)) mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.trans
form.Simplify()(mod)["main"].body assert not any(collect_visit(stmt[0], lambda x: isinstance(x, tvm.tir.Select))) def test_condition_EQ(): ib = tvm.tir.ir_builder.create() m = te.size_var("m") n = te.size_var("n") with ib.for_range(0, 10, "i") as i: ib.emit(tvm.tir.Evaluate(tvm.tir.Select(ib.likely(tvm.tir.EQ(i, 5)), m, n))) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, n], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt[0], lambda x: isinstance(x, tvm.tir.Select))) def test_thread_axis2(): n = tvm.runtime.convert(4096) m = te.size_var("m") A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") C = te.compute(A.shape, lambda i: A[i] + B[i], name="C") s = te.create_schedule(C.op) num_thread = 32 bx, x = s[C].split(C.op.axis[0], factor=32) tx, x = s[C].split(x, nparts=num_thread) _, x = s[C].split(x, factor=m) s[C].bind(bx, te.thread_axis("blockIdx.x")) s[C].bind(tx, te.thread_axis("threadIdx.x")) stmt = tvm.lower(s, [A, B], name="main")["main"] for_body = stmt.body.body.body.body[0] assert "threadIdx" not in str(for_body.extent) def test_everything_during_deduction(): m = te.size_var("m") n = te.size_var("n") ib = tvm.tir.ir_builder.create() with ib.for_range(0, n, "i") as i: with ib.for_range(0, 32, "j") as j: with ib.if_scope(ib.likely(tvm.tir.truncdiv(i, j) < m)): ib.emit(tvm.tir.Evaluate(m)) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, n], stmt)) mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert isinstance(stmt.body.body, tvm.tir.IfThenElse) def test_single_likely(): n = 60 A = te.placeholder
((n,), name="A") B = te.placeholder((n,), name="B") T = te.compute((n,), lambda i: A[i] + B[i]) s = te.create_schedule(T.op) x = T.op.axis[0] xo, xi = s[T].split(x, factor=16) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_multi_likely(): n = 94 m = 62 A = te.placeholder((n, m), name="A") B = te.placeholder((n, m), name="B") T = te.compute((n, m), lambda i, j: A[i, j] + B[i, j]) s = te.create_schedule(T.op) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) x, y = T.op.axis xo, xi = s[T].split(x, factor=16) yo, yi = s[T].split(y, factor=16) s[T].reorder(xo, yo, xi, yi) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_oneD_pool(): m = te.size_var("m") ib = tvm.tir.ir_builder.create() data = ib.pointer("float32", name="A") out = ib.pointer("float32", name="A") with ib.for_range(0, 16, "ow") as ow: with ib.for_range(0, 3, "kw") as kw: with ib.if_scope(ib.likely(ow > 0)): with ib.if_scope(ib.likely(ow < 15)): out[ow] = tvm.te.max(out[ow], data[ow + kw - 1]) with ib.for_range(0, 16, "ow") as ow: with ib
.for_range(0, 3, "kw") as kw: with ib.if_scope(ib.likely(ow < 1)): with ib.if_scope(ib.likely(kw > 0)): out[ow] = tvm.te.max(out[ow], data[ow + kw - 1]) with ib.for_range(0, 16, "ow") as ow: with ib.for_range(0, 3, "kw") as kw: with ib.if_scope(ib.likely(ow > 14)): with ib.if_scope(ib.likely(kw < 2)): out[ow] = tvm.te.max(out[ow], data[ow + kw - 1]) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([m, data, out], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_cce_loop_1(): ib = tvm.tir.ir_builder.create() dtype = "float16" n = 514 m = 514 _A = te.placeholder((n * m,), name="A") Ab = tvm.tir.decl_buffer((n * m,), dtype, name="A") A = ib.buffer_ptr(Ab) _B = te.placeholder((n * m,), name="B") Bb = tvm.tir.decl_buffer((n * m,), dtype, name="B") B = ib.buffer_ptr(Bb) with ib.for_range(0, 11, name="i") as i: with ib.for_range(0, 160, name="j") as j: with ib.if_scope(ib.likely(((i * 160) + j) < 1600)): A[(i + 1) * m + j + 1] = ( B[(i) * m + j + 1] + B[(i + 1) * m + j + 1] + B[(i + 2) * m + j + 1] ) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab, Bb], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_cce_loop_2(): ib = tvm.tir.ir_builder.create() len = 112 tile = 32 loop = (len + tile - 1) with ib.
for_range(0, loop, "i") as i: head = i * tile with ib.if_scope(ib.likely(head + tile > len)): tail = len ib.emit(tvm.tir.call_extern("float32", "cce_intrisic", head, tail)) with ib.else_scope(): tail = head + tile ib.emit(tvm.tir.call_extern("float32", "cce_intrisic", head, tail)) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_cce_loop_3(): ib = tvm.tir.ir_builder.create() loop1 = 4 loop2 = 9998 tile = 39991 with ib.for_range(0, loop2, "i") as i: with ib.for_range(0, loop1, "j") as j: head1 = i head2 = j with ib.if_scope(ib.likely(head1 * loop1 + head2 < tile)): ib.emit(tvm.tir.call_extern("float16", "cce_intrisic", head1)) stmt = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_conv_tiling(): HSTR = WSTR = 1 in_channel = 128 kernel_height = kernel_width = 3 out_channel = 64 batch_size = 1 in_height = in_width = 64 out_height = out_width = in_height - kernel_height + 1 data = te.placeholder((batch_size, in_channel, in_height, in_width), name="data") kernel = te.placeholder((kernel_height, kernel_width, in_channel, out_channel), name="kernel") ic = te.reduce_axis((0, in_channel), name="ic") kh = te.reduce_axis((0, kernel_height), name="kh") kw = te
.reduce_axis((0, kernel_width), name="kw") conv = te.compute( (batch_size, out_channel, out_height, out_width), lambda n, oc, oh, ow: te.sum( data[n, ic, oh * HSTR + kh, ow * WSTR + kw] * kernel[kh, kw, ic, oc], axis=[ic, kh, kw] ), name="conv2d", ) s = te.create_schedule(conv.op) n, oc, oh, ow = conv.op.axis oho, owo, ohi, owi = s[conv].tile(oh, ow, 16, 16) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt)) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.LoopPartition()(mod) stmt = tvm.tir.transform.Simplify()(mod)["main"].body assert not any(collect_visit(stmt, lambda x: isinstance(x, tvm.tir.IfThenElse))) def test_multilevel_splitting_with_indivisble_factors(): from tvm
import topi A = te.placeholder((130,), dtype="float32") B = topi.nn.relu(A) s = te.create_schedule(B.op) (y,) = s[B].op.axis (yo, yi) = s[B].split(y, factor=8) (yoo, yoi) = s[B].split(yo, factor=16) s[B].reorder(yoo, yoi, yi) s[B].unroll(yi) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): lowered_body = tvm.lower(s, [A, B], name="x")["x"].body def visit_stmt(op): return isinstance(op, tvm.tir.Max) num_max = collect_visit(lowered_body, visit_stmt) assert num_max.count(True) == 10 def test_double_splitting_with_indivisible_factors(): m = 48 dtype = "float32" A = te.placeholder((m,), name="A", dtype=dtype) C = te.compute((m,), lambda i: A[i], name="C") D = te.compute((m,), lambda i: C[i], name="D") s = te.create_schedule(D.op) co, ci = s[C].split(C.op.axis[0], factor=10) do, di = s[D].split(D.op.axis[0], 32) s[C].compute_at(s[D], do) target = "llvm" with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): f = tvm.lower(s, [A, C, D], name="fadd1", simple_mode=False) func = tvm.build(f, target=target) top_produce = f["fadd1"].body assert not any(collect_visit(top_produce, lambda x: isinstance(x, tvm.tir.IfThenElse))) dev = tvm.device(target, 0) a = tvm.nd.array( numpy.ones( m, ).astype(dtype), dev, ) c = tvm.nd.array( numpy.zeros( m, ).astype(dtype), dev, ) d = tvm.nd.array( numpy.zeros( m, ).astype(dtype), dev, ) func(a, c, d) tvm.testing.assert_allclose(c.numpy(), a.numpy(), rtol=1e-5) tvm.testing.assert_allclose(d.numpy(), a.numpy(), rtol=1e-5) def test_simple_rfactor(): K = 16 * 4 + 4 k = te.reduce_axis((0, K), "k") A = te.placeholder((1, K), name="A") B = te.compute((1,), lambda b: te.sum(A[b, k], axis
=k), name="B") s = te.create_schedule(B.op) ko, _ = s[B].split(s[B].op.reduce_axis[0], 16) BF = s.rfactor(B, ko, 0) s.normalize() bounds = tvm.te.schedule.InferBound(s) stmt1 = tvm.te.schedule.ScheduleOps(s, bounds) mod1 = tvm.IRModule.from_expr(tvm.tir.PrimFunc([], stmt1)) stmt1 = tvm.tir.transform.Simplify()(mod1)["main"].body with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod2 = tvm.tir.transform.LoopPartition()(mod1) stmt2 = tvm.tir.transform.Simplify()(mod2)["main"].body assert not tvm.ir.structural_equal(stmt1.body, stmt2.body) @T.prim_func def partitioned_concat( A: T.Buffer[(16,), "float32"], B: T.Buffer[(16,), "float32"], C: T.Buffer[(32,), "float32"] ) -> None: T.func_attr({"from_legacy_te_schedule": True, "global_symbol": "main", "tir.noalias": True}) T.preflattened_buffer(A, [16], data=A.data) T.preflattened_buffer(B, [16], data=B.data) T.preflattened_buffer(C, [32], data=C.data) for i in T.serial(0, 16): C[i] = A[i] for i in T.serial(0, 16): C[i + 16] = B[i + 16] def test_explicit_partition_hint(): A = te.placeholder((16,), name="A") B = te.placeholder((16,), name="B") C = te.compute((32,), lambda i: te.if_then_else(i < 16, A[i], B[i]), name="C") s = te.create_schedule(C.op) s.normalize() s[C].pragma(s[C].op.axis[0], "loop_partition_hint", True) mod = tvm.driver.build_module.schedule_to_module(s, [A, B, C], "main", None) with tvm.transform.PassContext(config={"tir.LoopPartition": {"partition_const_loop": True}}): mod = tvm.tir.transform.StorageFlatten(64)(mod) mod = tvm.tir.transform.LoopPartition()(mod) mod = tvm.tir.transform.Simplify()(mod) assert tvm.ir.structural_equal(mod["main"], partitioned_concat) def partition_from_scheduled_tir(prim_func, pass_cfg): with tvm.transform.PassContext(config=pass_cfg): mod = IRModule.from_expr(prim_func) mod = tvm.tir.tran
sform.LowerOpaqueBlock()(mod) mod = tvm.tir.transform.FlattenBuffer()(mod) mod = tvm.tir.transform.LoopPartition()(mod) mod = tvm.tir.transform.Simplify()(mod) mod = tvm.tir.transform.RemoveNoOp()(mod) return mod @T.prim_func def partitioned_concat_3( placeholder: T.Buffer[(50176,), "int8"], placeholder_1: T.Buffer[(25088,), "int8"], placeholder_2: T.Buffer[(25088,), "int8"], T_concat: T.Buffer[(100352,), "int8"], ) -> None: T.preflattened_buffer(placeholder, [1, 64, 28, 28], "int8", data=placeholder.data) T.preflattened_buffer(placeholder_1, [1, 32, 28, 28], "int8", data=placeholder_1.data) T.preflattened_buffer(placeholder_2, [1, 32, 28, 28], "int8", data=placeholder_2.data) T.preflattened_buffer(T_concat, [1, 128, 28, 28], "int8", data=T_concat.data) for i1, i2, i3 in T.grid(64, 28, 28): T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3] for i1, i2, i3 in T.grid(32, 28, 28): T_concat[i1 * 784 + i2 * 28 + i3 + 50176] = placeholder_1[i1 * 784 + i2 * 28 + i3] for i1, i2, i3 in T.grid(32, 28, 28): T_concat[i1 * 784 + i2 * 28 + i3 + 75264] = placeholder_2[i1 * 784 + i2 * 28 + i3] @T.prim_func def concat_func_3( placeholder: T.Buffer[(50176,), "int8"], placeholder_1: T.Buffer[(25088,), "int8"], placeholder_2: T.Buffer[(25088,), "int8"], T_concat: T.Buffer[(100352,), "int8"], ) -> None: T.preflattened_buffer(placeholder, (1, 64, 28, 28), "int8", data=placeholder.data) T.preflattened_buffer(placeholder_1, (1, 32, 28, 28), "int8", data=placeholder_1.data) T.preflattened_buffer(placeholder_2, (1, 32, 28, 28), "int8", data=placeholder_2.data) T.preflattened_buffer(T_concat, (1, 128, 28, 28), "int8", data=T_concat.data) for i1 in T.serial(128, annotations={"pragma_loop_partition_hint": 1}): for i2, i3 in T.grid(28, 28): if 96 <= i1: T_concat[i1 * 784 + i2 * 28 + i3] = placeholder_2[i1 * 784 + i2 * 28 + i3 - 75264]
if 64 <= i1 and i1 < 96: T_concat[i1 * 784 + i2 * 28 + i3] = placeholder_1[i1 * 784 + i2 * 28 + i3 - 50176] if i1 < 64: T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3] def test_condition_mutually_exclusive(): mod = partition_from_scheduled_tir( concat_func_3, {"tir.LoopPartition": {"partition_const_loop": True}} ) assert tvm.ir.structural_equal(mod["main"], partitioned_concat_3) def test_loop_partition_unroll_hint(): @T.prim_func def main(A: T.Buffer[150528, "int8"], B: T.Buffer[25088, "int8"]) -> None: T.preflattened_buffer(A, [1, 3, 224, 224], "int8", data=A.data) T.preflattened_buffer(B, [1, 224, 7, 16], "int8", data=B.data) for ax0 in T.serial( 112, annotations={"pragma_loop_partition_hint": True}, ): for ax1, ax2, ax3 in T.grid(224, 7, 16): if 3 <= ax0 * 2 + ax2 and ax0 * 2 + ax2 < 227 and ax3 < 3: B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax0 * 2 + ax2 - 3] @T.prim_func def partitioned_main(A: T.Buffer[150528, "int8"], B: T.Buffer[25088, "int8"]) -> None: T.preflattened_buffer(A, [1, 3, 224, 224], dtype="int8", data=A.data) T.preflattened_buffer(B, [1, 224, 7, 16], dtype="int8", data=B.data) for ax1, ax2, ax3 in T.grid(224, 7, 16): if 3 <= ax2 and ax3 < 3: B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax2 - 3] for ax1, ax2, ax3 in T.grid(224, 7, 16): if 1 <= ax2 and ax3 < 3: B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax2 - 1] for ax0, ax1, ax2, ax3 in T.grid(109, 224, 7, 16): if ax3 < 3: B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 + ax1 * 224 + ax0 * 2 + ax2 + 1] for ax1, ax2, ax3 in T.grid(224, 7, 16): if ax2 < 5 and ax3 < 3: B[ax1 * 112 + ax2 * 16 + ax3] = A[ax3 * 50176 +
ax1 * 224 + ax2 + 219] mod = partition_from_scheduled_tir( main, { "tir.LoopPartition": { "partition_const_loop": True, "unroll_loop_with_partition_hint_no_interval": True, } }, ) mod = tvm.tir.transform.UnrollLoop()(mod) mod = tvm.tir.transform.RemoveNoOp()(mod) mod = tvm.tir.transform.Simplify()(mod) assert tvm.ir.structural_equal(mod["main"], partitioned_main) def test_loop_partition_keep_loop_annotations(): @T.prim_func def before(A: T.Buffer[160, "int32"], B: T.Buffer[160, "int32"]) -> None: for i in T.serial( 160, annotations={"pragma_loop_partition_hint": True, "key": "value"}, ): if i < 10: B[i] = A[i] + 1 elif 10 <= i and i < 150: B[i] = A[i] + 2 else: B[i] = A[i] + 3 @T.prim_func def after(A: T.Buffer[160, "int32"], B: T.Buffer[160, "int32"]) -> None: T.preflattened_buffer(A, [160], dtype="int32", data=A.data) T.preflattened_buffer(B, [160], dtype="int32", data=B.data) for i in T.serial(10, annotations={"key": "value"}): B[i] = A[i] + 1 for i in T.serial(140, annotations={"key": "value"}): B[i + 10] = A[i + 10] + 2 for i in T.serial(10, annotations={"key": "value"}): B[i + 150] = A[i + 150] + 3 mod = partition_from_scheduled_tir( before, { "tir.LoopPartition": { "partition_const_loop": True, } }, ) assert tvm.ir.structural_equal(mod["main"], after) def test_loop_partition_with_unit_loop_in_condition(): @T.prim_func def before( placeholder: T.Buffer[(50176,), "int8"], placeholder_1: T.Buffer[(25088,), "int8"], placeholder_2: T.Buffer[(25088,), "int8"], T_concat: T.Buffer[(100352,), "int8"], ) -> None: for k in range(1, annotations={"preserve_unit_loop": True
}): for i1 in T.serial(128, annotations={"pragma_loop_partition_hint": 1}): for i2, i3 in T.grid(28, 28): if 96 <= k * 128 + i1: T_concat[k * i1 * 784 + i2 * 28 + i3] = placeholder_2[ i1 * 784 + i2 * 28 + i3 - 75264 ] if 64 <= k * 128 + i1 and k * 128 + i1 < 96: T_concat[i1 * 784 + i2 * 28 + i3] = placeholder_1[ i1 * 784 + i2 * 28 + i3 - 50176 ] if k * 128 + i1 < 64: T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3] @T.prim_func def after( placeholder: T.Buffer[50176, "int8"], placeholder_1: T.Buffer[25088, "int8"], placeholder_2: T.Buffer[25088, "int8"], T_concat: T.Buffer[100352, "int8"], ) -> None: T.preflattened_buffer(placeholder, [50176], dtype="int8", data=placeholder.data) T.preflattened_buffer(placeholder_1, [25088], dtype="int8", data=placeholder_1.data) T.preflattened_buffer(placeholder_2, [25088], dtype="int8", data=placeholder_2.data) T.preflattened_buffer(T_concat, [100352], dtype="int8", data=T_concat.data) for _ in T.serial(1, annotations={"preserve_unit_loop": True}): for i1, i2, i3 in T.grid(64, 28, 28): T_concat[i1 * 784 + i2 * 28 + i3] = placeholder[i1 * 784 + i2 * 28 + i3] for i1, i2, i3 in T.grid(32, 28, 28): T_concat[i1 * 784 + i2 * 28 + i3 + 50176] = placeholder_1[i1 * 784 + i2 * 28 + i3] for i1, i2, i3 in T.grid(32, 28, 28): T_concat[i2 * 28 + i3] = placeholder_2[i1 * 784 + i2 * 28 + i3] mod = partition_from_scheduled_tir( before, { "tir.LoopPartition": { "partition_const_loop": True, } }, ) assert tvm.ir.structural_equal(mod["main"], after) if __name__ == "__main
__": tvm.testing.main()
import sys
import pytest
import tvm
import tvm.testing from tvm
import te from tvm.script
import tir as T def _check(original, transformed): mod = tvm.IRModule.from_expr(original) mod = tvm.tir.transform.LowerCrossThreadReduction()(mod) tvm.ir.assert_structural_equal(mod["main"], transformed, True) def _check_fail(original): mod = tvm.IRModule.from_expr(original) with pytest.raises(ValueError): tvm.tir.transform.LowerCrossThreadReduction()(mod) @T.prim_func def loop_split(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, [128, 128], dtype="float32") B = T.match_buffer(b, [128], dtype="float32") for i, ko in T.grid(128, 4): for ki in T.thread_binding(0, 32, thread="threadIdx.x"): with T.block("B"): vi = T.axis.S(128, i) vk = T.axis.R(128, ko * 32 + ki) T.reads([A[vi, vk]]) T.writes([B[vi]]) with T.init(): B[vi] = T.float32(0) B[vi] = B[vi] + A[vi, vk] @T.prim_func def lowered_loop_split(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, [128, 128], dtype="float32") B = T.match_buffer(b, [128], dtype="float32") reduce_temp0 = T.alloc_buffer([1], dtype="float32", strides=[1], scope="local") normal_reduce_temp0 = T.alloc_buffer([1], dtype="float32", strides=[1], scope="local") for i in T.serial(0, 128): for ki in T.thread_binding(0, 32, thread="threadIdx.x"): with T.block("B_in_thread_init"): T.reads([]) T.writes([normal_reduce_temp0[0]]) normal_reduce_temp0[0] = T.float32(0) for ko in T.serial(0, 4): with T.block("B_normal_reduction"): vi = T.axis.S(128, i) vk = T.axis.R(128, ko * 32 + ki) T.reads([A[vi, vk]]) T.writes([normal_reduce_temp0[0]]) normal_reduce_temp0[0] = normal_reduce_temp0[0] + A[vi, vk] with T.block("B_cross_thread_reduction"): T.reads([normal_reduce_te