text
stringlengths
1
2.05k
bx, tx = s[C].split(C.op.axis[0], factor=64) s[C].bind(bx, te.thread_axis("blockIdx.x")) s[C].bind(tx, te.thread_axis("threadIdx.x")) mod = tvm.lower(s, [A, B, C, D]) for dev_type in gpu_devices: if tvm.testing.device_enabled(dev_type): binded_mod = tvm.tir.transform.Apply( lambda f: f.with_attr("target", tvm.target.Target(dev_type)) )(mod) with pytest.raises(RuntimeError): tvm.tir.transform.VerifyMemory()(binded_mod) for dev_type in other_devices: if tvm.testing.device_enabled(dev_type): binded_mod = tvm.tir.transform.Apply( lambda f: f.with_attr("target", tvm.target.Target(dev_type)) )(mod) tvm.tir.transform.VerifyMemory()(binded_mod) if __name__ == "__main__": test_verify_memory_all_bind() test_verify_memory_not_bind() test_verify_memory_partially_bind()
# 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 tvm from tvm import te def test_verify_ssa(): x = te.var("x") y = te.var() z = tvm.tir.Evaluate(x + y) assert tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([x, y], z)) assert not tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([x, y], tvm.tir.LetStmt(x, 1, z))) def test_verify_weak_let_ssa(): x = te.var("x") z1 = tvm.tir.Let(x, 1, x + 1) z2 = tvm.tir.Let(x, 2, x + 2) assert tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([], tvm.tir.Evaluate(z1 + z1))) assert not tvm.tir.analysis.verify_ssa(tvm.tir.PrimFunc([], tvm.tir.Evaluate(z1 * z2))) if __name__ == "__main__": test_verify_ssa() test_verify_weak_let_ssa()
# 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 tvm import tvm.testing from tvm.script import tir as T def test_pass_simple(): @T.prim_func def element_wise( A: T.Buffer[(128, 128), "float32"], C: T.Buffer[(128, 128), "float32"], ): B = T.alloc_buffer((128, 128), "float32") for i, j in T.grid(128, 128): with T.block("B"): vi, vj = T.axis.remap("SS", [i, j]) B[vi, vj] = A[vi, vj] * 2.0 for i, j in T.grid(128, 128): with T.block("C"): # It's a opaque block , so it can use outside variables C[i, j] = B[i, j] * 2.0 assert tvm.tir.analysis.verify_well_formed(element_wise) def test_fail_use_out_loop_var(): @T.prim_func def element_wise( A: T.Buffer[(128, 128), "float32"], B: T.Buffer[(128, 128), "float32"], ): for i, j in T.grid(128, 128): with T.block("B"): vi, vj = T.axis.remap("SS", [i, j]) # we cannot use `i` since it's defined outside the block B[vi, vj] = A[i, vj] * 2.0 assert not tvm.tir.analysis.verify_well_formed(element_wise, assert_mode=False) if __name__ == "__main__": tvm.testing.main()
import tvm
import pytest from tvm
import tir from tvm._ffi.base
import TVMError from tvm.ir.transform
import PassContext
import itertools
import pytest def build_tir_func(func): func = func.with_attr("global_symbol", "main") pass_ctx = PassContext.current() if pass_ctx.config.get("tir.noalias", True): func = func.with_attr("tir.noalias", True) mod = tvm.IRModule({"main": func}) func = tvm.build(mod) return func def test_scalar_add(): lhs_types = ["float32", "float16", "int32", "int64"] rhs_types = ["float32", "float16"] for lhs_type, rhs_type in itertools.product(lhs_types, rhs_types): lhs_input = tir.Var("lhs", "float32") rhs_input = tir.Var("rhs", "float32") lhs = tir.Cast(lhs_type, lhs_input) rhs = tir.Cast(rhs_type, rhs_input) output = lhs + rhs output = tir.ret(output) output = tir.Evaluate(output) func = tir.PrimFunc([lhs_input, rhs_input], output) func = build_tir_func(func) out = func(1.0, 2.0) assert out == 3.0 def assignment_helper(store_dtype, value_dtype): store = tir.Var("store", dtype=store_dtype) value = tir.Var("value", dtype=value_dtype) tir.Let(store, value, body=store) def test_fail_implicit_downcasts_same_type(): bits = [8, 16, 32, 64] for type in ["float", "int", "uint"]: for i in range(len(bits) - 1): with pytest.raises(TVMError): assignment_helper( store_dtype=f"{type}{bits[i]}", value_dtype=f"{type}{bits[i + 1]}" ) def test_cast_between_types(): bits = [16, 32] types = ["float", "int", "uint"] for store_type, store_bits, value_type, value_bits in itertools.product( types, bits, types, bits ): store_dtype = f"{store_type}{store_bits}" value_dtype = f"{value_type}{value_bits}" if store_dtype == value_dtype: assignment_helper(store_dtype, value_dtype) else: with pytest.raises(TVMError): assignment_helper(store_dtype, value_dtype) def test_ret_const():
a = tir.const(0) b = tir.ret(a) b = tir.Evaluate(b) func = tir.PrimFunc([], b) func = build_tir_func(func) out = func() assert out == 0 def test_control_flow_jump(): ib = tvm.tir.ir_builder.create() a = tir.Var("a", "float32") b = tir.Var("b", "float32") with ib.if_scope(True): ib.emit(tir.Evaluate(tir.ret(a))) ib.emit(tir.Evaluate(tir.ret(b))) stmt = ib.get() func = tir.PrimFunc([a, b], stmt) func = build_tir_func(func) out = func(1.0, 2.0) assert out == 1.0 def test_exception(): with pytest.raises(tvm.TVMError): x = tir.Var(name=1, dtype="int") def test_eq_ops(): a = tir.IntImm("int8", 1) with pytest.raises(ValueError): assert a != None with pytest.raises(ValueError): assert not a == None b = tir.StringImm("abc") assert b != None assert not b == None if __name__ == "__main__": test_scalar_add() test_ret_const() test_control_flow_jump() test_exception() test_eq_ops()
import pytest
import tvm
import tvm.testing from tvm
import te from tvm.tir
import Buffer
import numpy as np def test_buffer(): m = te.size_var("m") n = te.size_var("n") l = te.size_var("l") Ab = tvm.tir.decl_buffer((m, n), "float32") Bb = tvm.tir.decl_buffer((n, l), "float32") assert isinstance(Ab, tvm.tir.Buffer) assert Ab.dtype == "float32" assert tuple(Ab.shape) == (m, n) def test_buffer_access_ptr(): m = te.size_var("m") n = te.size_var("n") Ab = tvm.tir.decl_buffer((m, n), "float32", strides=[n + 1, 1]) aptr = Ab.access_ptr("rw") assert tvm.ir.structural_equal(aptr.args[3], Ab.strides[0] * m) assert aptr.args[0].dtype == Ab.dtype assert aptr.args[4].value == Buffer.READ | Buffer.WRITE aptr = Ab.access_ptr("w") assert aptr.args[4].value == Buffer.WRITE def test_buffer_access_ptr_offset(): m = te.size_var("m") n = te.size_var("n") Ab = tvm.tir.decl_buffer((m, n), "float32") aptr = Ab.access_ptr("rw", offset=100) tvm.testing.assert_prim_expr_equal(aptr.args[2], 100) assert aptr.args[4].value == Buffer.READ | Buffer.WRITE v = te.size_var("int32") aptr = Ab.access_ptr("rw", offset=100 + 100 + v) tvm.testing.assert_prim_expr_equal(aptr.args[2], 200 + v) assert aptr.args[4].value == Buffer.READ | Buffer.WRITE aptr = Ab.access_ptr("rw", offset=tvm.tir.call_extern("int32", "test_call", 100 + 100 + v)) tvm.testing.assert_prim_expr_equal( aptr.args[2], tvm.tir.call_extern("int32", "test_call", 200 + v) ) assert aptr.args[4].value == Buffer.READ | Buffer.WRITE def test_buffer_access_ptr_extent(): m = te.size_var("m") n = te.size_var("n") Ab = tvm.tir.decl_buffer((m, n), "float32") aptr = Ab.access_ptr("rw") assert tvm.ir.structural_equal(aptr.args[3], m * n) aptr = Ab.access_ptr("rw", offset=100) assert tvm.ir.structural_equal(aptr.args[3], m * n - 100) Ab = tvm.tir.decl_buffer((m, n), "float32", strides=[n + 1, 1]) aptr = Ab.access_ptr("rw", offset=100) assert tvm.ir.structural_equal(aptr.args[3], Ab.strides[0] * m - 100)
aptr = Ab.access_ptr("rw", extent=200) assert tvm.ir.structural_equal(aptr.args[3], 200) aptr = Ab.access_ptr("rw", offset=100, extent=100) assert tvm.ir.structural_equal(aptr.args[3], 100) def test_buffer_vload(): m = te.size_var("m") n = te.size_var("n") Ab = tvm.tir.decl_buffer((m, n), "float32", elem_offset=100) load = Ab.vload([2, 3]) tvm.ir.assert_structural_equal(load.indices, [2, 3]) def test_buffer_offset_of(): m = te.size_var("m") n = te.size_var("n") Ab = tvm.tir.decl_buffer((m, n), "float32", elem_offset=100) offset = Ab.offset_of([2, 3]) tvm.ir.assert_structural_equal(offset, [n * 2 + 103]) def test_buffer_vload_nullptr(): var = tvm.tir.Var("v", dtype="int32") buf = tvm.tir.decl_buffer((1,), name="buf") buf_load = tvm.tir.expr.BufferLoad(buffer=buf, indices=tvm.runtime.convert([0])) buf_load_stmt = tvm.tir.stmt.Evaluate(buf_load) for_loop = tvm.tir.stmt.For( loop_var=var, kind=0, min_val=0, extent=tvm.tir.Cast("int32", buf_load), body=buf_load_stmt ) buf_func = tvm.tir.PrimFunc(params={}, body=for_loop) mod = tvm.IRModule({"main": buf_func}) with pytest.raises(tvm.error.TVMError) as cm: mod = tvm.transform.Sequential( [ tvm.tir.transform.PlanAndUpdateBufferAllocationLocation(), tvm.tir.transform.CompactBufferAllocation(), tvm.tir.transform.LowerOpaqueBlock(), tvm.tir.transform.FlattenBuffer(), ] )(mod) assert "(n != nullptr) is false" in str(cm.execption) def test_buffer_index_merge_mult_mod(): m = te.size_var("m") n = te.size_var("n") s = te.size_var("s") k0 = te.size_var("k0") k1 = te.size_var("k1") A = tvm.tir.decl_buffer((m, n), "float32") A_stride = tvm.tir.decl_buffer((m, n), "float32", strides=(s, 1)) def assert_simplified_equal(index_simplified, index_direct): assert tvm.ir.structural_equal( index_simplified, index_dire
ct ), "index_simplified=%s, index_direct=%s" % (index_simplified, index_direct) idxd = tvm.tir.indexdiv idxm = tvm.tir.indexmod index_simplified = A_stride.offset_of( (idxd(idxm(k0, k1), s), idxm(idxm(k0, k1), s) + idxd(k0, k1) * k1) ) index_direct = A_stride.offset_of((0, k0)) assert_simplified_equal(index_simplified, index_direct) index_simplified = A.offset_of( (idxd(idxm(k0, idxd(k1, s)), n), idxm(idxm(k0, idxd(k1, s)), n) + idxm(k0, k1)) ) index_direct = A.offset_of((0, idxm(k0, k1) + idxm(k0, idxd(k1, s)))) assert_simplified_equal(index_simplified, index_direct) index_simplified = A.offset_of( ( idxd((idxd(k0, idxd(k1, s)) * idxd(k1, s)), n) + idxd(idxm(k0, idxd(k1, s)), n), idxm((idxd(k0, idxd(k1, s)) * idxd(k1, s)), n) + idxm(idxm(k0, idxd(k1, s)), n), ) ) index_direct = A.offset_of((0, k0)) assert_simplified_equal(index_simplified, index_direct) index_simplified = A.offset_of( (idxd(idxm(k0, idxd(k1, s)), n), idxm(idxm(k0, idxd(k1, n)), n) + idxm(k0, k1)) ) index_direct = A.offset_of( (0, idxd(idxm(k0, idxd(k1, s)), n) * n + (idxm(idxm(k0, idxd(k1, n)), n) + idxm(k0, k1))) ) assert_simplified_equal(index_simplified, index_direct) B = tvm.tir.decl_buffer((1, 14, 14, 1024)) i = te.size_var("i") j = te.size_var("j") k = te.size_var("k") index_simplified1 = B.offset_of( ( idxd(idxd(idxd((i * 50176 + j * 28672 + k), 1024), 14), 14), idxm(idxd(idxd((i * 50176 + j * 28672 + k), 1024), 14), 14), idxm(idxd((i * 50176 + j * 28672 + k), 1024), 14), idxm((i * 50176 + j * 28672 + k), 1024), ) ) index_simplified2 = B.offset_of( ( idxd(idxd(i * 49 + j * 28 + idxd(k, 1024), 14), 14), idxm(idxd(i * 49 + j * 28 + idxd(k, 1024), 14), 14), idxm(i * 7 + idxd(k, 1024), 14), idxm(k, 1024), )
) index_direct = B.offset_of((0, 0, 0, (i * 50176 + j * 28672 + k))) assert_simplified_equal(index_simplified1, index_direct) assert_simplified_equal(index_simplified2, index_direct) @tvm.testing.requires_llvm def test_buffer_broadcast(): m0, m1, m2 = te.size_var("m0"), te.size_var("m1"), te.size_var("m2") n0, n1, n2 = te.size_var("n0"), te.size_var("n1"), te.size_var("n2") o0, o1, o2 = te.size_var("o0"), te.size_var("o1"), te.size_var("o2") A = te.placeholder((m0, m1, m2), name="A") B = te.placeholder((n0, n1, n2), name="B") C = te.compute((o0, o1, o2), lambda i, j, k: A[i, j, k] + B[i, j, k], name="C") Ab = tvm.tir.decl_buffer(A.shape, A.dtype, name="Ab", buffer_type="auto_broadcast") Bb = tvm.tir.decl_buffer(B.shape, B.dtype, name="Bb", buffer_type="auto_broadcast") s = te.create_schedule(C.op) def check(): fadd = tvm.build(s, [A, B, C], target="llvm", name="bcast_add", binds={A: Ab, B: Bb}) dev = tvm.cpu(0) a = tvm.nd.array(np.random.uniform(size=(2, 4, 3)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(2, 1, 1)).astype(B.dtype), dev) c = tvm.nd.array(np.zeros((2, 4, 3), dtype=C.dtype), dev) fadd(a, b, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) check() @tvm.testing.requires_llvm def test_buffer_broadcast_expr(): n0, m0, x = te.size_var("n0"), te.size_var("m0"), te.size_var("x") n1, m1 = te.size_var("n1"), te.size_var("m1") o0, o1 = te.size_var("o0"), te.size_var("o1") A = te.placeholder((m0, n0), name="A") B = te.placeholder((m1, n1), name="B") C = te.compute((o0, o1 Ab = tvm.tir.decl_buffer(A.shape, A.dtype, name="Ab", buffer_type="auto_broadcast") Bb = tvm.tir.decl_buffer(B.shape, B.dtype, name="Bb", buffer_type="auto_broadcast") Cc = tvm.tir.decl_buffer(C.shape, C.dtype, name="Cc", buffer_type="auto_broadcast") s = te.create_schedule(C.op) def check_stride(): fadd = tvm.build( s
, [A, B, C, o1, x], target="llvm", name="bcast_add", binds={A: Ab, B: Bb, C: Cc} ) dev = tvm.cpu(0) a = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(B.dtype), dev) c = tvm.nd.array(np.zeros((2, 4), dtype=C.dtype), dev) fadd(a, b, c, 4, 1) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) def check_no_stride(): fadd = tvm.build( s, [A, B, C, o1, x], target="llvm", name="bcast_add", binds={A: Ab, B: Bb, C: Cc} ) dev = tvm.cpu(0) a = tvm.nd.array(np.random.uniform(size=(1, 4)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(B.dtype), dev) c = tvm.nd.array(np.zeros((2, 4), dtype=C.dtype), dev) fadd(a, b, c, 4, 1) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) def check_auto_bind(): fadd = tvm.build(s, [A, B, C, o1, x], target="llvm", name="bcast_add") dev = tvm.cpu(0) a = tvm.nd.array(np.random.uniform(size=(1, 4)).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(size=(2, 4)).astype(B.dtype), dev) c = tvm.nd.array(np.zeros((2, 4), dtype=C.dtype), dev) fadd(a, b, c, 4, 1) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) check_stride() check_no_stride() check_auto_bind() if __name__ == "__main__": pytest.main([__file__])
import pytest
import tvm from tvm
import te def test_expr_constructor(): x = tvm.tir.Var("xx", "float32") assert isinstance(x, tvm.tir.Var) assert x.name == "xx" x = tvm.tir.Reduce(None, [1], [tvm.tir.IterVar((0, 1), "x", 2)], None, 0) assert isinstance(x, tvm.tir.Reduce) assert x.combiner == None assert x.value_index == 0 x = tvm.tir.FloatImm("float32", 1.0) assert isinstance(x, tvm.tir.FloatImm) assert x.value == 1.0 assert x.dtype == "float32" x = tvm.tir.IntImm("int64", 2) assert isinstance(x, tvm.tir.IntImm) assert x.value == 2 assert x.dtype == "int64" x = tvm.tir.StringImm("xyza") assert isinstance(x, tvm.tir.StringImm) assert x.value == "xyza" x = tvm.tir.Cast("float32", tvm.tir.IntImm("uint32", 1)) assert isinstance(x, tvm.tir.Cast) assert x.dtype == "float32" assert x.value.value == 1 a = tvm.tir.const(1.0, dtype="float32") b = te.var("x", dtype="float32") for cls in [ tvm.tir.Add, tvm.tir.Sub, tvm.tir.Mul, tvm.tir.Div, tvm.tir.Mod, tvm.tir.Min, tvm.tir.Max, tvm.tir.LT, tvm.tir.LE, tvm.tir.GT, tvm.tir.GE, ]: x = cls(a, b) assert isinstance(x, cls) assert x.a == a assert x.b.same_as(b) a = tvm.runtime.convert(te.var("x") > 1) b = tvm.runtime.convert(te.var("x") == 1) for cls in [tvm.tir.And, tvm.tir.Or]: x = cls(a, b) assert isinstance(x, cls) assert x.a == a assert x.b.same_as(b) x = tvm.tir.Not(a) assert isinstance(x, tvm.tir.Not) assert x.a == a x = tvm.tir.Select(a, a, b) assert isinstance(x, tvm.tir.Select) assert x.true_value == a assert x.false_value == b assert x.condition == a buffer_var = tvm.tir.Var("buf", tvm.ir.PointerType(tvm.ir.PrimType("float32"))) buffer = tvm.tir.decl_buffer([16], "float32", data=buffer_var) x = tvm.tir.BufferLoad(buffer, [1]) assert isinstance(x, tvm.tir.BufferLoad) assert x
.dtype == "float32" assert x.buffer == buffer assert x.buffer.data == buffer_var assert list(x.indices) == [1] x = tvm.tir.Ramp(1, 2, 10) assert isinstance(x, tvm.tir.Ramp) assert x.base.value == 1 assert x.stride.value == 2 assert x.lanes == 10 x = tvm.tir.Broadcast(a, 10) assert isinstance(x, tvm.tir.Broadcast) assert x.value == a assert x.lanes == 10 x = tvm.tir.Shuffle([a], [0]) assert isinstance(x, tvm.tir.Shuffle) assert x.vectors[0] == a assert x.indices[0].value == 0 x = tvm.tir.Call("float32", "tir.call_extern", [tvm.tir.StringImm("xyz"), a]) assert isinstance(x, tvm.tir.Call) assert x.dtype == "float32" assert x.op.name == "tir.call_extern" assert x.args[1] == a v = te.var("aa") x = tvm.tir.Let(v, 1, v) assert x.var == v assert x.value.value == 1 assert x.body == v def test_stmt_constructor(): v = te.var("aa") nop = tvm.tir.Evaluate(1) x = tvm.tir.LetStmt(v, 1, tvm.tir.Evaluate(1)) assert isinstance(x, tvm.tir.LetStmt) assert x.var == v assert x.value.value == 1 assert isinstance(x.body, tvm.tir.Evaluate) x = tvm.tir.AttrStmt(v == 1, "xx", 1, tvm.tir.Evaluate(1)) assert isinstance(x, tvm.tir.AttrStmt) assert x.value.value == 1 x = tvm.tir.AssertStmt(tvm.tir.const(1, "uint1"), tvm.runtime.convert("hellow"), nop) assert isinstance(x, tvm.tir.AssertStmt) assert x.body == nop x = tvm.tir.For(te.var("x"), 0, 10, tvm.tir.ForKind.SERIAL, nop) assert isinstance(x, tvm.tir.For) assert x.min.value == 0 assert x.extent.value == 10 assert x.body == nop buffer_var = tvm.tir.Var("buf", tvm.ir.PointerType(tvm.ir.PrimType("uint1"))) buffer = tvm.tir.decl_buffer([16], "uint1", data=buffer_var) x = tvm.tir.BufferStore(buffer, 1, [10]) assert isinstance(x, tvm.tir.BufferStore) assert x.buffer == buffer assert x.buffer.data == buffer_var assert list(x.indices) == [10] assert x.value.value == 1 buffer_va
r = tvm.tir.Var("buf", tvm.ir.PointerType(tvm.ir.PrimType("float32"))) x = tvm.tir.Allocate(buffer_var, "float32", [10], tvm.tir.const(1, "uint1"), nop) assert isinstance(x, tvm.tir.Allocate) assert x.dtype == "float32" assert x.buffer_var == buffer_var assert x.body == nop storage_scope = "global.texture" buffer_var = tvm.tir.Var("buf", tvm.ir.PointerType(tvm.ir.PrimType("float32"), storage_scope)) x = tvm.tir.Allocate(buffer_var, "float32", [10], tvm.tir.const(1, "uint1"), nop) assert isinstance(x, tvm.tir.Allocate) assert x.dtype == "float32" assert x.buffer_var == buffer_var assert x.buffer_var.type_annotation.storage_scope == storage_scope assert x.body == nop x = tvm.tir.AttrStmt(buffer_var, "xyz", 1, nop) assert isinstance(x, tvm.tir.AttrStmt) assert x.node == buffer_var assert x.attr_key == "xyz" assert x.body == nop x = tvm.tir.IfThenElse(tvm.tir.const(1, "uint1"), tvm.tir.Evaluate(11), nop) assert isinstance(x, tvm.tir.IfThenElse) assert x.then_case.value.value == 11 assert x.else_case == nop b = tvm.tir.decl_buffer((1, 2)) x = tvm.tir.Prefetch(b, []) assert isinstance(x, tvm.tir.Prefetch) def test_float_constructor_requires_float_dtype(): with pytest.raises(tvm.TVMError): tvm.tir.FloatImm("int32", 1.0) if __name__ == "__main__": tvm.testing.main()
"""Test layout and bijective-layout node"""
import tvm from tvm
import te from tvm.topi.utils
import get_const_tuple def test_layout(): layout = tvm.tir.layout("NCHW16c") assert layout is not None assert isinstance(layout, tvm.tir.Layout) assert layout.factor_of("c") == 16 assert layout.factor_of("C") == 16 assert layout.factor_of("N") == -1 assert layout.index_of("N") == 0 assert layout.index_of("C") == 1 assert layout.index_of("H") == 2 assert layout.index_of("W") == 3 assert layout.index_of("c") == 4 assert layout.index_of("O") == -1 assert "N" in layout assert "C" in layout assert "H" in layout assert "W" in layout assert "c" in layout assert "O" not in layout assert layout[0] == "N" assert layout[1] == "C" assert layout[2] == "H" assert layout[3] == "W" assert layout[4] == "c" assert layout[-1] == "c" def test_bilayout_convertible(): assert tvm.tir.bijective_layout("NCHW", "ABCD") is None assert tvm.tir.bijective_layout("__undef__", "NCHW") is None assert tvm.tir.bijective_layout("NCHW", "__undef__") is None assert tvm.tir.bijective_layout("__undef__", "__undef__") is None assert tvm.tir.bijective_layout("", "NCHW") is None assert tvm.tir.bijective_layout("NCHW", "") is None assert tvm.tir.bijective_layout("", "") is None assert tvm.tir.bijective_layout("NCHW", "NCHW16c") is not None def test_bilayout_shape(): bilayout = tvm.tir.bijective_layout("NCHW", "NCHW16c") assert isinstance(bilayout, tvm.tir.BijectiveLayout) dst_shape = bilayout.forward_shape((1, 32, 7, 7)) assert get_const_tuple(dst_shape) == (1, 2, 7, 7, 16) src_shape = bilayout.backward_shape(dst_shape) assert get_const_tuple(src_shape) == (1, 32, 7, 7) def test_bilayout_index(): bilayout = tvm.tir.bijective_layout("NCHW", "NCHW16c") dst_index = bilayout.forward_index([0, 18, 6, 6]) assert get_const_tuple(dst_index) == (0, 1, 6, 6, 2) src_index = bilayout.backward_index([0, 1, 6, 6, 2]) assert get_const_tuple(src_index) == (0, 18, 6, 6) if __n
ame__ == "__main__": test_layout() test_bilayout_convertible() test_bilayout_shape() test_bilayout_index()
import math
import random
import numpy as np
import tvm
import tvm.testing
import pytest from tvm
import tir from tvm.script
import tir as T
import pytest @pytest.mark.parametrize( "dtype, literals", [ ["int8", [-128, 0, 127]], ["uint8", [0, 255]], ["int32", [-2147483648, 2147483647]], ["uint32", [0, 4294967295]], ["int64", [-9223372036854775808, 9223372036854775807]], ["uint64", [0, 9223372036854775807]], ], ) def test_tir_make_intimm(dtype, literals): for l in literals: imm = tir.const(l, dtype) assert imm.value == l, imm @pytest.mark.parametrize( "dtype, literals", [ ["int8", [-129, 128]], ["uint8", [-1, 256]], ["int32", [-2147483650, 2147483648]], ["uint32", [-1, 4294967296]], ["uint64", [-1, 18446744073709551616]], ], ) def test_tir_invalid_intimm(dtype, literals): for l in literals: with pytest.raises(tvm.TVMError): tir.const(l, dtype) @pytest.mark.parametrize( "dtype, literals", [ [ "uint64", { 9223372036854775807: 9223372036854775807, 18446744073709551615: 18446744073709551615, }, ], ], ) def test_tir_large_py_int_literals(dtype, literals): """ For large uint value, use LargeUIntImm intrin, """ for l in literals: x = tir.const(l, dtype) if isinstance(x, (tir.IntImm, tir.FloatImm)): assert x.value == literals[l] else: assert (int(x.args[1]) << 32) + int(x.args[0]) == literals[l] def test_tir_intimm_overflow(): assert int(tir.const(255, "uint8") + tir.const(1, "uint8")) == 0 assert int(tir.const(2**31 - 1, "int32") + tir.const(1, "int32")) == -(2**31) assert int(tir.const(2**32 - 1, "uint32") + tir.const(1, "uint32")) == 0 assert int(tir.const(2**63 - 1, "int64") + tir.const(1, "int64")) == -(2**63) assert int(tir.const(2**32, "uint64") * tir.const(2**32, "uint64")) == 0 assert int(tir.const(7, "int4") + tir.const(1, "int4")) == -8 assert int(tir.const(2**39 - 1, "int40") + tir.cons
t(1, "int40")) == -(2**39) def compare_float_value(value, expect, msg): if math.isfinite(value): assert np.abs(value - expect) < 1e-5, f"{value} vs {expect}, {msg}" elif math.isnan(value): assert math.isnan(expect), f"{value} vs {expect}, {msg}" elif math.isinf(value): assert math.isinf(expect), f"{value} vs {expect}, {msg}" @pytest.mark.parametrize( "dtype, literals", [ ["float16", [-65504.0, 3.14, 65504.0, np.inf, np.nan]], ["bfloat16", [-3.38953139e38, 3.38953139e38, 3.14]], ["float32", [np.finfo("float32").min, 3.14, np.finfo("float32").max, np.inf, np.nan]], ["float64", [np.finfo("float64").min, 3.14, np.finfo("float64").max, np.inf, np.nan]], ], ) def test_tir_make_floatimm(dtype, literals): for l in literals: imm = tir.const(l, dtype) compare_float_value(imm.value, l, "imm value should match feed value") @pytest.mark.parametrize( "dtype, literals", [ ["float16", [-65505.0, 65505.0]], ["float32", [-3.402e39, 3.402e39]], ], ) def test_tir_invalid_floatimm(dtype, literals): """Currently only fp16 and fp32 have range check.""" for l in literals: with pytest.raises(tvm.TVMError): tir.const(l, dtype) @pytest.mark.parametrize("dtype", ["float16", "float32", "float64"]) @pytest.mark.parametrize("literal", [3.14, np.nan, np.inf]) def test_tir_special_floatimms(dtype, literal): x = tir.const(literal, dtype) compare_float_value(x.value, literal, "imm value should match feed value") @tvm.testing.requires_llvm() def test_tir_too_large_literal_f64(): @T.prim_func def imm_overflow_fp64() -> T.float64: T.evaluate(T.ret(T.float64(1.7976e309), dtype="float64")) f = tvm.build(imm_overflow_fp64, target="llvm") assert math.isinf(f()) @pytest.mark.parametrize( "literal, expect_dtype", [ (256, "int32"), (2147483647, "int32"), (-2147483648, "int32"), (2147483648, "int64"), (-
2147483649, "int64"), (3.14159, "float32"), (np.finfo("float32").min, "float32"), (np.finfo("float32").max, "float32"), (-3.402e39, "float64"), (3.402e39, "float64"), ], ) def test_tir_const_auto_dtype(literal, expect_dtype): x = tir.const(literal, dtype=None) assert x.dtype == expect_dtype assert x.value == literal def check_tir_const_fold( dtype, foldf, calcf, x_range=None, y_range=None, expect=None, skip_overflow=False ): """Helper to check constant folding behavior Parameters ---------- dtype: str Datatype of constants foldf: (x, y) -> z Folding function to call calcf: (x, y) -> z Compiled calculation function to call x_range: Union[int, float, tuple] Single value or value range [min, max] y_range: Union[int, float, tuple] Single value or value range [min, max] expect: Union[int, float] Expected calculation result skip_overflow: bool Skip assertion if the overflow happens """ seed = random.randint(0, 2147483648) np.random.seed(seed) ninfo = np.finfo(dtype) if dtype.startswith("float") else np.iinfo(dtype) if x_range is None: x_range = (ninfo.min, ninfo.max) if isinstance(x_range, (int, float)): x = x_range elif dtype.startswith("int") or dtype.startswith("uint"): x = np.random.randint(x_range[0], x_range[1] + 1, dtype=dtype) else: x = np.random.uniform(x_range[0], x_range[1]) if y_range is None: y_range = (ninfo.min, ninfo.max) if isinstance(y_range, (int, float)): y = y_range elif dtype.startswith("int") or dtype.startswith("uint"): y = np.random.randint(y_range[0], y_range[1] + 1, dtype=dtype) else: y = np.random.uniform(y_range[0], y_range[1]) if skip_overflow: py_res = foldf(x, y) if isinstance(py_res, (tir.IntImm, tir.FloatImm)): py_res = py_res.value if not (ninfo.min <= py_res <= ninfo.ma
x): return fold_res = foldf(tir.const(x, dtype), tir.const(y, dtype)) calc_res = calcf(x, y) flaky_msg = ( f"{dtype} ({x}, {y}, {expect}) const folding check failed.\n" + "This test is intentionally non-deterministic, " + f"if it fails please report it in github issue together with this seed {seed}\n" ) if dtype.startswith("float"): compare_float_value(calc_res, fold_res.value, flaky_msg) if expect: compare_float_value(expect, calc_res, flaky_msg) else: assert calc_res == fold_res.value, flaky_msg if expect: assert expect == calc_res, flaky_msg @tvm.testing.requires_llvm() def test_tir_floatimm_const_fold(): """Behavior check: folding fp32 match platform f32 arithmetic""" @T.prim_func def float_imm_multiply(x: T.float32, y: T.float32, z: T.Buffer[(), "float32"]): z[()] = x * y @T.prim_func def float_imm_add(x: T.float32, y: T.float32, z: T.Buffer[(), "float32"]): z[()] = x + y @T.prim_func def float_imm_sub(x: T.float32, y: T.float32, z: T.Buffer[(), "float32"]): z[()] = x - y @T.prim_func def float_imm_div(x: T.float32, y: T.float32, z: T.Buffer[(), "float32"]): z[()] = x / y def __wrap_build(f): lib = tvm.build(f, target="llvm") z = tvm.nd.array(np.zeros([]).astype("float32")) def _func(x, y): lib(x, y, z) return z.numpy() return _func fmul = __wrap_build(float_imm_multiply) fadd = __wrap_build(float_imm_add) fsub = __wrap_build(float_imm_sub) fdiv = __wrap_build(float_imm_div) check_tir_const_fold("float32", lambda x, y: x * y, fmul, 3.0e30, 3.0e30, np.inf) check_tir_const_fold("float32", lambda x, y: x * y, fmul, 3.0e30, -3.0e30, -np.inf) check_tir_const_fold("float32", lambda x, y: x / y, fdiv, 3.0e30, 3.0e-30, np.inf) with pytest.raises(tvm.TVMError): check_tir_const_fold("float3
2", lambda x, y: x / y, fdiv, 1.0, 0.0) check_tir_const_fold("float32", lambda x, y: x + y, fadd, 1.0, np.nan, np.nan) check_tir_const_fold("float32", lambda x, y: x + y, fadd, 1.0, np.inf, np.inf) check_tir_const_fold("float32", lambda x, y: x + y, fadd, 1.0, -np.inf, -np.inf) check_tir_const_fold("float32", lambda x, y: x * y, fmul) check_tir_const_fold("float32", lambda x, y: x + y, fadd) check_tir_const_fold("float32", lambda x, y: x - y, fsub) check_tir_const_fold( "float32", lambda x, y: x / y, fdiv, y_range=(0.01, np.finfo("float32").max) ) @tvm.testing.requires_llvm() def test_tir_int8_const_fold(): """Behavior check: folding i8 operation match platform i8 arithmetic""" @T.prim_func def imm_multiply(x: T.int8, y: T.int8) -> T.int8: T.evaluate(T.ret(x * y, dtype="int8")) @T.prim_func def imm_add(x: T.int8, y: T.int8) -> T.int8: T.evaluate(T.ret(x + y, dtype="int8")) @T.prim_func def imm_sub(x: T.int8, y: T.int8) -> T.int8: T.evaluate(T.ret(x - y, dtype="int8")) @T.prim_func def imm_truncdiv(x: T.int8, y: T.int8) -> T.int8: T.evaluate(T.ret(T.truncdiv(x, y), dtype="int8")) @T.prim_func def imm_floordiv(x: T.int8, y: T.int8) -> T.int8: T.evaluate(T.ret(T.floordiv(x, y), dtype="int8")) fmul = tvm.build(imm_multiply, target="llvm") fadd = tvm.build(imm_add, target="llvm") fsub = tvm.build(imm_sub, target="llvm") ffloordiv = tvm.build(imm_floordiv, target="llvm") ftruncdiv = tvm.build(imm_truncdiv, target="llvm") check_tir_const_fold("int8", lambda x, y: x + y, fadd, 127, 1, -128) check_tir_const_fold("int8", lambda x, y: x * y, fmul, 127, 127, 1) with pytest.raises(tvm.TVMError): check_tir_const_fold("int8", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0) with pytest.raises(tvm.TVMError): check_tir_const_fold("int8", lambda x, y: tir.truncdiv(x, y), ftruncdiv, 1, 0) assert not isinstance(tir.fl
oormod(tir.const(7, "int8"), tir.const(3, "int8")), tir.IntImm) assert not isinstance(tir.truncmod(tir.const(7, "int8"), tir.const(3, "int8")), tir.IntImm) check_tir_const_fold("int8", lambda x, y: x * y, fmul) check_tir_const_fold("int8", lambda x, y: x + y, fadd) check_tir_const_fold("int8", lambda x, y: x - y, fsub) check_tir_const_fold( "int8", lambda x, y: tir.floordiv(x, y), ffloordiv, y_range=(1, np.iinfo("int8").max) ) check_tir_const_fold( "int8", lambda x, y: tir.truncdiv(x, y), ftruncdiv, y_range=(1, np.iinfo("int8").max) ) @tvm.testing.requires_llvm() def test_tir_uint8_const_fold(): """Behavior check: folding u8 operation match platform u8 arithmetic""" @T.prim_func def imm_multiply(x: T.uint8, y: T.uint8) -> T.uint8: T.evaluate(T.ret(x * y, dtype="uint8")) @T.prim_func def imm_add(x: T.uint8, y: T.uint8) -> T.uint8: T.evaluate(T.ret(x + y, dtype="uint8")) @T.prim_func def imm_sub(x: T.uint8, y: T.uint8) -> T.uint8: T.evaluate(T.ret(x - y, dtype="uint8")) @T.prim_func def imm_truncdiv(x: T.uint8, y: T.uint8) -> T.uint8: T.evaluate(T.ret(T.truncdiv(x, y), dtype="uint8")) @T.prim_func def imm_floordiv(x: T.uint8, y: T.uint8) -> T.uint8: T.evaluate(T.ret(T.floordiv(x, y), dtype="uint8")) fmul = tvm.build(imm_multiply, target="llvm") fadd = tvm.build(imm_add, target="llvm") fsub = tvm.build(imm_sub, target="llvm") ffloordiv = tvm.build(imm_floordiv, target="llvm") ftruncdiv = tvm.build(imm_truncdiv, target="llvm") check_tir_const_fold("uint8", lambda x, y: x + y, fadd, 255, 1, 0) with pytest.raises(tvm.TVMError): check_tir_const_fold("uint8", lambda x, y: x - y, fsub, 0, 10) with pytest.raises(tvm.TVMError): check_tir_const_fold("uint8", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0) with pytest.raises(tvm.TVMError): check_tir_const_fold("uint8", lambda x, y: tir.truncdiv(x, y), ft
runcdiv, 1, 0) assert not isinstance(tir.floormod(tir.const(7, "uint8"), tir.const(3, "uint8")), tir.IntImm) assert not isinstance(tir.truncmod(tir.const(7, "uint8"), tir.const(3, "uint8")), tir.IntImm) check_tir_const_fold("uint8", lambda x, y: x * y, fmul) check_tir_const_fold("uint8", lambda x, y: x + y, fadd) check_tir_const_fold("uint8", lambda x, y: x - y, fsub) check_tir_const_fold( "uint8", lambda x, y: tir.floordiv(x, y), ffloordiv, y_range=(1, np.iinfo("uint8").max) ) check_tir_const_fold( "uint8", lambda x, y: tir.truncdiv(x, y), ftruncdiv, y_range=(1, np.iinfo("uint8").max) ) @tvm.testing.requires_llvm() def test_tir_int32_const_fold(): """Behavior check: folding i32 operation match platform i32 arithmetic""" @T.prim_func def imm_multiply(x: T.int32, y: T.int32) -> T.int32: T.evaluate(T.ret(x * y, dtype="int32")) @T.prim_func def imm_add(x: T.int32, y: T.int32) -> T.int32: T.evaluate(T.ret(x + y, dtype="int32")) @T.prim_func def imm_sub(x: T.int32, y: T.int32) -> T.int32: T.evaluate(T.ret(x - y, dtype="int32")) @T.prim_func def imm_truncdiv(x: T.int32, y: T.int32) -> T.int32: T.evaluate(T.ret(T.truncdiv(x, y), dtype="int32")) @T.prim_func def imm_truncmod(x: T.int32, y: T.int32) -> T.int32: T.evaluate(T.ret(T.truncmod(x, y), dtype="int32")) @T.prim_func def imm_floordiv(x: T.int32, y: T.int32) -> T.int32: T.evaluate(T.ret(T.floordiv(x, y), dtype="int32")) @T.prim_func def imm_floormod(x: T.int32, y: T.int32) -> T.int32: T.evaluate(T.ret(T.floormod(x, y), dtype="int32")) fmul = tvm.build(imm_multiply, target="llvm") fadd = tvm.build(imm_add, target="llvm") fsub = tvm.build(imm_sub, target="llvm") ffloordiv = tvm.build(imm_floordiv, target="llvm") ffloormod = tvm.build(imm_floormod, target="llvm") ftruncdiv = tvm.build(imm_truncdiv, target="llvm") ftruncmod = tvm.build(imm_truncmod, target
="llvm") assert -(2**31) <= int(tir.const(2**31 - 1, "int32") + tir.const(1, "int32")) < 2**31 assert -(2**31) <= int(tir.const(-(2**31), "int32") - tir.const(1, "int32")) < 2**31 with pytest.raises(tvm.TVMError): check_tir_const_fold("int32", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0) with pytest.raises(tvm.TVMError): check_tir_const_fold("int32", lambda x, y: tir.floormod(x, y), ffloormod, 1, 0) with pytest.raises(tvm.TVMError): check_tir_const_fold("int32", lambda x, y: tir.truncdiv(x, y), ftruncdiv, 1, 0) with pytest.raises(tvm.TVMError): check_tir_const_fold("int32", lambda x, y: tir.truncmod(x, y), ftruncmod, 1, 0) check_tir_const_fold("int32", lambda x, y: x * y, fmul, skip_overflow=True) check_tir_const_fold("int32", lambda x, y: x + y, fadd, skip_overflow=True) check_tir_const_fold("int32", lambda x, y: x - y, fsub, skip_overflow=True) check_tir_const_fold( "int32", lambda x, y: tir.floordiv(x, y), ffloordiv, y_range=(1, np.iinfo("int32").max), skip_overflow=True, ) check_tir_const_fold( "int32", lambda x, y: tir.truncdiv(x, y), ftruncdiv, y_range=(1, np.iinfo("int32").max), skip_overflow=True, ) check_tir_const_fold( "int32", lambda x, y: tir.floormod(x, y), ffloormod, y_range=(1, np.iinfo("int32").max), skip_overflow=False, ) check_tir_const_fold( "int32", lambda x, y: tir.truncmod(x, y), ftruncmod, y_range=(1, np.iinfo("int32").max), skip_overflow=False, ) @tvm.testing.requires_llvm() def test_tir_uint32_const_fold(): """Behavior check: folding u32 operation match platform u32 arithmetic""" @T.prim_func def imm_multiply(x: T.uint32, y: T.uint32) -> T.uint32: T.evaluate(T.ret(x * y, dtype="uint32")) @T.prim_func def imm_add(x: T.uint32, y: T.uint32) -> T.uint32: T.evaluate(T.ret(x +
y, dtype="uint32")) @T.prim_func def imm_sub(x: T.uint32, y: T.uint32) -> T.uint32: T.evaluate(T.ret(x - y, dtype="uint32")) @T.prim_func def imm_truncdiv(x: T.uint32, y: T.uint32) -> T.uint32: T.evaluate(T.ret(T.truncdiv(x, y), dtype="uint32")) @T.prim_func def imm_floordiv(x: T.uint32, y: T.uint32) -> T.uint32: T.evaluate(T.ret(T.floordiv(x, y), dtype="uint32")) fmul = tvm.build(imm_multiply, target="llvm") fadd = tvm.build(imm_add, target="llvm") fsub = tvm.build(imm_sub, target="llvm") ffloordiv = tvm.build(imm_floordiv, target="llvm") ftruncdiv = tvm.build(imm_truncdiv, target="llvm") assert 0 <= int(tir.const(2**32 - 1, "uint32") + tir.const(1, "uint32")) < 2**32 with pytest.raises(tvm.TVMError): check_tir_const_fold("uint32", lambda x, y: tir.floordiv(x, y), ffloordiv, 1, 0) with pytest.raises(tvm.TVMError): check_tir_const_fold("uint32", lambda x, y: tir.truncdiv(x, y), ftruncdiv, 1, 0) assert not isinstance(tir.floormod(tir.const(7, "uint32"), tir.const(3, "uint32")), tir.IntImm) assert not isinstance(tir.truncmod(tir.const(7, "uint32"), tir.const(3, "uint32")), tir.IntImm) check_tir_const_fold("uint32", lambda x, y: x * y, fmul, skip_overflow=True) check_tir_const_fold("uint32", lambda x, y: x + y, fadd, skip_overflow=True) check_tir_const_fold("uint32", lambda x, y: x - y, fsub, skip_overflow=True) check_tir_const_fold( "uint32", lambda x, y: tir.floordiv(x, y), ffloordiv, y_range=(1, np.iinfo("uint32").max), skip_overflow=False, ) check_tir_const_fold( "uint32", lambda x, y: tir.truncdiv(x, y), ftruncdiv, y_range=(1, np.iinfo("uint32").max), skip_overflow=False, ) if __name__ == "__main__": tvm.testing.main()
import tvm
import tvm.testing from tvm
import te, tir from tvm
import topi from tvm.contrib
import utils, clang from tvm.script
import tir as T
import numpy as np
import ctypes
import math def test_nearbyint(): m = te.var( "m", ) A = te.placeholder((m,), name="A") A_rounded = te.compute((m,), lambda *i: tvm.tir.nearbyint(A(*i)), name="A") s = te.create_schedule(A_rounded.op) f = tvm.build(s, [A, A_rounded], "llvm") dev = tvm.cpu(0) n = 10 a = tvm.nd.array(np.random.uniform(high=100, size=n).astype(A.dtype), dev) a_rounded = tvm.nd.array(np.random.uniform(size=n).astype(A_rounded.dtype), dev) f(a, a_rounded) tvm.testing.assert_allclose(a_rounded.numpy(), np.rint(a.numpy())) def test_round_intrinsics_on_int(): i = tvm.te.var("i", "int32") for op in [tvm.tir.round, tvm.tir.trunc, tvm.tir.ceil, tvm.tir.floor, tvm.tir.nearbyint]: assert op(tvm.tir.const(10, "int32")).value == 10 assert op(tvm.tir.const(True, "bool")).value == True assert op(i).same_as(i) assert tvm.tir.isnan(tvm.tir.const(10, "int32")).value == False def test_unary_intrin(): test_funcs = [ (tvm.tir.exp10, lambda x: np.power(10, x)), (tvm.tir.log2, lambda x: np.log2(x)), (tvm.tir.log10, lambda x: np.log10(x)), (tvm.tir.sinh, lambda x: np.sinh(x)), (tvm.tir.cosh, lambda x: np.cosh(x)), (tvm.tir.log1p, lambda x: np.log1p(x)), (tvm.tir.asin, lambda x: np.arcsin(x)), (tvm.tir.acos, lambda x: np.arccos(x)), (tvm.tir.atan, lambda x: np.arctan(x)), (tvm.tir.asinh, lambda x: np.arcsinh(x)), (tvm.tir.acosh, lambda x: np.arccosh(x)), (tvm.tir.atanh, lambda x: np.arctanh(x)), ] def run_test(tvm_intrin, np_func): m = te.var( "m", ) A = te.placeholder((m,), name="A") B = te.compute((m,), lambda *i: tvm_intrin(A(*i)), name="B") s = te.create_schedule(B.op) f = tvm.build(s, [A, B], "llvm") dev = tvm.cpu(0) n = 10 a = tvm.nd.array(np.random.uniform(0.1, 0.5, size=n).astype(A.dtype), dev) b = tvm.nd.array(np.random.uni
form(size=n).astype(A.dtype), dev) f(a, b) tvm.testing.assert_allclose(b.numpy(), np_func(a.numpy()), atol=1e-5, rtol=1e-5) for func in test_funcs: run_test(*func) def test_binary_intrin(): test_funcs = [ (tvm.tir.atan2, lambda x1, x2: np.arctan2(x1, x2)), (tvm.tir.nextafter, lambda x1, x2: np.nextafter(x1, x2)), (tvm.tir.copysign, lambda x1, x2: np.copysign(x1, x2)), (tvm.tir.hypot, lambda x1, x2: np.hypot(x1, x2)), ] def run_test(tvm_intrin, np_func): m = te.var( "m", ) A = te.placeholder((m,), name="A") B = te.placeholder((m,), name="B") C = te.compute((m,), lambda *i: tvm_intrin(A(*i), B(*i)), name="C") s = te.create_schedule(C.op) f = tvm.build(s, [A, B, C], "llvm") dev = tvm.cpu(0) n = 10 a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev) b = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(B.dtype), dev) c = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) f(a, b, c) tvm.testing.assert_allclose(c.numpy(), np_func(a.numpy(), b.numpy()), atol=1e-5, rtol=1e-5) for func in test_funcs: run_test(*func) def test_ldexp(): m = te.var( "m", ) A = te.placeholder((m,), name="A") B = te.placeholder((m,), name="B", dtype="int32") C = te.compute((m,), lambda *i: tvm.tir.ldexp(A(*i), B(*i)), name="C") s = te.create_schedule(C.op) f = tvm.build(s, [A, B, C], "llvm") dev = tvm.cpu(0) n = 10 a = tvm.nd.array(np.random.uniform(0, 1, size=n).astype(A.dtype), dev) b = tvm.nd.array(np.random.randint(0, 5, size=n).astype(B.dtype), dev) c = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) f(a, b, c) tvm.testing.assert_allclose(c.numpy(), np.ldexp(a.numpy(), b.numpy()), atol=1e-5, rtol=1e-5) dtype = tvm.testing.parameter("int32", "int64") @tvm.testing.parametrize_targets("llvm", "vulkan -from_device=0") def
test_clz(target, dev, dtype): target = tvm.target.Target(target) if ( target.kind.name == "vulkan" and dtype == "int64" and not target.attrs.get("supports_int64", False) ): pytest.xfail("Vulkan target does not support Int64 types") def clz_np(x, dtype): ceil_log2 = np.ceil(np.log2(x)).astype(dtype) bits = int(dtype[-2:]) clz = bits - ceil_log2 clz[np.bitwise_and(x, x - 1) == 0] -= 1 return clz m = te.var("m") A = te.placeholder((m,), name="A", dtype=dtype) B = te.compute((m,), lambda *i: tvm.tir.clz(A(*i)), name="B") s = te.create_schedule(B.op) if target.kind.name == "vulkan": bx, tx = s[B].split(B.op.axis[0], factor=64) s[B].bind(bx, te.thread_axis("blockIdx.x")) s[B].bind(tx, te.thread_axis("threadIdx.x")) f = tvm.build(s, [A, B], target) n = 10 highs = [10, 100, 1000, 10000, 100000, 1000000] if dtype == "int64": highs.append((1 << 63) - 1) for high in highs: a_np = np.random.randint(1, high=high, size=(n,), dtype=dtype) a = tvm.nd.array(a_np, dev) b = tvm.nd.array(np.zeros((n,)).astype("int32"), dev) f(a, b) ref = clz_np(a_np, dtype) np.testing.assert_equal(b.numpy(), ref) @tvm.script.ir_module class Module: @T.prim_func def test_tir_fma(A: T.handle, B: T.handle, C: T.handle, d: T.handle) -> None: T.func_attr({"global_symbol": "test_fma", "tir.noalias": True}) n = T.var("int32") stride = T.var("int32") stride_1 = T.var("int32") stride_2 = T.var("int32") stride_3 = T.var("int32") A_1 = T.match_buffer( A, [n], strides=[stride], elem_offset=0, align=64, offset_factor=1, buffer_type="auto", ) B_1 = T.match_buffer( B, [n], strides=[stride_1], elem_offset=0, align=64,
offset_factor=1, buffer_type="auto", ) C_1 = T.match_buffer( C, [n], strides=[stride_2], elem_offset=0, align=64, offset_factor=1, buffer_type="auto", ) d_1 = T.match_buffer( d, [n], strides=[stride_3], elem_offset=0, align=64, offset_factor=1, buffer_type="auto", ) for i in T.serial(0, n): d_1[(i * stride_3)] = (A_1[(i * stride)] * B_1[(i * stride_1)]) + C_1[(i * stride_2)] def test_fma(): opt = tvm.transform.Sequential( [ tvm.tir.transform.Apply(lambda f: f.with_attr("target", tvm.target.Target("llvm"))), tvm.tir.transform.LowerIntrin(), ] ) mod = opt(Module) assert mod["test_tir_fma"].body.body.value.op.name == "tir.call_llvm_pure_intrin" if __name__ == "__main__": test_nearbyint() test_unary_intrin() test_round_intrinsics_on_int() test_binary_intrin() test_ldexp() test_clz() test_fma()
import tvm from tvm
import te
import numpy as np
import tvm.testing from tvm.topi.math
import cast def test_for(): ib = tvm.tir.ir_builder.create() n = te.size_var("n") A = ib.allocate("float32", n, name="A", scope="global") with ib.for_range(0, n, name="i") as i: A[i] = A[i] + 1 with ib.for_range(0, 10, name="j") as j: A[j] = A[j] + 2 body = ib.get() assert isinstance(body, tvm.tir.Allocate) body = body.body assert isinstance(body, tvm.tir.For) body = body.body assert isinstance(body, tvm.tir.SeqStmt) assert isinstance(body[1], tvm.tir.For) def test_if(): ib = tvm.tir.ir_builder.create() n = te.size_var("n") A = ib.pointer("float32", name="A") tmod = tvm.tir.truncmod with ib.for_range(0, n, name="i") as i: with ib.if_scope(tmod(i, 2) == 0): A[i] = A[i] + 1 with ib.else_scope(): A[0] = A[i] + 2 body = ib.get() assert A == A assert isinstance(body, tvm.tir.For) body = body.body assert isinstance(body, tvm.tir.IfThenElse) assert isinstance(body.condition, tvm.tir.EQ) assert isinstance(body.then_case.indices[0], tvm.tir.Var) assert list(body.else_case.indices) == [0] def test_prefetch(): A = tvm.tir.decl_buffer((10, 20), name="A") ib = tvm.tir.ir_builder.create() n = te.size_var("n") with ib.for_range(0, n, name="i") as i: ib.emit( tvm.tir.Prefetch( A, [tvm.ir.Range.from_min_extent(i + 1, 2), tvm.ir.Range.from_min_extent(0, 20)] ) ) body = ib.get() assert body.body.bounds[0].extent.value == 2 def test_cpu(): n = 1024 dtype = "float32" A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") def test_device_ir(A, B, C): n = A.shape[0] max_threads = 8 ib = tvm.tir.ir_builder.create() Aptr = ib.buffer_ptr(A) Bptr = ib.buffer_ptr(B) Cptr = ib.buffer_ptr(C) with ib.for_range(0, n, name="i") as i: Cptr[i] = Aptr[i] + Bptr[i] body = ib.get()
return body C = te.extern( A.shape, [A, B], lambda ins, outs: test_device_ir(ins[0], ins[1], outs[0]), name="vector_add", dtype=dtype, ) s = te.create_schedule(C.op) def check_target(target): if not tvm.testing.device_enabled(target): return fadd = tvm.build(s, [A, B, C], target) dev = tvm.device(target, 0) 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) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) fadd(a, b, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) check_target("llvm") @tvm.testing.requires_gpu def test_gpu(): n = te.size_var("n") dtype = "float32" A = te.placeholder((n,), name="A") B = te.placeholder((n,), name="B") idxd = tvm.tir.indexdiv def test_device_ir(A, B, C): n = A.shape[0] max_threads = 32 ib = tvm.tir.ir_builder.create() bx = te.thread_axis("blockIdx.x") tx = te.thread_axis("threadIdx.x") ib.scope_attr(bx, "thread_extent", idxd(n + max_threads - 1, max_threads)) ib.scope_attr(tx, "thread_extent", max_threads) idx = bx.var * max_threads + tx.var Aptr = ib.buffer_ptr(A) Bptr = ib.buffer_ptr(B) Cptr = ib.buffer_ptr(C) with ib.if_scope(ib.likely(idx < n)): Cptr[idx] = Aptr[idx] + Bptr[idx] body = ib.get() return body C = te.extern( A.shape, [A, B], lambda ins, outs: test_device_ir(ins[0], ins[1], outs[0]), name="vector_add", dtype=dtype, ) s = te.create_schedule(C.op) bounds = tvm.te.schedule.InferBound(s) stmt = tvm.te.schedule.ScheduleOps(s, bounds) def check_target(target): n = 1024 if not tvm.testing.device_enabled(target): return fadd = tvm.build(s, [A, B, C], target) dev
= tvm.device(target, 0) 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) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) fadd(a, b, c) tvm.testing.assert_allclose(c.numpy(), a.numpy() + b.numpy()) check_target("opencl") check_target("cuda") def test_while_vectorize(): """Test while loop + vectorized inner loop""" n = 64 num_iter = 10 def test_ir(A, B, C): ib = tvm.tir.ir_builder.create() n = C.shape[0] A = ib.buffer_ptr(A) B = ib.buffer_ptr(B) C = ib.buffer_ptr(C) i = ib.allocate("int32", (1,), name="i", scope="local") i[0] = 0 with ib.for_range(0, n) as j: C[j] = 0.0 with ib.while_loop(i[0] < num_iter): with ib.for_range(0, n, kind="vectorize") as j: C[j] += A[j] + B[j] i[0] += 1 return ib.get() def check_target(target, ir): dtype = "float32" A = te.placeholder((n,), name="A", dtype=dtype) B = te.placeholder((n,), name="B", dtype=dtype) C = te.extern( (n,), [A, B], lambda ins, outs: ir(ins[0], ins[1], outs[0]), name="while_vectorize", dtype=dtype, ) s = te.create_schedule(C.op) with tvm.transform.PassContext(opt_level=3): func = tvm.build(s, [A, B, C], target) dev = tvm.device(target, 0) a_np = np.random.uniform(size=n).astype(A.dtype) b_np = np.random.uniform(size=n).astype(B.dtype) a = tvm.nd.array(a_np, dev) b = tvm.nd.array(b_np, dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) func(a, b, c) ref = num_iter * (a_np + b_np) tvm.testing.assert_allclose(c.numpy(), ref, rtol=1e-5, atol=1e-5) check_target("llvm", test_ir) def test_while_collatz(): """Test while loop + if""" def collatz_ref(n):
a = n i = 0 while a > 1: if a % 2 == 1: a = 3 * a + 1 else: a = a >> 1 i += 1 return i def collatz(ib, n, C): i = ib.allocate("int32", (1,), name="i", scope="local") a = ib.allocate("int32", (1,), name="a", scope="local") i[0] = 0 a[0] = n with ib.while_loop(a[0] > 1): with ib.if_scope(tvm.tir.floormod(a[0], 2) == 1): a[0] = 3 * a[0] + 1 with ib.else_scope(): a[0] = a[0] >> 1 i[0] += 1 C[n] = i[0] def collatz_ir_cpu(C): ib = tvm.tir.ir_builder.create() n = C.shape[0] C = ib.buffer_ptr(C) with ib.for_range(0, n, name="i", kind="parallel") as i: collatz(ib, i, C) body = ib.get() return body n = 30 def check_target(target, ir): C = te.extern( (n,), [], lambda ins, outs: ir(outs[0]), name="collatz", dtype="int32", ) s = te.create_schedule(C.op) with tvm.transform.PassContext(opt_level=3): func = tvm.build(s, [C], target) dev = tvm.device(target, 0) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) func(c) ref = np.array([collatz_ref(i) for i in range(n)]) tvm.testing.assert_allclose(c.numpy(), ref) check_target("llvm", collatz_ir_cpu) def test_while_mandel(): n = 160 shape = (n * 2, n) t = 300 def mandel_ref(): def complex_sqr(z): return np.array([z[0] ** 2 - z[1] ** 2, z[1] * z[0] * 2]) pixels = np.zeros(shape) for i in range(pixels.shape[0]): for j in range(pixels.shape[1]): c = np.array([-0.8, np.cos(t) * 0.2]) z = np.array([i / n - 1, j / n - 0.5]) * 2 iterations = 0 while np.linalg.norm(z) < 20 and iterations < 50: z = co
mplex_sqr(z) + c iterations += 1 pixels[i, j] = 1 - iterations * 0.02 return pixels def mandel(ib, i, j, pixels): z = ib.allocate("float32", (2,), name="z", scope="local") tmp = ib.allocate("float32", (1,), name="tmp", scope="local") iterations = ib.allocate("int32", (1,), name="iterations", scope="local") z[0] = (i / float(n) - 1) * 2 z[1] = (j / float(n) - 0.5) * 2 iterations[0] = 0 c = [-0.8, float(np.cos(t)) * 0.2] def norm(z): return tvm.tir.sqrt(z[0] * z[0] + z[1] * z[1]) with ib.while_loop(tvm.tir.all(norm(z) < 20, iterations[0] < 50)): tmp[0] = z[0] z[0] = z[0] * z[0] - z[1] * z[1] + c[0] z[1] = z[1] * tmp[0] * 2 + c[1] iterations[0] += 1 pixels[i, j] = 1 - iterations[0] * 0.02 def mandel_ir_cpu(C): ib = tvm.tir.ir_builder.create() ny = C.shape[0] nx = C.shape[1] C = ib.buffer_ptr(C) with ib.for_range(0, ny, name="i", kind="parallel") as i: with ib.for_range(0, nx, name="j") as j: mandel(ib, i, j, C) body = ib.get() return body def mandel_ir_gpu(C): ib = tvm.tir.ir_builder.create() ny = C.shape[0] nx = C.shape[1] C = ib.buffer_ptr(C) bx = te.thread_axis("blockIdx.x") tx = te.thread_axis("threadIdx.x") by = te.thread_axis("blockIdx.y") ty = te.thread_axis("threadIdx.y") max_threads = 16 ib.scope_attr(bx, "thread_extent", tvm.tir.indexdiv(nx + max_threads - 1, max_threads)) ib.scope_attr(tx, "thread_extent", max_threads) ib.scope_attr(by, "thread_extent", tvm.tir.indexdiv(ny + max_threads - 1, max_threads)) ib.scope_attr(ty, "thread_extent", max_threads) tidx = bx * max_threads + tx tidy = by * max_threads + ty with ib.if_scope(tvm.tir.all(tidx < nx, tidy < ny)): mandel(ib, tidy,
tidx, C) body = ib.get() return body ref = mandel_ref() def check_target(target, ir): if not tvm.testing.device_enabled(target): return C = te.extern( shape, [], lambda ins, outs: ir(outs[0]), name="mandel_ir", dtype="float32", ) s = te.create_schedule(C.op) with tvm.transform.PassContext(opt_level=3): func = tvm.build(s, [C], target) dev = tvm.device(target, 0) c = tvm.nd.array(np.zeros(shape, dtype=C.dtype), dev) func(c) tvm.testing.assert_allclose(c.numpy(), ref, rtol=1e-5, atol=1e-5) check_target("llvm", mandel_ir_cpu) check_target("npvtx", mandel_ir_gpu) check_target("cuda", mandel_ir_gpu) check_target("vulkan", mandel_ir_gpu) def test_while_binary_search(): def binary_search(ib, n, i, Aptr, Bptr, Cptr): lo = ib.allocate("int32", (1,), name="lo", scope="local") hi = ib.allocate("int32", (1,), name="hi", scope="local") lo[0] = 0 hi[0] = n v = Bptr[i] with ib.while_loop(lo[0] < hi[0]): mid = lo[0] + (hi[0] - lo[0] >> 1) with ib.if_scope(Aptr[mid] < v): lo[0] = mid + 1 with ib.else_scope(): hi[0] = mid Cptr[i] = lo[0] def searchsorted_ir_cpu(A, B, C, n): ib = tvm.tir.ir_builder.create() Aptr = ib.buffer_ptr(A) Bptr = ib.buffer_ptr(B) Cptr = ib.buffer_ptr(C) with ib.for_range(0, n, name="i", kind="parallel") as i: binary_search(ib, n, i, Aptr, Bptr, Cptr) body = ib.get() return body def searchsorted_ir_gpu(A, B, C, n): ib = tvm.tir.ir_builder.create() Aptr = ib.buffer_ptr(A) Bptr = ib.buffer_ptr(B) Cptr = ib.buffer_ptr(C) bx = te.thread_axis("blockIdx.x") tx = te.thread_axis("threadIdx.x") max_threads = 32 ib.scope_attr(bx, "thread_exten
t", tvm.tir.indexdiv(n + max_threads - 1, max_threads)) ib.scope_attr(tx, "thread_extent", max_threads) tid = bx * max_threads + tx with ib.if_scope(tid < n): binary_search(ib, n, tid, Aptr, Bptr, Cptr) body = ib.get() return body n = 1024 dtype = "float32" A = te.placeholder((n,), name="A", dtype=dtype) B = te.placeholder((n,), name="B", dtype=dtype) def check_target(target, ir): if not tvm.testing.device_enabled(target): return C = te.extern( A.shape, [A, B], lambda ins, outs: ir(ins[0], ins[1], outs[0], n), name="searchsorted_ir", dtype="int32", ) s = te.create_schedule(C.op) with tvm.transform.PassContext(opt_level=3): func = tvm.build(s, [A, B, C], target) dev = tvm.device(target, 0) a_np = np.random.uniform(size=n).astype(A.dtype) b_np = np.random.uniform(size=n).astype(B.dtype) a_np = np.sort(a_np) a = tvm.nd.array(a_np, dev) b = tvm.nd.array(b_np, dev) c = tvm.nd.array(np.zeros(n, dtype=C.dtype), dev) func(a, b, c) ref = np.searchsorted(a_np, b_np) tvm.testing.assert_allclose(c.numpy(), ref) check_target("llvm", searchsorted_ir_cpu) check_target("cuda", searchsorted_ir_gpu) check_target("nvptx", searchsorted_ir_gpu) check_target("vulkan", searchsorted_ir_gpu) @tvm.testing.requires_gpu def test_dyn_shared(): n = te.size_var("n") dtype = "float32" A = te.placeholder((n,), name="A") def test_device_ir(A, B): n = A.shape[0] ib = tvm.tir.ir_builder.create() tx = te.thread_axis("threadIdx.x") ib.scope_attr(tx, "thread_extent", n) temp = ib.allocate(dtype, (n,), scope="shared.dyn") Aptr = ib.buffer_ptr(A) Bptr = ib.buffer_ptr(B) temp[tx] = Aptr[tx] depth = tvm.tir.log2(cast(n, "float32")) with ib.for_range(0, cas
t(tvm.tir.ceil(depth), n.dtype)) as i: ib.emit(tvm.tir.Call(None, "tir.tvm_storage_sync", tvm.runtime.convert(["shared"]))) d = n >> (i + 1) with ib.if_scope(tx < d): temp[tx] += temp[tx + d] Bptr[0] = temp[0] return ib.get() B = te.extern( (1,), [A], lambda ins, outs: test_device_ir(ins[0], outs[0]), name="reduce", dtype=dtype, ) s = te.create_schedule(B.op) def check_target(target): if not tvm.testing.device_enabled(target): return freduce = tvm.build(s, [A, B], target) dev = tvm.device(target, 0) for n in [512, 1024]: a = tvm.nd.array(np.random.uniform(size=n).astype(A.dtype), dev) b = tvm.nd.array(np.zeros(1, dtype=B.dtype), dev) freduce(a, b) tvm.testing.assert_allclose(b.numpy()[0], np.sum(a.numpy()), 1e-4, 1e-4) for target in ["cuda", "nvptx"]: check_target(target) if __name__ == "__main__": test_prefetch() test_if() test_for() test_cpu() test_gpu() test_while_vectorize() test_while_collatz() test_while_mandel() test_while_binary_search() test_dyn_shared()
import pytest
import tvm from tvm.script
import tir as T def _check(original, transformed): mod = tvm.IRModule.from_expr(original) mod = tvm.tir.transform.LowerMatchBuffer()(mod) mod = tvm.tir.transform.Simplify()(mod) tvm.ir.assert_structural_equal(mod["main"], transformed) def _check_fail(original): mod = tvm.IRModule.from_expr(original) with pytest.raises(tvm.TVMError): mod = tvm.tir.transform.LowerMatchBuffer()(mod) @T.prim_func def buffer_load_store(a: T.handle, c: T.handle) -> None: A = T.match_buffer(a, (16, 16, 16)) C = T.match_buffer(c, (16, 16)) for i, j, k in T.grid(4, 16, 8): with T.block(): T.reads(C[i * 4 : i * 4 + 4, k * 2 : k * 2 + 2]) T.writes(A[i * 4 : i * 4 + 4, j, k * 2 : k * 2 + 2]) sub_A = T.match_buffer( A[i * 4 : i * 4 + 4, j, k * 2 : k * 2 + 2], (4, 1, 2), offset_factor=1 ) sub_C = T.match_buffer(C[i * 4 : i * 4 + 4, k * 2 : k * 2 + 2], (4, 2), offset_factor=1) for ii, kk in T.grid(4, 2): sub_A[ii, 0, kk] += sub_C[ii, kk] @T.prim_func def transformed_buffer_load_store(a: T.handle, c: T.handle) -> None: A = T.match_buffer(a, (16, 16, 16)) C = T.match_buffer(c, (16, 16)) for i, j, k in T.grid(4, 16, 8): with T.block(): T.reads(C[i * 4 : i * 4 + 4, k * 2 : k * 2 + 2]) T.writes(A[i * 4 : i * 4 + 4, j, k * 2 : k * 2 + 2]) for ii, kk in T.grid(4, 2): A[i * 4 + ii, j, k * 2 + kk] += C[i * 4 + ii, k * 2 + kk] @tvm.ir.register_op_attr("tir.intrin_test", "") def intrin_test(data, elem_offset, stride_0, stride_1, shape_0, shape_1): return 0 @T.prim_func def opaque_access(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, (32, 64, 128)) B = T.match_buffer(b, (64, 64, 64)) for i, j, k in T.grid(2, 64, 8): with T.block(): T.reads([]) T.writes(A[i * 16 : i * 16 + 16, j, k * 16 : k * 16 + 16]) sub_A = T.match_buffer( A[i * 16 :
i * 16 + 16, j, k * 16 : k * 16 + 16], (16, 1, 16), strides=[8192, 128, 1], offset_factor=1, ) T.evaluate( intrin_test( sub_A.data, sub_A.elem_offset, sub_A.strides[0], sub_A.strides[1], sub_A.shape[0], sub_A.shape[1], ) ) for i, j, k in T.grid(64, 2, 8): with T.block(): Bs_0 = T.var("int32") Bs_1 = T.var("int32") T.reads([]) T.writes(B[i, j * 32 : j * 32 + 32, k * 8 : k * 8 + 8]) sub_B = T.match_buffer( B[i, j * 32 : j * 32 + 32, k * 8 : k * 8 + 8], (32, 8), strides=[Bs_0, Bs_1], offset_factor=1, ) T.evaluate( intrin_test( sub_B.data, sub_B.elem_offset, sub_B.strides[0], sub_B.strides[1], sub_B.shape[0], sub_B.shape[1], ) ) @T.prim_func def transformed_opaque_access(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, (32, 64, 128)) B = T.match_buffer(b, (64, 64, 64)) for i, j, k in T.grid(2, 64, 8): with T.block(): T.reads([]) T.writes(A[i * 16 : i * 16 + 16, j, k * 16 : k * 16 + 16]) T.evaluate( intrin_test( A.data, i * 131072 + j * 128 + k * 16, 8192, 128, 16, 1, ) ) for i, j, k in T.grid(64, 2, 8): with T.block(): T.reads([]) T.writes(B[i, j * 32 : j * 32 + 32, k * 8 : k * 8 + 8]) T.evaluate( intrin_test( B.data, i * 4096 + j * 2048 +
k * 8, 64, 1, 32, 8, ) ) @T.prim_func def high_dim_opaque_access(a: T.handle) -> None: A = T.match_buffer(a, (16, 32, 64)) for i, j, k in T.grid(16, 2, 4): with T.block(): As_0 = T.var("int32") As_1 = T.var("int32") T.reads([]) T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16]) sub_A = T.match_buffer( A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], (16, 16), strides=[As_0, As_1], offset_factor=1, ) T.evaluate( intrin_test( sub_A.data, sub_A.elem_offset, sub_A.strides[0], sub_A.strides[1], sub_A.shape[0], sub_A.shape[1], ) ) @T.prim_func def transformed_high_dim_opaque_access(a: T.handle) -> None: A = T.match_buffer(a, (16, 32, 64)) for i, j, k in T.grid(16, 2, 4): with T.block(): T.reads([]) T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16]) T.evaluate( intrin_test( A.data, i * 2048 + j * 1024 + k * 16, 64, 1, 16, 16, ) ) @T.prim_func def high_dim_opaque_access_with_source_strides(a: T.handle) -> None: A = T.match_buffer(a, (16, 32, 64), strides=[2576, 80, 1]) for i, j, k in T.grid(16, 2, 4): with T.block(): As_0 = T.var("int32") As_1 = T.var("int32") T.reads([]) T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16]) sub_A = T.match_buffer( A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], (16, 16), strides=[As_0, As_1],
offset_factor=1, ) T.evaluate( intrin_test( sub_A.data, sub_A.elem_offset, sub_A.strides[0], sub_A.strides[1], sub_A.shape[0], sub_A.shape[1], ) ) @T.prim_func def transformed_high_dim_opaque_access_with_source_strides(a: T.handle) -> None: A = T.match_buffer(a, (16, 32, 64), strides=[2576, 80, 1]) for i, j, k in T.grid(16, 2, 4): with T.block(): T.reads([]) T.writes(A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16]) T.evaluate( intrin_test( A.data, i * 2576 + j * 1280 + k * 16, 80, 1, 16, 16, ) ) @T.prim_func def recursive_match(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, (64, 64, 64)) B = T.match_buffer(b, (64, 64, 64)) for i, j, k in T.grid(64, 4, 4): with T.block(): T.reads([]) T.writes( [ A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], B[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], ] ) As_0 = T.var("int32") As_1 = T.var("int32") sub_A = T.match_buffer( A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], (16, 16), strides=[As_0, As_1], offset_factor=1, ) sub_B = T.match_buffer( B[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], (16, 16), offset_factor=1, ) for jj, kk in T.grid(4, 4): with T.block(): T.reads([]) T.writes( [ sub_A[jj * 4 : jj * 4 + 4, kk * 4 :
kk * 4 + 4], sub_B[jj * 4 : jj * 4 + 4, kk * 4 : kk * 4 + 4], ] ) Ass_0 = T.var("int32") Ass_1 = T.var("int32") sub_sub_A = T.match_buffer( sub_A[jj * 4 : jj * 4 + 4, kk * 4 : kk * 4 + 4], (4, 4), strides=[Ass_0, Ass_1], offset_factor=1, ) sub_sub_B = T.match_buffer( sub_B[jj * 4 : jj * 4 + 4, kk * 4 : kk * 4 + 4], (4, 4), offset_factor=1, ) T.evaluate( intrin_test( sub_sub_A.data, sub_sub_A.elem_offset, sub_sub_A.strides[0], sub_sub_A.strides[1], sub_sub_A.shape[0], sub_sub_A.shape[1], ) ) for jjj, kkk in T.grid(4, 4): sub_sub_B[jjj, kkk] = 1 @T.prim_func def transformed_recursive_match(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, (64, 64, 64)) B = T.match_buffer(b, (64, 64, 64)) for i, j, k in T.grid(64, 4, 4): with T.block(): T.reads([]) T.writes( [ A[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], B[i, j * 16 : j * 16 + 16, k * 16 : k * 16 + 16], ] ) for jj, kk in T.grid(4, 4): with T.block(): T.reads([]) T.writes( [ A[ i, j * 16 + jj * 4 : j * 16 + jj * 4 + 4, k * 16 + kk * 4 : k * 16 + kk * 4 + 4,
], B[ i, j * 16 + jj * 4 : j * 16 + jj * 4 + 4, k * 16 + kk * 4 : k * 16 + kk * 4 + 4, ], ] ) T.evaluate( intrin_test( A.data, i * 4096 + j * 1024 + jj * 256 + k * 16 + kk * 4, 64, 1, 4, 4, ) ) for jjj, kkk in T.grid(4, 4): B[i, j * 16 + jj * 4 + jjj, k * 16 + kk * 4 + kkk] = 1 @T.prim_func def symbolic_match(a: T.handle, b: T.handle, n: T.int32, m: T.int32) -> None: A = T.match_buffer(a, (n * m, m)) B = T.match_buffer(b, (n * 2, m * 4)) for i in range(0, n): with T.block(): T.reads([]) T.writes([A[i * m : i * m + n, 0:m], B[i * n : i * n + 2, 0 : m * 4]]) Bs_0 = T.var("int32") Bs_1 = T.var("int32") sub_A = T.match_buffer(A[i * m : i * m + m, 0:m], (m, m), offset_factor=1) sub_B = T.match_buffer( B[i * n : i * n + 2, 0 : m * 4], (2, m * 4), strides=[Bs_0, Bs_1], offset_factor=1 ) for ii, jj in T.grid(m, m): sub_A[ii, jj] = 1 for j in range(0, 4): T.evaluate( intrin_test( sub_B.data, sub_B.elem_offset, sub_B.strides[0], sub_B.strides[1], sub_B.shape[0], sub_B.shape[1], ) ) @T.prim_func def transformed_symbolic_match(a: T.handle, b: T.handle, n: T.int32, m: T.int32) -> None: A = T.match_buffer(a, (n * m, m)) B = T.match_buffer(b, (
n * 2, m * 4)) for i in range(0, n): with T.block(): T.reads([]) T.writes([A[i * m : i * m + n, 0:m], B[i * n : i * n + 2, 0 : m * 4]]) for ii, jj in T.grid(m, m): A[i * m + ii, jj] = 1 for j in range(0, 4): T.evaluate( intrin_test( B.data, i * n * (m * 4), m * 4, 1, 2, m * 4, ) ) @T.prim_func def rank0_buffer(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, (8, 8)) B = T.match_buffer(b, (8, 8)) for i, j in T.grid(8, 8): with T.block(): T.reads([]) T.writes([A[i, j], B[i, j]]) sub_A = T.match_buffer(A[i, j], (), offset_factor=1) sub_B = T.match_buffer(B[i, j], (), offset_factor=1) sub_A[()] = 1 T.evaluate( intrin_test( sub_B.data, sub_B.elem_offset, 0, 0, 0, 0, ) ) @T.prim_func def transformed_rank0_buffer(a: T.handle, b: T.handle) -> None: A = T.match_buffer(a, (8, 8)) B = T.match_buffer(b, (8, 8)) for i, j in T.grid(8, 8): with T.block(): T.reads([]) T.writes([A[i, j], B[i, j]]) A[i, j] = 1 T.evaluate( intrin_test( B.data, i * 8 + j, 0, 0, 0, 0, ) ) @T.prim_func def fail_match_load(a: T.handle) -> None: A = T.match_buffer(a, (8, 8)) for i, j in T.grid(8, 8): with T.block(): T.reads(A[i, j]) T.writes([]) sub_A = T.match_buffer(A[i, j], (), elem_offset=0) T.evaluate(sub_A
[()]) @T.prim_func def fail_match_store(a: T.handle) -> None: A = T.match_buffer(a, (8, 8)) for i, j in T.grid(8, 8): with T.block(): T.reads([]) T.writes(A[i, j]) sub_A = T.match_buffer(A[i, j], (), elem_offset=0) sub_A[()] = 1 @T.prim_func def fail_buffer_bind(a: T.handle) -> None: A = T.match_buffer(a, (8, 8)) for i, j in T.grid(8, 2): with T.block(): stride = T.var("int32") sub_A = T.match_buffer( A[i, j * 4 : j * 4 + 4], (1, 4), strides=[stride, stride], offset_factor=1 ) for jj in range(0, 4): sub_A[i, j * 4 + jj] = 1 @T.prim_func def fail_match_func_param(a: T.handle, m: T.handle, n: T.handle) -> None: A = T.match_buffer(a, (8, 8)) for i, j in T.grid(8, 2): with T.block(): sub_A = T.match_buffer(A[i, j * 4 : j * 4 + 4], (1, 4), strides=[m, n], offset_factor=1) for jj in range(0, 4): sub_A[i, j * 4 + jj] = 1 def test_buffer_load_store(): _check(buffer_load_store, transformed_buffer_load_store) def test_opaque_access(): _check(opaque_access, transformed_opaque_access) def test_high_dim_opaque_access(): _check(high_dim_opaque_access, transformed_high_dim_opaque_access) _check( high_dim_opaque_access_with_source_strides, transformed_high_dim_opaque_access_with_source_strides, ) def test_recursive_match(): _check(recursive_match, transformed_recursive_match) def test_symbolic_match(): _check(symbolic_match, transformed_symbolic_match) def test_rank0_buffer(): _check(rank0_buffer, transformed_rank0_buffer) def test_fail_load_store(): _check_fail(fail_match_load) _check_fail(fail_match_store) def test_fail_buffer_bind(): _check_fail(fail_buffer_bind) def test_fail_match_func_param(): _check_fail(fail_match_func_param) if __name__ == "__main__": test_buffer_load_store() test_opaque_access() test_high_d
im_opaque_access() test_recursive_match() test_symbolic_match() test_rank0_buffer() test_fail_load_store() test_fail_buffer_bind() test_fail_match_func_param()
import pytest
import tvm from tvm
import te, ir
import numpy as np def test_const(): x = tvm.tir.const(1, "int32") assert x.dtype == "int32" assert isinstance(x, tvm.tir.IntImm) def test_te_const(): x = tvm.te.const(1, "int32") assert x.dtype == "int32" assert isinstance(x, tvm.tir.IntImm) def test_scalar_dtype_inference(): for data in [ True, bool(1), np.uint8(1), np.uint16(1), np.uint32(1), np.uint64(1), np.int8(1), np.int16(1), np.int32(1), np.int64(1), np.float16(1), np.float32(1), np.float64(1), ]: assert tvm.tir.const(data).dtype == str(np.array(data).dtype) assert tvm.tir.const(1).dtype == "int32" assert tvm.tir.const(1.0).dtype == "float32" for data in [ True, bool(1), np.uint8(1), np.uint16(1), np.uint32(1), np.uint64(1), np.int8(1), np.int16(1), np.int32(1), np.int64(1), np.float16(1), np.float32(1), np.float64(1), ]: assert tvm.runtime.convert(data).dtype == str(np.array(data).dtype) assert tvm.runtime.convert(1).dtype == "int32" assert tvm.runtime.convert(1.0).dtype == "float32" def test_make(): x = tvm.tir.const(1, "int32") y = te.var("x") z = x + y assert isinstance(tvm.tir.max(x, y), tvm.tir.Max) assert isinstance(tvm.tir.min(x, y), tvm.tir.Min) def test_ir(): x = tvm.tir.const(1, "int32") y = tvm.tir.IntImm("int32", 1) z = x + y stmt = tvm.tir.Evaluate(z) assert isinstance(stmt, tvm.tir.Evaluate) def test_ir2(): buf_size = te.var("size") x = te.var("n") storage_type = ir.PrimType("int32") handle_type = ir.PointerType(storage_type) array = te.var("array", handle_type) buf = tvm.tir.decl_buffer([buf_size], "int32", data=array) st = tvm.tir.BufferStore(buf, x + 1, [1]) assert isinstance(st, tvm.tir.BufferStore) assert st.buffer == buf assert st.buffer.data == array def test_let
(): x = te.var("x") y = te.var("y") stmt = tvm.tir.LetStmt(x, 10, tvm.tir.Evaluate(x + 1)) def test_cast(): x = te.var("x", dtype="float32") y = x.astype("int32") z = x.astype("float32x4") assert isinstance(y, tvm.tir.Cast) assert isinstance(z, tvm.tir.Broadcast) assert z.lanes == 4 s = tvm.tir.StringImm("s") with pytest.raises(tvm.error.TVMError) as cm: s.astype("int") assert "Can't cast a handle to other types" in str(cm.execption) def test_attr(): x = te.var("x") y = te.var("y") stmt = tvm.tir.AttrStmt(y, "stride", 10, tvm.tir.Evaluate(x + 1)) assert stmt.node == y a = tvm.runtime.convert(1) assert a.value == 1 try: a.no_field assert False except AttributeError: pass def test_basic(): a = te.var("a") b = te.var("b") c = a + b assert str(c) == "(%s: int32 + %s: int32)" % (a.name, b.name) def test_stmt(): x = tvm.tir.Evaluate(0) tvm.tir.For(te.var("i"), 0, 1, tvm.tir.ForKind.SERIAL, x) def test_dir(): x = te.var("x") dir(x) def test_dtype(): x = te.var("x") assert x.dtype == "int32" y = te.var("y") assert (x > y).dtype == "bool" def test_any(): x = te.var("x") y = te.var("y") z = te.var("z") try: t = x or x assert False except ValueError: pass try: tvm.tir.any() assert False except ValueError: pass assert str(tvm.tir.any(x < y)) == "(%s: int32 < %s: int32)" % (x.name, y.name) assert str(tvm.tir.any(x < y, x > z)) == "((%s: int32 < %s: int32) || (%s > %s: int32))" % ( x.name, y.name, x.name, z.name, ) assert str( tvm.tir.any(x < y, y > z + 1, x < z * 2) ) == "(((%s: int32 < %s: int32) || (%s > (%s: int32 + 1))) || (%s < (%s*2)))" % ( x.name, y.name, y.name, z.name, x.name, z.name, ) def test_all(): x = te.var("x") y = te.var("y") z = te.v
ar("z") try: t = x and x assert False except ValueError: pass try: tvm.tir.all() assert False except ValueError: pass assert str(tvm.tir.all(x < y)) == "(%s: int32 < %s: int32)" % (x.name, y.name) assert str(tvm.tir.all(x < y, x > z)) == "((%s: int32 < %s: int32) && (%s > %s: int32))" % ( x.name, y.name, x.name, z.name, ) assert str( tvm.tir.all(x < y, y > z + 1, x < z * 2) ) == "(((%s: int32 < %s: int32) && (%s > (%s: int32 + 1))) && (%s < (%s*2)))" % ( x.name, y.name, y.name, z.name, x.name, z.name, ) def test_bitwise(): x = te.var("x") y = te.var("y") assert str(x << y) == "@tir.shift_left(x: int32, y: int32, dtype=int32)" assert str(x >> y) == "@tir.shift_right(x: int32, y: int32, dtype=int32)" assert str(x & y) == "@tir.bitwise_and(x: int32, y: int32, dtype=int32)" assert str(x | y) == "@tir.bitwise_or(x: int32, y: int32, dtype=int32)" assert str(x ^ y) == "@tir.bitwise_xor(x: int32, y: int32, dtype=int32)" assert str(10 & x) == "@tir.bitwise_and(10, x: int32, dtype=int32)" assert str(10 | x) == "@tir.bitwise_or(10, x: int32, dtype=int32)" assert str(10 ^ x) == "@tir.bitwise_xor(10, x: int32, dtype=int32)" assert str(10 >> x) == "@tir.shift_right(10, x: int32, dtype=int32)" assert str(10 << x) == "@tir.shift_left(10, x: int32, dtype=int32)" assert str(10 % x) == "floormod(10, x: int32)" assert str(~x) == "@tir.bitwise_not(x: int32, dtype=int32)" assert (tvm.tir.const(1, "int8x2") >> 1).dtype == "int8x2" assert (x >> tvm.tir.const(1, "int32x2")).dtype == "int32x2" assert (te.var("z", "int8x2") << tvm.tir.const(1, "int8x2")).dtype == "int8x2" def test_float_bitwise(): t = tvm.tir.const(1.5, dtype="float32") for test in [ lambda lhs, rhs: lhs << rhs, lambda lhs, rhs: lhs >> rhs, lambda lhs, rhs: lhs | rhs, lambda lhs, rhs: lhs
^ rhs, lambda lhs, rhs: lhs & rhs, ]: try: test(t, 10.0) assert False except tvm.TVMError: pass try: ~t assert False except RuntimeError: pass def test_shift_bounds(): x = te.var("x") for test in [lambda lhs, rhs: lhs << rhs, lambda lhs, rhs: lhs >> rhs]: for testcase in [(x, -1), (x, 32)]: try: test(*testcase) assert False except tvm.TVMError: pass for testcase in [(x, 0), (x, 16), (x, 31)]: test(*testcase) def test_divide_by_zero(): for test in [ lambda lhs, rhs: tvm.tir.floormod(lhs, rhs), lambda lhs, rhs: tvm.tir.floordiv(lhs, rhs), lambda lhs, rhs: tvm.tir.truncmod(lhs, rhs), lambda lhs, rhs: tvm.tir.truncdiv(lhs, rhs), lambda lhs, rhs: tvm.tir.div(lhs, rhs), ]: try: test(tvm.tir.const(5, "int32"), tvm.tir.const(0, "int32")) assert False except tvm.TVMError: pass def test_infinity(): assert str(tvm.tir.infinity("float16")) == "inff16" assert str(tvm.tir.infinity("float32")) == "inff32" assert str(tvm.tir.infinity("float64")) == "inff64" def test_isnan(): x = te.var("x", "float32") assert str(tvm.tir.isnan(x)) == "@tir.isnan(x: float32, dtype=bool)" assert str(tvm.tir.isnan(x).dtype) == "bool" y = te.var("y", "float16") assert str(tvm.tir.isnan(y)) == "@tir.isnan(cast(float32, y: float16), dtype=bool)" z = te.var("z", "int32") assert str(tvm.tir.isnan(z)) == "False" k = te.var("k", "int8x2") assert str(tvm.tir.isnan(k).dtype) == "uint1x2" def test_equality(): a = te.var("a") b = te.var("b") c = a == b assert not c d = c != c assert not d def test_equality_string_imm(): x = "a" y = tvm.tir.StringImm(x) x == y.value x == y def test_prim_func(): x = te.var("x") y = te.var("y") b = tv
m.tir.decl_buffer((x,), "float32") stmt = tvm.tir.LetStmt(x, 10, tvm.tir.Evaluate(x + 1)) func = tvm.tir.PrimFunc([x, y, b], stmt) func.astext() assert func.buffer_map[func.params[2]].same_as(b) assert len(func.buffer_map) == 1 f2 = func.with_attr({"calling_conv": 1, "tir.noalias": True}) assert f2.attrs["calling_conv"].value == 1 assert func.attrs is None def test_vars(): x = tvm.tir.Var("xyz", "int8") assert x.dtype == "int8" ptype = tvm.ir.PointerType(tvm.ir.PrimType("float")) x = tvm.tir.Var("xyz", ptype) assert x.dtype == "handle" assert x.type_annotation == ptype assert isinstance(ptype.element_type, tvm.ir.PrimType) def test_scoped_storage_vars(): dtype = "float" storage_scope = "global.texture" ptype = tvm.ir.PointerType(tvm.ir.PrimType(dtype), storage_scope) x = tvm.tir.Var("xyz", ptype) assert x.dtype == "handle" assert x.type_annotation == ptype assert x.type_annotation.storage_scope == storage_scope assert isinstance(ptype.element_type, tvm.ir.PrimType) def test_buffer_load_store(): b = tvm.tir.decl_buffer((10,), "float32") x = tvm.tir.BufferLoad(b, [0]) assert isinstance(x, tvm.tir.BufferLoad) assert x.dtype == "float32" assert x.buffer == b s = tvm.tir.BufferStore(b, 0.1, [0]) assert isinstance(s, tvm.tir.BufferStore) s = tvm.tir.BufferRealize(b, [tvm.ir.Range(0, 1)], True, tvm.tir.Evaluate(0)) assert isinstance(s, tvm.tir.BufferRealize) def test_intimm_cond(): x = tvm.runtime.convert(1) y = tvm.runtime.convert(1) s = {x} assert y in s assert x == y assert x < 20 assert not (x >= 20) assert x < 10 and y < 10 assert not tvm.runtime.convert(x != 1) assert x == 1 def test_block_blockrealize(): x = tvm.tir.Var("x", "int32") y = tvm.tir.Var("y", "int32") vx = tvm.tir.IterVar((16, 16), "vx", 0) vx_var = vx.var vy = tvm.tir.IterVar((16, 16), "vy", 2) vy_var = vy.var A = tvm.tir.decl_buffer((16),
"float32") B = tvm.tir.decl_buffer((16, 16), "float32") alloc_buffer = tvm.tir.decl_buffer((16, 16), "float32") match_buffer = tvm.tir.decl_buffer((16, 16), "float32") init_body = tvm.tir.BufferStore(A, 0.0, [vx_var]) body = tvm.tir.BufferStore( A, tvm.tir.BufferLoad(A, [vx_var]) + tvm.tir.BufferLoad(B, [vx_var, vy_var]), [vx_var], ) reads = [ tvm.tir.BufferRegion( B, [tvm.ir.Range.from_min_extent(vx_var, 1), tvm.ir.Range.from_min_extent(vy_var, 1)] ) ] writes = [tvm.tir.BufferRegion(A, [tvm.ir.Range.from_min_extent(vx_var, 1)])] block_match_buffer = tvm.tir.MatchBufferRegion( match_buffer, tvm.tir.BufferRegion(B, [tvm.ir.Range(0, 16), tvm.ir.Range(0, 16)]) ) block = tvm.tir.Block( [vx, vy], reads, writes, "block", body, init=init_body, alloc_buffers=[alloc_buffer], match_buffers=[block_match_buffer], annotations={"attr_key": "attr_value"}, ) assert isinstance(block, tvm.tir.Block) assert block.iter_vars[0] == vx assert block.iter_vars[1] == vy assert isinstance(block.reads[0], tvm.tir.BufferRegion) assert block.reads[0].buffer == B assert block.reads[0].region[0].min == vx_var assert block.reads[0].region[1].min == vy_var assert isinstance(block.writes[0], tvm.tir.BufferRegion) assert block.writes[0].buffer == A assert block.writes[0].region[0].min == vx_var assert block.writes[0].region[0].extent == 1 assert block.name_hint == "block" assert block.body == body assert block.init == init_body assert block.alloc_buffers[0] == alloc_buffer assert block.match_buffers[0].buffer == match_buffer assert isinstance(block.match_buffers[0].source, tvm.tir.BufferRegion) assert block.match_buffers[0].source.buffer == B assert block.match_buffers[0].source.region[0].min == 0 assert block.match_buffers[0].source.region[0].exte
nt == 16 block_realize = tvm.tir.BlockRealize([x, y], tvm.tir.const(True, "bool"), block) assert isinstance(block_realize, tvm.tir.BlockRealize) assert block_realize.iter_values[0] == x assert block_realize.iter_values[1] == y assert block_realize.predicate == tvm.tir.const(True, "bool") assert block_realize.block == block str(block) str(block_realize) func = tvm.tir.PrimFunc([], block_realize) output = func.astext() assert output.find("meta[tir.BlockRealise]") == -1 assert output.find("bind") != -1 assert output.find("reads") != -1 assert output.find("writes") != -1 assert output.find("alloc_buffer") != -1 assert output.find("match_buffer") != -1 assert output.find("attr") != -1 assert output.find("with init()") != -1 def test_tir_allocate(): dtype = "int8" storage_scope = "global" ptype = tvm.ir.PointerType(tvm.ir.PrimType(dtype), storage_scope) a = te.var("buffer", ptype) allocate = tvm.tir.Allocate( buffer_var=a, dtype=dtype, extents=[2, 2], condition=tvm.get_global_func("tir.const_true")(dtype, None), body=tvm.tir.Evaluate(2 + 1), annotations={ "attr1": "foo", "attr2": "bar", }, ) assert allocate.buffer_var == a assert allocate.dtype == "int8" assert list(allocate.extents) == [2, 2] assert allocate.annotations["attr1"] == "foo" assert allocate.annotations["attr2"] == "bar" func = tvm.tir.PrimFunc([], allocate) output = func.astext() assert ( output.find( 'allocate(buffer: Pointer(global int8), int8, [2, 2]), storage_scope = global, annotations = {"attr2": "bar", "attr1": "foo"})' ) != -1 ) if __name__ == "__main__": pytest.main([__file__])
import tvm
import tvm.testing from tvm
import tir def test_tir_op_tvm_tuple(): x = tir.Var("x", dtype="float32") y = tir.Var("y", dtype="float32") z = tir.Var("z", dtype="float32") expr = tir.tvm_tuple(x, y, z, 1, 2, 3) assert expr.op.name == "tir.tvm_tuple" def test_tir_op_tvm_struct_get(): x = tir.Var("x", dtype="handle") expr = tir.tvm_struct_get(x, 1, 2, dtype="int32") assert expr.op.name == "tir.tvm_struct_get" def test_tir_op_tvm_struct_set(): x = tir.Var("x", dtype="handle") expr = tir.tvm_struct_set(x, 1, 2, 3) assert expr.op.name == "tir.tvm_struct_set" def test_tir_op_address_of(): buffer = tir.decl_buffer((128), "float32") expr = tir.address_of(buffer[0]) assert expr.op.name == "tir.address_of" def test_tir_op_lookup_param(): expr = tir.lookup_param("p0") assert expr.op.name == "tir.lookup_param" def test_tir_op_reinterpret(): x = tir.Var("x", dtype="int32") expr = tir.reinterpret("float32", x) assert expr.op.name == "tir.reinterpret" def test_tir_op_isnullptr(): x = tir.Var("x", dtype="int32") expr = tir.isnullptr(x) assert expr.op.name == "tir.isnullptr" def test_tir_op_call_assume(): x = tir.Var("x", dtype="int32") expr = tir.assume(cond=x) assert expr.op.name == "tir.assume" def test_tir_op_call_undef(): expr = tir.undef() assert expr.op.name == "tir.undef" def test_tir_op_call_likely(): x = tir.Var("x", dtype="int32") expr = tir.likely(cond=x) assert expr.op.name == "tir.likely" def test_tir_op_tvm_thread_allreduce(): x = tir.Var("x", "int32") buffer = tir.decl_buffer((128), "float32") y = tir.Var("y", "handle") z = tir.Var("z", "int32") expr = tir.tvm_thread_allreduce(x, buffer[0], True, y, z) assert expr.op.name == "tir.tvm_thread_allreduce" def test_tir_op_type_annotation(): expr = tir.type_annotation("int32") assert expr.op.name == "tir.type_annotation" def test_tir_op_tvm_access_ptr(): buffer = tir.decl_buffer((128), "float32") expr = tir.tvm_acces
s_ptr("float32", buffer.data, 0, 1, 2) assert expr.op.name == "tir.tvm_access_ptr" def test_tir_op_tvm_throw_last_error(): expr = tir.tvm_throw_last_error() assert expr.op.name == "tir.tvm_throw_last_error" def test_tir_op_tvm_load_matrix_sync(): buffer = tir.decl_buffer((16, 16), "float32") x = tir.Var("x", "handle") expr = tir.tvm_load_matrix_sync(buffer.data, 16, 16, 16, 0, x, 128, "row_major") assert expr.op.name == "tir.tvm_load_matrix_sync" def test_tir_op_tvm_store_matrix_sync(): buffer = tir.decl_buffer((16, 16), "float32") x = tir.Var("x", "handle") expr = tir.tvm_store_matrix_sync(buffer.data, 16, 16, 16, 0, x, 128, "row_major") assert expr.op.name == "tir.tvm_store_matrix_sync" def test_tir_op_tvm_mma_sync(): buffer_0 = tir.decl_buffer((16, 16), "float32") buffer_1 = tir.decl_buffer((16, 16), "float32") buffer_2 = tir.decl_buffer((16, 16), "float32") buffer_3 = tir.decl_buffer((16, 16), "float32") expr = tir.tvm_mma_sync(buffer_0.data, 0, buffer_1.data, 0, buffer_2.data, 0, buffer_3.data, 0) assert expr.op.name == "tir.tvm_mma_sync" def test_tir_op_tvm_bmma_sync(): buffer_0 = tir.decl_buffer((16, 16), "float32") buffer_1 = tir.decl_buffer((16, 16), "float32") buffer_2 = tir.decl_buffer((16, 16), "float32") buffer_3 = tir.decl_buffer((16, 16), "float32") expr = tir.tvm_bmma_sync(buffer_0.data, 0, buffer_1.data, 0, buffer_2.data, 0, buffer_3.data, 0) assert expr.op.name == "tir.tvm_bmma_sync" def test_tir_op_tvm_fill_fragment(): buffer = tir.decl_buffer((16, 16), "float32") expr = tir.tvm_fill_fragment(buffer.data, 16, 16, 16, 0, 0) assert expr.op.name == "tir.tvm_fill_fragment" def test_tir_op_ptx_mma(): buffer_a = tir.decl_buffer([32], "int4", scope="local") buffer_b = tir.decl_buffer([16], "uint4", scope="local") buffer_c = tir.decl_buffer([4], "int32", scope="local") expr = tir.ptx_mma( "int32", "m8n8k32", "row", "col", "int4",
"uint4", "int32", buffer_a.data, 0, buffer_b.data, 0, buffer_c.data, 0, False, ) assert expr.op.name == "tir.ptx_mma" def test_tir_op_ptx_mma_sp(): buffer_a = tir.decl_buffer([32], "int4", scope="local") buffer_b = tir.decl_buffer([16], "uint4", scope="local") buffer_c = tir.decl_buffer([4], "int32", scope="local") buffer_d = tir.decl_buffer([1], "uint32", scope="local") expr = tir.ptx_mma_sp( "int32", "m8n8k32", "row", "col", "int4", "uint4", "int32", buffer_a.data, 0, buffer_b.data, 0, buffer_c.data, 0, buffer_d.data, 0, 0, False, ) assert expr.op.name == "tir.ptx_mma_sp" def test_tir_op_mma_store(): x = tir.Var("x", dtype="int32") y = tir.Var("y", dtype="int32") buffer_w = tir.decl_buffer([16, 8], dtype="int32", scope="warp", offset_factor=1) buffer = tir.decl_buffer( [16, 16], dtype="int32", scope="global", offset_factor=1, strides=[x, y] ) expr = tir.mma_store( "int32", 16, 16, buffer.access_ptr("w"), buffer_w.data, buffer_w.elem_offset, x, ) assert expr.op.name == "tir.mma_store" def test_tir_op_mma_fill(): buffer_w = tir.decl_buffer([16, 8], dtype="int32", scope="warp", offset_factor=1) expr = tir.mma_fill("int32", 8, buffer_w.data, buffer_w.elem_offset) assert expr.op.name == "tir.mma_fill" def test_op_ptx_ldmatrix(): buffer_shared = tir.decl_buffer([16, 16], "float16", scope="shared") buffer_local = tir.decl_buffer([8], "float16", scope="local") expr = tir.ptx_ldmatrix( "float16", False, 4, ".b16", buffer_local.data, 0, buffer_shared.data, 0 ) assert expr.op.name == "tir.ptx_ldmatrix" def test_op_ptx_cp_async(): buffer_shared = tir.decl_buffer([16, 16], "float16", scope="shared") buffer_local = tir.decl_buffer([8],
"float16", scope="local") expr = tir.ptx_cp_async("float16", buffer_shared.data, 0, buffer_local.data, 0, 16) assert expr.op.name == "tir.ptx_cp_async" def test_op_ptx_commit_group(): expr = tir.ptx_commit_group() assert expr.op.name == "tir.ptx_commit_group" def test_op_ptx_wait_group(): expr = tir.ptx_wait_group(8) assert expr.op.name == "tir.ptx_wait_group" def test_tir_op_vectorlow(): buffer = tir.decl_buffer((4, 4), "int8", offset_factor=1) vec = buffer.vload([0, 0], dtype="int8x16") expr = tir.vectorlow("int8x8", vec) assert expr.op.name == "tir.vectorlow" def test_tir_op_vectorhigh(): buffer = tir.decl_buffer((4, 4), "int8", offset_factor=1) vec = buffer.vload([0, 0], dtype="int8x16") expr = tir.vectorhigh("int8x8", vec) assert expr.op.name == "tir.vectorhigh" def test_tir_op_vectorcombine(): buffer = tir.decl_buffer((4, 4), "int8", offset_factor=1) vec = buffer.vload([0, 0], dtype="int8x16") expr = tir.vectorcombine("int8x8", vec, vec) assert expr.op.name == "tir.vectorcombine" def test_tir_op_shift_left(): x = tir.Var("x", dtype="int32") y = tir.Var("x", dtype="int32") expr = tir.shift_left(x, y) assert expr.op.name == "tir.shift_left" def test_tir_op_shift_right(): x = tir.Var("x", dtype="int32") y = tir.Var("x", dtype="int32") expr = tir.shift_right(x, y) assert expr.op.name == "tir.shift_right" def test_tir_op_TVMBackendAllocWorkspace(): expr = tir.TVMBackendAllocWorkspace(0, 1, 2, 3, 4) assert expr.op.name == "tir.TVMBackendAllocWorkspace" def test_tir_op_TVMBackendFreeWorkspace(): buffer = tir.decl_buffer((128), "float32") expr = tir.TVMBackendFreeWorkspace(0, 1, buffer.data) assert expr.op.name == "tir.TVMBackendFreeWorkspace" if __name__ == "__main__": tvm.testing.main()
import tvm from tvm