text
stringlengths 1
2.05k
|
---|
, 2**31 - 1) * i, name="A")
s = te.create_schedule(A.op)
s[A].vectorize(A.op.axis[1])
lower_sch(s, [A], 32, extra_passes=[tvm.tir.transform.VectorizeLoop()])
def test_condition():
@T.prim_func
def before(A: T.Buffer[(128,), "float32"], B: T.Buffer[(130,), "float32"]):
for i, j in T.grid(T.int64(2), T.int64(65)):
if i * T.int64(65) + j >= T.int64(0) and i * T.int64(65) + j < T.int64(128):
A[i * T.int64(65) + j] = 0.0
for i, j in T.grid(T.int64(2), T.int64(65)):
B[i * T.int64(65) + j] = T.if_then_else(
i * T.int64(65) + j >= T.int64(0) and i * T.int64(65) + j < T.int64(128),
A[i * T.int64(65) + j],
0.0,
dtype="float32",
)
@T.prim_func
def expected_after(A: T.Buffer[128, "float32"], B: T.Buffer[130, "float32"]):
for i, j in T.grid(2, 65):
if i * 65 + j >= 0 and i * 65 + j < 128:
A[i * 65 + j] = T.float32(0)
for i, j in T.grid(2, 65):
B[i * 65 + j] = T.if_then_else(
i * 65 + j >= 0 and i * 65 + j < 128, A[i * 65 + j], T.float32(0), dtype="float32"
)
after = tvm.tir.transform.NarrowDataType(32)(tvm.IRModule.from_expr(before))["main"]
tvm.ir.assert_structural_equal(after, expected_after)
if __name__ == "__main__":
test_basic()
test_thread_axis()
test_thread_axis_2()
test_multilanes()
test_reduce()
test_slice()
test_relay_basic()
test_relay_take()
test_ramp_dtype_consistency()
test_condition() |
import tvm |
import tvm.testing
from tvm |
import te
from tvm.script |
import tir as T
def _check(original, transformed):
func = original
mod = tvm.IRModule.from_expr(func)
mod = tvm.tir.transform.PlanAndUpdateBufferAllocationLocation()(mod)
tvm.ir.assert_structural_equal(mod["main"], transformed)
@T.prim_func
def element_func(a: T.handle, c: T.handle) -> None:
A = T.match_buffer(a, (16, 16))
C = T.match_buffer(c, (16, 16))
B = T.alloc_buffer((16, 16))
for i0 in range(0, 16):
for j0 in range(0, 16):
with T.block():
i, j = T.axis.remap("SS", [i0, j0])
B[i, j] = A[i, j] + 1.0
for j0 in range(0, 16):
with T.block():
i, j = T.axis.remap("SS", [i0, j0])
C[i, j] = B[i, j] * 2.0
@T.prim_func
def transformed_element_func(a: T.handle, c: T.handle) -> None:
A = T.match_buffer(a, [16, 16])
C = T.match_buffer(c, [16, 16])
for i_0 in range(0, 16):
with T.block():
T.reads([A[i_0, 0:16]])
T.writes([C[i_0, 0:16]])
B = T.alloc_buffer([16, 16])
for j_0 in T.serial(0, 16):
with T.block():
i, j = T.axis.remap("SS", [i_0, j_0])
B[i, j] = A[i, j] + 1.0
for j_0 in T.serial(0, 16):
with T.block():
i, j = T.axis.remap("SS", [i_0, j_0])
C[i, j] = B[i, j] * 2.0
@T.prim_func
def original_func() -> None:
A = T.alloc_buffer((128, 128), "float32")
for i0, j0 in T.grid(128, 128):
with T.block():
i, j = T.axis.remap("SS", [i0, j0])
A[i, j] = T.float32(0)
for i0, j0, k0 in T.grid(32, 32, 32):
with T.block():
i, j, k = T.axis.remap("SSR", [i0, j0, k0])
B = T.alloc_buffer((128, 128), "float32")
C = T.alloc_buffer((128, 128), "float32")
D = T.alloc_buffer((128, 128), "float32")
if k == 0:
for ii, jj in T.grid(4, 4):
B[i * 4 + ii, j * 4 + jj] = |
A[i * 4 + ii, j * 4 + jj]
for ii, jj in T.grid(4, 4):
for kk in range(0, 4):
B[i * 4 + ii, j * 4 + jj] += C[i * 4 + ii, k * 4 + kk]
for kk in range(0, 4):
B[i * 4 + ii, j * 4 + jj] += (
D[j * 4 + jj, k * 4 + kk] * C[i * 4 + ii, k * 4 + kk]
)
@T.prim_func
def transformed_func() -> None:
A = T.alloc_buffer([128, 128])
for i0, j0 in T.grid(128, 128):
with T.block():
i, j = T.axis.remap("SS", [i0, j0])
A[i, j] = T.float32(0)
for i0, j0, k0 in T.grid(32, 32, 32):
with T.block():
i, j, k = T.axis.remap("SSR", [i0, j0, k0])
B = T.alloc_buffer([128, 128])
if k == 0:
for ii, jj in T.grid(4, 4):
B[i * 4 + ii, j * 4 + jj] = A[i * 4 + ii, j * 4 + jj]
for ii, jj in T.grid(4, 4):
with T.block(""):
T.reads([B[((i * 4) + ii), ((j * 4) + jj)]])
T.writes([B[((i * 4) + ii), ((j * 4) + jj)]])
C = T.alloc_buffer([128, 128])
for kk in T.serial(0, 4):
B[((i * 4) + ii), ((j * 4) + jj)] = (
B[((i * 4) + ii), ((j * 4) + jj)] + C[((i * 4) + ii), ((k * 4) + kk)]
)
for kk in T.serial(0, 4):
with T.block(""):
T.reads(
[
B[((i * 4) + ii), ((j * 4) + jj)],
C[((i * 4) + ii), ((k * 4) + kk)],
]
)
T.writes([B[((i * 4) + ii), ((j * 4) + jj)]])
D = T.alloc_buffer([128, 128])
B[((i * 4) + ii), ((j * 4) + jj)] = B[
((i * 4) + ii), ((j * 4) + jj)
] |
+ (
D[((j * 4) + jj), ((k * 4) + kk)]
* C[((i * 4) + ii), ((k * 4) + kk)]
)
@T.prim_func
def match_buffer_func() -> None:
C = T.alloc_buffer((128, 128))
for i in range(128):
with T.block():
vi = T.axis.S(128, i)
C0 = T.match_buffer(C[vi, 0:128], (128))
for j in range(128):
with T.block():
jj = T.axis.S(128, j)
C1 = T.match_buffer(C0[jj], ())
C1[()] = 0
@T.prim_func
def transformed_match_buffer_func() -> None:
for i in range(0, 128):
with T.block():
vi = T.axis.S(128, i)
C = T.alloc_buffer((128, 128))
C0 = T.match_buffer(C[vi, 0:128], (128))
for j in range(128):
with T.block():
jj = T.axis.S(128, j)
C1 = T.match_buffer(C0[jj], ())
C1[()] = 0
@T.prim_func
def opaque_access(a: T.handle, b: T.handle) -> None:
A = T.match_buffer(a, [1024])
B = T.match_buffer(b, [1024])
A_cache = T.alloc_buffer([1024])
for i in T.serial(0, 8):
with T.block():
vi = T.axis.S(8, i)
with T.block():
v = T.axis.S(8, vi)
T.reads([A[(v * 128) : ((v * 128) + 128)]])
T.writes([A_cache[(v * 128) : ((v * 128) + 128)]])
T.evaluate(
T.call_extern(
"test",
A_cache.data,
(v * 128),
128,
A.data,
(v * 128),
128,
dtype="float32",
)
)
for j in T.serial(0, 128):
with T.block():
v = T.axis.S(1024, vi * 128 + j)
T.reads([A_cache[v]])
T.writes([B[v]]) |
B[v] = A_cache[v]
@T.prim_func
def transformed_opaque_access(a: T.handle, b: T.handle) -> None:
A = T.match_buffer(a, [1024])
B = T.match_buffer(b, [1024])
for i in T.serial(0, 8):
with T.block():
vi = T.axis.S(8, i)
T.reads(A[vi * 128 : vi * 128 + 128])
T.writes(B[vi * 128 : vi * 128 + 128])
A_cache = T.alloc_buffer([1024])
with T.block():
v = T.axis.S(8, vi)
T.reads([A[v * 128 : v * 128 + 128]])
T.writes([A_cache[v * 128 : v * 128 + 128]])
T.evaluate(
T.call_extern(
"test", A_cache.data, v * 128, 128, A.data, v * 128, 128, dtype="float32"
)
)
for j in T.serial(0, 128):
with T.block():
v = T.axis.S(1024, vi * 128 + j)
T.reads([A_cache[v]])
T.writes([B[v]])
B[v] = A_cache[v]
def test_elementwise():
_check(element_func, transformed_element_func)
def test_locate_buffer_allocation():
_check(original_func, transformed_func)
def test_match_buffer_allocation():
_check(match_buffer_func, transformed_match_buffer_func)
def test_opaque_access():
_check(opaque_access, transformed_opaque_access)
def test_lower_te():
x = te.placeholder((1,))
y = te.compute((1,), lambda i: x[i] + 2)
s = te.create_schedule(y.op)
orig_mod = tvm.driver.build_module.schedule_to_module(s, [x, y])
mod = tvm.tir.transform.PlanAndUpdateBufferAllocationLocation()(orig_mod)
tvm.ir.assert_structural_equal(
mod, orig_mod
)
def test_loop_carried_dependency():
"""The buffer allocation should be above opaque iter var's loop scopes
such that buffer accesses with loop carried dependencies are covered."""
@T.prim_func
def before(A: T.Buffer[(8, 8, 8), "int32"], B: T.Buffer[(8, 8, 8), "int32"]):
C = T.alloc_buffer([8, 8, 8], dtype="int32 |
")
for i in T.serial(8):
for j in T.serial(8):
for k in T.serial(8):
with T.block("b0"):
vi, vj, vk = T.axis.remap("SSS", [i, j, k])
C[vi, vj, vk] = A[vi, vj, vk] + 1
for k in T.serial(8):
with T.block("b1"):
vi, vk = T.axis.remap("SS", [i, k])
vj = T.axis.opaque(8, j)
B[vi, vj, vk] = C[vi, vj, vk] + T.if_then_else(
0 < vj, C[vi, vj - 1, vk], 0, dtype="int32"
)
@T.prim_func
def after(A: T.Buffer[(8, 8, 8), "int32"], B: T.Buffer[(8, 8, 8), "int32"]) -> None:
for i in T.serial(8):
with T.block():
T.reads(A[i, 0:8, 0:8])
T.writes(B[i, 0:8, 0:8])
C = T.alloc_buffer([8, 8, 8], dtype="int32")
for j in T.serial(8):
for k in T.serial(8):
with T.block("b0"):
vi, vj, vk = T.axis.remap("SSS", [i, j, k])
C[vi, vj, vk] = A[vi, vj, vk] + 1
for k in T.serial(8):
with T.block("b1"):
vi, vk = T.axis.remap("SS", [i, k])
vj = T.axis.opaque(8, j)
B[vi, vj, vk] = C[vi, vj, vk] + T.if_then_else(
0 < vj, C[vi, vj - 1, vk], 0, dtype="int32"
)
_check(before, after)
def test_1D_cascade_op_rolling_buffer():
"""The intermediate buffer must be allocated above rolling buffer's rolling loop,
which is marked as opaque in consumer block's iter mappings."""
@T.prim_func
def before(A: T.Buffer[(4, 16), "int32"], C: T.Buffer[(4, 8), "int32"]):
B = T.alloc_buffer((4, 6), "int32")
for c in T.serial(4):
for i in T.serial(0, 2):
for j in T.serial(0, 6): |
for k in T.serial(3):
with T.block("P1"):
T.where(i < 1 or j >= 2)
cc, vi, vj, vk = T.axis.remap("SSSR", [c, i, j, k])
if vk == 0:
B[cc, T.floormod(vi * 4 + vj, 6)] = 0
B[cc, T.floormod(vi * 4 + vj, 6)] = (
B[cc, T.floormod(vi * 4 + vj, 6)] + A[cc, vi * 4 + vj + vk]
)
for j in T.serial(0, 4):
for k in T.serial(3):
with T.block("P2"):
vi = T.axis.opaque(2, i)
cc, vj, vk = T.axis.remap("SSR", [c, j, k])
if vk == 0:
C[cc, vi * 4 + vj] = 0
C[cc, vi * 4 + vj] = (
C[cc, vi * 4 + vj] + B[cc, T.floormod(vi * 4 + vj + vk, 6)]
)
@T.prim_func
def after(A: T.Buffer[(4, 16), "int32"], C: T.Buffer[(4, 8), "int32"]):
for c in T.serial(4):
with T.block():
T.reads(A[c, 0:12], C[c, 0:8])
T.writes(C[c, 0:8])
B = T.alloc_buffer([4, 6], dtype="int32")
for i in T.serial(2):
for j, k in T.grid(6, 3):
with T.block("P1"):
T.where(i < 1 or j >= 2)
cc, vi, vj, vk = T.axis.remap("SSSR", [c, i, j, k])
if vk == 0:
B[cc, (vi * 4 + vj) % 6] = 0
B[cc, (vi * 4 + vj) % 6] = (
B[cc, (vi * 4 + vj) % 6] + A[cc, vi * 4 + vj + vk]
)
for j, k in T.grid(4, 3):
with T.block("P2"):
vi = T.axis.opaque(2, i)
cc, vj, vk = T |
.axis.remap("SSR", [c, j, k])
if vk == 0:
C[cc, vi * 4 + vj] = 0
C[cc, vi * 4 + vj] = C[cc, vi * 4 + vj] + B[cc, (vi * 4 + vj + vk) % 6]
_check(before, after)
if __name__ == "__main__":
tvm.testing.main() |
import tvm |
import tvm.testing
from tvm |
import te
def test_prim_func_pass():
@tvm.tir.transform.prim_func_pass(opt_level=1)
class TestReplaceFunc:
"""Simple test function to replace one argument to another."""
def __init__(self, new_func):
self.new_func = new_func
def transform_function(self, func, mod, ctx):
return self.new_func
x = te.var("x")
y = te.var("y")
b = tvm.tir.decl_buffer((x,), "float32")
stmt = tvm.tir.LetStmt(x, 10, tvm.tir.Evaluate(x + 1))
func = tvm.tir.PrimFunc([x, y, b], stmt)
new_func = tvm.tir.PrimFunc([x, y, b], tvm.tir.Evaluate(0))
mod = tvm.IRModule({"main": func})
mod = TestReplaceFunc(new_func)(mod)
assert tvm.ir.structural_equal(mod["main"].body, new_func.body)
def test_cow_pass():
def fapply(f):
assert tvm.testing.object_use_count(f) == 1
return f
pidentity = tvm.tir.transform.Apply(fapply)
x = te.var("x")
func = tvm.tir.PrimFunc([x], tvm.tir.Evaluate(x)).with_attr("target_bits", 32)
func_hash = func.__hash__()
mod = tvm.IRModule({"main": func})
del func
mod_hash = mod.__hash__()
mod = tvm.transform.Sequential([pidentity, tvm.tir.transform.NarrowDataType(32)])(mod._move())
assert mod_hash == mod.__hash__()
assert func_hash == mod["main"].__hash__()
if __name__ == "__main__":
test_cow_pass()
test_prim_func_pass() |
import tvm |
import tvm.testing
from tvm |
import te
from tvm.ir.module |
import IRModule
from tvm.script |
import tir as T |
import numpy
default_lwp_test_config = {
"tir.instrument_lwp": True,
"tir.lwp_disable_func_prof": True,
"tir.reset_start_id": True,
}
@T.prim_func
def input1(a: T.handle, b: T.handle, c: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
for i, j in T.grid(8, 8):
for k, l in T.grid(8, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
for k, l in T.grid(8, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2
@T.prim_func
def input2(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
D = T.match_buffer(d, (8, 8, 128), dtype="int32")
for i in T.serial(0, 8):
for j in T.serial(0, 8):
for k, l in T.grid(8, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
for k, l in T.grid(8, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]
for j in T.serial(0, 8):
for k, l in T.grid(8, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2
for k, l in T.grid(8, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l]) |
C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]
@T.prim_func
def input3(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
D = T.match_buffer(d, (8, 8, 128), dtype="int32")
for i in T.serial(0, 8):
for j in T.parallel(0, 8):
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]
for j in T.serial(0, 8):
for k in T.parallel(0, 8):
for l in T.serial(0, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2
for k in T.parallel(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]
@T.prim_func
def test1_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
for i, j in T.grid(8, 8):
T.evaluate(T.start_profile_intrinsic(3, dtype="handle"))
for k, l in T.grid(8, 16):
with T.block("B"): |
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
T.evaluate(T.end_profile_intrinsic(3, dtype="handle"))
T.evaluate(T.start_profile_intrinsic(5, dtype="handle"))
for k, l in T.grid(8, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2
T.evaluate(T.end_profile_intrinsic(5, dtype="handle"))
@T.prim_func
def test2_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
T.evaluate(T.start_profile_intrinsic(1, dtype="handle"))
for i in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(2, dtype="handle"))
for j in T.serial(0, 8):
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2
T.evaluate(T.end_profile_intrinsic(2, dtype="handle"))
T.evaluate(T.end_profile_intrinsic(1, dtype="handle"))
@T.prim_func
def test3_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
T.evaluate(T.start_profile_intrinsic(1, dtype="handle"))
for i in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(2, dtype="handle"))
f |
or j in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(3, dtype="handle"))
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
T.evaluate(T.end_profile_intrinsic(3, dtype="handle"))
T.evaluate(T.start_profile_intrinsic(5, dtype="handle"))
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2
T.evaluate(T.end_profile_intrinsic(5, dtype="handle"))
T.evaluate(T.end_profile_intrinsic(2, dtype="handle"))
T.evaluate(T.end_profile_intrinsic(1, dtype="handle"))
@T.prim_func
def test4_expected_output(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
D = T.match_buffer(d, (8, 8, 128), dtype="int32")
for i in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(2, dtype="handle"))
for j in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(3, dtype="handle"))
for k, l in T.grid(8, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
T.evaluate(T.end_profile_intrinsic(3, dtype="handle"))
T.evaluate(T.start_profile_intrinsic(5, dtype="handle"))
for k, l in T.grid(8, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] |
* D[vi, vj, vk * 16 + vl]
T.evaluate(T.end_profile_intrinsic(5, dtype="handle"))
T.evaluate(T.end_profile_intrinsic(2, dtype="handle"))
T.evaluate(T.start_profile_intrinsic(7, dtype="handle"))
for j in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(8, dtype="handle"))
for k, l in T.grid(8, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2
T.evaluate(T.end_profile_intrinsic(8, dtype="handle"))
T.evaluate(T.start_profile_intrinsic(10, dtype="handle"))
for k, l in T.grid(8, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]
T.evaluate(T.end_profile_intrinsic(10, dtype="handle"))
T.evaluate(T.end_profile_intrinsic(7, dtype="handle"))
@T.prim_func
def test5_expected_output(a: T.handle, b: T.handle, c: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
T.evaluate(T.start_profile_intrinsic(1, dtype="handle"))
for i in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(2, dtype="handle"))
for j in T.serial(0, 8):
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * 2
T.ev |
aluate(T.end_profile_intrinsic(2, dtype="handle"))
T.evaluate(T.end_profile_intrinsic(1, dtype="handle"))
@T.prim_func
def test6_expected_output(a: T.handle, b: T.handle, c: T.handle, d: T.handle) -> None:
A = T.match_buffer(a, (8, 8, 128), dtype="int32")
B = T.match_buffer(b, (8, 8, 128), dtype="int32")
C = T.match_buffer(c, (8, 8, 128), dtype="int32")
D = T.match_buffer(d, (8, 8, 128), dtype="int32")
for i in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(2, dtype="handle"))
for j in T.parallel(0, 8):
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = A[vi, vj, vk * 16 + vl] * 2
for k in T.serial(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
B[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] * D[vi, vj, vk * 16 + vl]
T.evaluate(T.end_profile_intrinsic(2, dtype="handle"))
T.evaluate(T.start_profile_intrinsic(7, dtype="handle"))
for j in T.serial(0, 8):
T.evaluate(T.start_profile_intrinsic(8, dtype="handle"))
for k in T.parallel(0, 8):
for l in T.serial(0, 16):
with T.block("C"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = B[vi, vj, vk * 16 + vl] + 2
T.evaluate(T.end_profile_intrinsic(8, dtype="handle"))
T.evaluate(T.start_profile_intrinsic(10, dtype="handle"))
for k in T.parallel(0, 8):
for l in T.serial(0, 16):
with T.block("B"):
vi, vj, vk, vl = T.axis.remap("SSSS", [i, j, k, l])
C[vi, vj, vk * 16 + vl] = C[vi, vj, vk * 16 + vl] * D[vi, vj, vk |
* 16 + vl]
T.evaluate(T.end_profile_intrinsic(10, dtype="handle"))
T.evaluate(T.end_profile_intrinsic(7, dtype="handle"))
def test1():
with tvm.transform.PassContext(config=default_lwp_test_config):
mod = tvm.IRModule.from_expr(input1)
mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)
tvm.ir.assert_structural_equal(mod["main"], test1_expected_output)
def test2():
test2_config = default_lwp_test_config.copy()
test2_config.update({"tir.lwp_max_depth": 3})
with tvm.transform.PassContext(config=test2_config):
mod = tvm.IRModule.from_expr(input1)
mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)
tvm.ir.assert_structural_equal(mod["main"], test1_expected_output)
def test3():
test3_config = default_lwp_test_config.copy()
test3_config.update({"tir.lwp_max_depth": 3, "tir.instr_siblings": False})
with tvm.transform.PassContext(config=test3_config):
mod = tvm.IRModule.from_expr(input1)
mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)
tvm.ir.assert_structural_equal(mod["main"], test3_expected_output)
def test4():
with tvm.transform.PassContext(config=default_lwp_test_config):
mod = tvm.IRModule.from_expr(input2)
mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)
tvm.ir.assert_structural_equal(mod["main"], test4_expected_output)
def test5():
test5_config = default_lwp_test_config.copy()
test5_config.update(
{"tir.lwp_max_depth": 3, "tir.instr_siblings": False, "tir.lwp_min_height": 2}
)
with tvm.transform.PassContext(config=test5_config):
mod = tvm.IRModule.from_expr(input1)
mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod)
tvm.ir.assert_structural_equal(mod["main"], test5_expected_output)
def test6():
with tvm.transform.PassContext(config=default_lwp_test_config):
mod = tvm.IRModule.from_expr(input3)
mod = tvm.tir.transform.InstrumentProfileIntrinsics()(mod) |
tvm.ir.assert_structural_equal(mod["main"], test6_expected_output)
if __name__ == "__main__":
tvm.testing.main() |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
import tvm.testing
from tvm import TVMError
from tvm.script import tir as T
class BaseBeforeAfter(tvm.testing.CompareBeforeAfter):
@tvm.testing.fixture
def transform(self):
return tvm.tir.transform.RemoveAssume()
class TestRemoveAssume(BaseBeforeAfter):
"""Remove any instance of T.assume"""
def before(A: T.Buffer[1, "int32"]):
T.evaluate(T.assume(A[0] == 5))
A[0] = 10
def expected(A: T.Buffer[1, "int32"]):
A[0] = 10
class TestRemoveAssumeLoop(BaseBeforeAfter):
"""Loops containing only T.assume should be removed"""
def before(A: T.Buffer[16, "int32"]):
for i in T.serial(16):
T.evaluate(T.assume(A[i] == 0))
for i in T.serial(16):
A[i] = 10
def expected(A: T.Buffer[16, "int32"]):
for i in T.serial(16):
A[i] = 10
if __name__ == "__main__":
tvm.testing.main()
|
import tvm
from tvm |
import te
from tvm.script |
import tir as T |
import tvm.testing
def nop():
return tvm.tir.Evaluate(0)
def test_remove_no_op():
i = te.var("i")
j = te.var("j")
k = te.var("k")
m = te.var("m")
n = te.var("n")
dtype = "int64"
Ab = tvm.tir.decl_buffer((n,), dtype)
stmt = tvm.tir.For(
i,
0,
4,
tvm.tir.ForKind.SERIAL,
tvm.tir.For(
j,
0,
n,
tvm.tir.ForKind.SERIAL,
tvm.tir.For(
k,
0,
m,
tvm.tir.ForKind.SERIAL,
tvm.tir.IfThenElse((i * m + j + k < n), tvm.tir.Evaluate(m), tvm.tir.Evaluate(n)),
),
),
)
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt))
ret = tvm.tir.transform.RemoveNoOp()(mod)["main"].body
assert isinstance(ret, tvm.tir.Evaluate)
store = tvm.tir.BufferStore(Ab, tvm.tir.BufferLoad(Ab, [i]) + 1, [i + 1])
stmt2 = tvm.tir.SeqStmt([nop(), tvm.tir.SeqStmt([store, nop()])])
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt2))
ret = tvm.tir.transform.RemoveNoOp()(mod)["main"].body
assert ret == store
stmt3 = tvm.tir.For(i, 0, 0, tvm.tir.ForKind.SERIAL, store)
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([Ab], stmt3))
ret = tvm.tir.transform.RemoveNoOp()(mod)["main"].body
assert isinstance(ret, tvm.tir.Evaluate)
def test_remove_no_op_with_invalid_extent():
@T.prim_func
def main(A: T.Buffer[(16), "int32"], B: T.Buffer[(16), "int32"]) -> None:
for i in T.serial(16):
for j in T.serial(i - 20):
B[i] = A[i] + j
mod = tvm.ir.module.IRModule.from_expr(main)
ret = tvm.tir.transform.RemoveNoOp()(mod)["main"].body
assert isinstance(ret, tvm.tir.Evaluate)
if __name__ == "__main__":
tvm.testing.main() |
import tvm |
import tvm.testing
from tvm.script |
import tir as T
from tvm |
import TVMError |
class BaseBeforeAfter(tvm.testing.CompareBeforeAfter):
@tvm.testing.fixture
def transform(self):
return tvm.tir.transform.RemoveStoreUndef() |
class TestRemoveStoreUndef(BaseBeforeAfter):
"""Remove a store whose value is T.undef()"""
def before(A: T.Buffer[1, "int32"]):
A[0] = T.undef(dtype="int32")
def expected(A: T.Buffer[1, "int32"]):
T.evaluate(0) |
class TestRemoveStoreUndefExpression(BaseBeforeAfter):
"""Expressions containing T.undef() are removed"""
def before(A: T.Buffer[1, "int32"]):
A[0] = 1 + T.undef(dtype="int32")
def expected(A: T.Buffer[1, "int32"]):
T.evaluate(0) |
class TestKeepOtherCallNodes(BaseBeforeAfter):
"""Expressions containing other CallNodes are not removed"""
def before(A: T.Buffer[1, "int32"], n: T.int32):
A[0] = T.shift_left(n, 1, dtype="int32")
expected = before |
class TestRemoveLetUndef(BaseBeforeAfter):
"""Remove a store whose value is bound to T.undef()"""
def before(A: T.Buffer[1, "int32"]):
val = T.undef(dtype="int32")
A[0] = val
def expected(A: T.Buffer[1, "int32"]):
T.evaluate(0) |
class TestRaiseErrorForUndefAsStoreIndices(BaseBeforeAfter):
"""Use of T.undef() as buffer indices is an error"""
def before(A: T.Buffer[1, "int32"]):
val = T.undef(dtype="int32")
A[val] = 5
expected = TVMError |
class TestRaiseErrorForUndefAsLoadIndices(BaseBeforeAfter):
"""Use of T.undef() as buffer indices is an error
Even though this occurs as part of the BufferStore's value, the
T.undef() may not appear in a buffer's indices.
"""
def before(A: T.Buffer[1, "int32"], B: T.Buffer[1, "int32"]):
B[0] = A[T.undef(dtype="int32")]
expected = TVMError
if __name__ == "__main__":
tvm.testing.main() |
import sys |
import tvm
from tvm.ir.module |
import IRModule
from tvm.script |
import tir as T
from tvm.tir.function |
import PrimFunc
def _check(before, expect):
if isinstance(before, PrimFunc):
before = IRModule({"main": before})
if isinstance(expect, PrimFunc):
expect = IRModule({"main": expect})
mod = tvm.tir.transform.RemoveWeightLayoutRewriteBlock()(before)
tvm.ir.assert_structural_equal(mod, expect)
def test_matmul():
@T.prim_func
def before(
A: T.Buffer[(16, 16), "float32"],
B: T.Buffer[(16, 16), "float32"],
C: T.Buffer[(16, 16), "float32"],
) -> None:
T.func_attr({"layout_free_buffers": [1]})
B_ = T.alloc_buffer([16, 4, 4], dtype="float32")
for i0_o, i1_o in T.grid(16, 16):
with T.block("layout_rewrite"):
i0, i1 = T.axis.remap("SS", [i0_o, i1_o])
T.reads(B[i0, i1])
T.writes(B_[i1, i0
T.block_attr({"meta_schedule.layout_rewrite_preproc": True})
B_[i1, i0
for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):
with T.block("matmul"):
vi = T.axis.spatial(16, i0 * 4 + i1)
vj = T.axis.spatial(16, j)
vk = T.axis.reduce(16, k0 * 4 + k1)
T.reads(A[vi, vk], B_[vj, vk
T.writes(C[vi, vj])
with T.init():
C[vi, vj] = T.float32(0)
C[vi, vj] = C[vi, vj] + A[vi, vk] * B_[vj, vk
@T.prim_func
def after(
A: T.Buffer[(16, 16), "float32"],
B: T.Buffer[(16, 4, 4), "float32"],
C: T.Buffer[(16, 16), "float32"],
) -> None:
T.func_attr({"layout_free_buffers": [1]})
for i0_o, i1_o in T.grid(16, 16):
with T.block("layout_rewrite"):
i0, i1 = T.axis.remap("SS", [i0_o, i1_o])
T.reads()
T.writes()
T.block_attr({"meta_schedule.layout_rewrite_preproc": True})
T.evaluate(0)
for i0, j, k0, i1, k1 in T.grid(4, 16, 4, 4, 4):
with T.block("matmul"): |
vi = T.axis.spatial(16, i0 * 4 + i1)
vj = T.axis.spatial(16, j)
vk = T.axis.reduce(16, k0 * 4 + k1)
T.reads(A[vi, vk], B[vj, vk
T.writes(C[vi, vj])
with T.init():
C[vi, vj] = T.float32(0)
C[vi, vj] = C[vi, vj] + A[vi, vk] * B[vj, vk
_check(before, after)
if __name__ == "__main__":
test_matmul() |
import tvm |
import tvm.testing
from tvm.script |
import tir as T
@tvm.script.ir_module
class Before:
@T.prim_func
def main(inputs: T.Buffer[(8192,), "float32"], weight: T.Buffer[(2097152,), "float32"], conv2d_transpose_nhwc: T.Buffer[(16384,), "float32"]) -> None:
T.func_attr({"global_symbol": "main", "tir.noalias": True})
T.preflattened_buffer(inputs, [1, 4, 4, 512], dtype="float32", data=inputs.data)
T.preflattened_buffer(weight, [4, 4, 512, 256], dtype="float32", data=weight.data)
T.preflattened_buffer(conv2d_transpose_nhwc, [1, 8, 8, 256], dtype="float32", data=conv2d_transpose_nhwc.data)
threadIdx_x = T.env_thread("threadIdx.x")
blockIdx_x = T.env_thread("blockIdx.x")
T.launch_thread(blockIdx_x, 64)
conv2d_transpose_nhwc_local = T.decl_buffer([8], "float32", scope="local")
PadInput_shared = T.decl_buffer([768], "float32", scope="shared")
weight_shared = T.decl_buffer([4096], "float32", scope="shared")
T.launch_thread(threadIdx_x, 32)
for i2_3_init, i1_4_init, i2_4_init in T.grid(2, 2, 2):
conv2d_transpose_nhwc_local[i1_4_init * 4 + i2_3_init * 2 + i2_4_init] = T.float32(0)
for i6_0 in T.serial(16):
for ax0_ax1_ax2_ax3_fused_0 in T.serial(24):
PadInput_shared[ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x] = T.if_then_else(128 <= ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x and ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x < 640 and 1 <= blockIdx_x
for ax0_ax1_ax2_ax3_fused_0 in T.serial(32):
weight_shared[T.ramp(ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4, 1, 4)] = weight[T.ramp((ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4)
for i6_1, i2_3, i4_2, i5_2, i6_2, i1_4, i2_4 in T.grid(4, 2, 4, 4, 8, 2, 2):
conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] = conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] + T.if_then_else((i1_4 + i4_2) % 2 == 0 and (i2_4 + i5_2) % 2 == 0, PadInput_shared[threadIdx_x
for ax |
1, ax2 in T.grid(2, 4):
conv2d_transpose_nhwc[threadIdx_x
@tvm.script.ir_module
class After:
@T.prim_func
def main(inputs: T.Buffer[(8192,), "float32"], weight: T.Buffer[(2097152,), "float32"], conv2d_transpose_nhwc: T.Buffer[(16384,), "float32"]) -> None:
T.func_attr({"global_symbol": "main", "tir.noalias": True})
T.preflattened_buffer(inputs, [1, 4, 4, 512], dtype="float32", data=inputs.data)
T.preflattened_buffer(weight, [4, 4, 512, 256], dtype="float32", data=weight.data)
T.preflattened_buffer(conv2d_transpose_nhwc, [1, 8, 8, 256], dtype="float32", data=conv2d_transpose_nhwc.data)
threadIdx_x = T.env_thread("threadIdx.x")
blockIdx_x = T.env_thread("blockIdx.x")
T.launch_thread(blockIdx_x, 64)
conv2d_transpose_nhwc_local = T.decl_buffer([8], "float32", scope="local")
PadInput_shared = T.decl_buffer([768], "float32", scope="shared")
weight_shared = T.decl_buffer([4096], "float32", scope="shared")
T.launch_thread(threadIdx_x, 32)
for i2_3_init, i1_4_init, i2_4_init in T.grid(2, 2, 2):
conv2d_transpose_nhwc_local[i1_4_init * 4 + i2_3_init * 2 + i2_4_init] = T.float32(0)
for i6_0 in T.serial(16):
for ax0_ax1_ax2_ax3_fused_0 in T.serial(24):
PadInput_shared[ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x] = T.if_then_else(1 <= (ax0_ax1_ax2_ax3_fused_0 + threadIdx_x
for ax0_ax1_ax2_ax3_fused_0 in T.serial(32):
weight_shared[T.ramp(ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4, 1, 4)] = weight[T.ramp((ax0_ax1_ax2_ax3_fused_0 + threadIdx_x * 4
for i6_1, i2_3, i4_2, i5_2, i6_2, i1_4, i2_4 in T.grid(4, 2, 4, 4, 8, 2, 2):
conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] = conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] + T.if_then_else((i1_4 + i4_2) % 2 == 0 and (i2_4 + i5_2) % 2 == 0, PadInput_shared[threadIdx_x
for ax1, ax2 in T.grid(2, 4): |
conv2d_transpose_nhwc[threadIdx_x
@tvm.script.ir_module
class After_simplified:
@T.prim_func
def main(inputs: T.Buffer[(8192,), "float32"], weight: T.Buffer[(2097152,), "float32"], conv2d_transpose_nhwc: T.Buffer[(16384,), "float32"]) -> None:
T.func_attr({"global_symbol": "main", "tir.noalias": True})
threadIdx_x = T.env_thread("threadIdx.x")
blockIdx_x = T.env_thread("blockIdx.x")
T.preflattened_buffer(inputs, [1, 4, 4, 512], dtype="float32", data=inputs.data)
T.preflattened_buffer(weight, [4, 4, 512, 256], dtype="float32", data=weight.data)
T.preflattened_buffer(conv2d_transpose_nhwc, [1, 8, 8, 256], dtype="float32", data=conv2d_transpose_nhwc.data)
T.launch_thread(blockIdx_x, 64)
conv2d_transpose_nhwc_local = T.decl_buffer([8], "float32", scope="local")
PadInput_shared = T.decl_buffer([768], "float32", scope="shared")
weight_shared = T.decl_buffer([4096], "float32", scope="shared")
T.launch_thread(threadIdx_x, 32)
for i2_3_init, i1_4_init, i2_4_init in T.grid(2, 2, 2):
conv2d_transpose_nhwc_local[i1_4_init * 4 + i2_3_init * 2 + i2_4_init] = T.float32(0)
for i6_0 in T.serial(16):
for ax0_ax1_ax2_ax3_fused_0 in T.serial(24):
PadInput_shared[ax0_ax1_ax2_ax3_fused_0 * 32 + threadIdx_x] = T.if_then_else(4 <= ax0_ax1_ax2_ax3_fused_0 and ax0_ax1_ax2_ax3_fused_0 < 20 and 1 <= blockIdx_x
for ax0_ax1_ax2_ax3_fused_0 in T.serial(32):
weight_shared[T.ramp(ax0_ax1_ax2_ax3_fused_0 * 128 + threadIdx_x * 4, 1, 4)] = weight[T.ramp(ax0_ax1_ax2_ax3_fused_0
for i6_1, i2_3, i4_2, i5_2, i6_2, i1_4, i2_4 in T.grid(4, 2, 4, 4, 8, 2, 2):
conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] = conv2d_transpose_nhwc_local[i1_4 * 4 + i2_3 * 2 + i2_4] + T.if_then_else((i1_4 + i4_2) % 2 == 0 and (i2_4 + i5_2) % 2 == 0, PadInput_shared[threadIdx_x
for ax1, ax2 in T.grid(2, 4):
co |
nv2d_transpose_nhwc[threadIdx_x
def test_renormalize_split_pattern():
after = tvm.tir.transform.RenormalizeSplitPattern()(Before)
tvm.ir.assert_structural_equal(after, After)
after = tvm.tir.transform.Simplify()(after)
tvm.ir.assert_structural_equal(after, After_simplified)
@T.prim_func
def impossible_equality(n: T.int32):
if 2 == 0:
if n
T.evaluate(0)
@T.prim_func
def impossible_inequality(n: T.int32):
if -1 < -2:
if n
T.evaluate(0)
integer_condition = tvm.testing.parameter(
impossible_equality,
impossible_inequality,
)
def test_analyze_inside_integer_conditional(integer_condition):
"""Avoid crash occurring in ConstIntBoundAnalyzer.
Crash occurred when simplifying some expressions with provably
false integer expressions. If the expressions were renormalized
before calling Simplify, conditional statements could assign a
range of possible values to integers, as if they were variables.
This would result in divide by zero throwing an exception,
followed by a second exception during stack unwinding causing the
program to crash.
"""
transform = tvm.tir.transform.RenormalizeSplitPattern()
mod = tvm.IRModule.from_expr(integer_condition)
transform(mod)
if __name__ == "__main__":
tvm.testing.main() |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_rewrite_Select():
ib = tvm.tir.ir_builder.create()
A = ib.allocate("float32", 100, name="A", scope="global")
i = te.var("i")
y = tvm.tir.Select(i > 1, A[i - 1], 1.0)
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i], tvm.tir.Evaluate(y)))
yy = tvm.tir.transform.RewriteUnsafeSelect()(mod)["main"].body.value
z = tvm.tir.Select(tvm.tir.Select(i > 1, A[i - 1], 1.0) > 0.0, A[i], 0.1)
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i], tvm.tir.Evaluate(z)))
zz = tvm.tir.transform.RewriteUnsafeSelect()(mod)["main"].body.value
a = tvm.tir.Select(tvm.tir.floordiv(i, 4) > 10, y, z)
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([i], tvm.tir.Evaluate(a)))
aa = tvm.tir.transform.RewriteUnsafeSelect()(mod)["main"].body.value
builtin_if_then_else = tvm.ir.Op.get("tir.if_then_else")
assert yy.op.same_as(builtin_if_then_else)
assert yy.op.same_as(builtin_if_then_else)
assert isinstance(aa, tvm.tir.Select)
if __name__ == "__main__":
test_rewrite_Select()
|
import tvm |
import tvm.testing
from tvm |
import te
from tvm.script |
import tir as T
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.BufferStore)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.BufferStore)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x" |
)
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt) |
class BaseBeforeAfter(tvm.testing.CompareBeforeAfter):
transitively_prove_inequalities = False
convert_boolean_to_and_of_ors = False
apply_constraints_to_boolean_branches = False
def transform(self):
def inner(mod):
config = {
"tir.Simplify": {
"transitively_prove_inequalities": self.transitively_prove_inequalities,
"convert_boolean_to_and_of_ors": self.convert_boolean_to_and_of_ors,
"apply_constraints_to_boolean_branches": self.apply_constraints_to_boolean_branches,
}
}
with tvm.transform.PassContext(config=config):
mod = tvm.tir.transform.Simplify()(mod)
return mod
return inner |
class TestLoadStoreNoop(BaseBeforeAfter):
"""Store of a value that was just read from the same location is a no-op."""
def before(A: T.Buffer[(1,), "float32"]):
A[0] = A[0]
def expected(A: T.Buffer[(1,), "float32"]):
T.evaluate(0) |
class TestLoadStoreNoopAfterSimplify(BaseBeforeAfter):
"""As test_load_store_noop, but requiring simplification to identify.
Previously, a bug caused the self-assignment of a buffer to
checked based on the pre-simplification assignment, not the
post-simplification. This test is to identify any similar
regression.
"""
def before(A: T.Buffer[(1,), "float32"]):
A[0] = A[0] + (5.0 - 5.0)
def expected(A: T.Buffer[(1,), "float32"]):
T.evaluate(0) |
class TestNestedCondition(BaseBeforeAfter):
"""Nested IfThenElse with the same condition can be simplified.
Requires const_int_bound to narrow scope of i within the
conditional, or for rewrite_simplify to recognize the literal
constraint.
"""
def before(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
if i == 5:
A[i] = 0.0
def expected(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
A[i] = 0.0 |
class TestNestedProvableCondition(BaseBeforeAfter):
"""Simplify inner conditional using constraint from outer.
Requires const_int_bound to narrow scope of i within the
conditional.
"""
def before(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
if i < 7:
A[i] = 0.0
def expected(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
A[i] = 0.0 |
class TestNestedVarCondition(BaseBeforeAfter):
"""Simplify inner conditional using constraint from outer.
Requires for rewrite_simplify to recognize the repeated
constraint.
"""
def before(A: T.Buffer[(16,), "float32"], n: T.int32):
for i in T.serial(16):
if i == n:
if i == n:
A[i] = 0.0
def expected(A: T.Buffer[(16,), "float32"], n: T.int32):
for i in T.serial(16):
if i == n:
A[i] = 0.0 |
class TestAlteredBufferContents(BaseBeforeAfter):
"""No simplification of data-dependent conditionals.
A literal constraint must not be propagated if the values
referenced may change. TIR requires single assignment of
variables, so Var objects may be assumed constant, but BufferLoad
may not.
"""
def before(A: T.Buffer[(1,), "int32"], n: T.int32):
if A[0] == n:
A[0] = A[0] + 1
if A[0] == n:
A[0] = 0
expected = before |
class TestNegationOfCondition(BaseBeforeAfter):
"""Use negation of outer condition to simplify innner.
Within the body of an if statement, the negation of the
condition is known to be false.
"""
def before(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i == 5:
if i != 5:
A[i] = 0
else:
A[i] = 1
def expected(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i == 5:
A[i] = 1 |
class TestNegationOfNotEqual(BaseBeforeAfter):
"""As TestNegationOfVarCondition, but with a != outer condition.
Because ConstIntBoundAnalyzer only tracks the min and max allowed
values, the outer i!=5 condition does provide a constraint on the
bounds. This test relies on RewriteSimplifier to recognize
``i==5`` as the negation of a literal constraint.
"""
def before(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i != 5:
if i == 5:
A[i] = 0
else:
A[i] = 1
def expected(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i != 5:
A[i] = 1 |
class TestNegationOfVarCondition(BaseBeforeAfter):
"""As TestNegationOfVarCondition, but with a dynamic condition.
This simplification cannot be done with ConstIntBoundAnalyzer, and
must rely on RewriteSimplifier recognizing the repeated literal.
"""
def before(A: T.Buffer[(16,), "int32"], n: T.int32):
for i in T.serial(16):
if i == n:
if i != n:
A[i] = 0
else:
A[i] = 1
def expected(A: T.Buffer[(16,), "int32"], n: T.int32):
for i in T.serial(16):
if i == n:
A[i] = 1 |
class TestLiteralConstraintSplitBooleanAnd(BaseBeforeAfter):
"""Split a boolean AND into independent constraints
A single if condition may impose multiple literal constraints.
Each constraint that is ANDed together to form the condition
should be treated as an independent constraint. The use of n in
the condition is to ensure we exercise RewriteSimplifier.
"""
def before(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n and j == n:
if i == n:
A[i, j] = 0
def expected(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n and j == n:
A[i, j] = 0 |
class TestLiteralConstraintSplitBooleanOr(BaseBeforeAfter):
"""Split a boolean OR into independent constraints
Similar to TestLiteralConstraintSplitBooleanAnd, but splitting a
boolean OR into independent conditions. This uses the
simplification that ``!(x || y) == !x && !y``.
The use of ``n`` in the condition is to ensure we exercise
RewriteSimplifier.
"""
def before(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n or j == n:
A[i, j] = 0
else:
if i == n:
A[i, j] = 1
else:
A[i, j] = 2
def expected(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n or j == n:
A[i, j] = 0
else:
A[i, j] = 2 |
class TestProveConditionUsingLet(BaseBeforeAfter):
"""Simplify conditions using non-inlined let bindings
Not all let bindings are inlined when they occur in later
expressions. However, even if they are not inlined, they may be
used to prove the value of a condition.
"""
@T.prim_func
def before(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if condition or i >= 3:
A[i] = condition
@T.prim_func
def expected(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
A[i] = condition |
class TestProveLetCondition(BaseBeforeAfter):
"""Simplify conditions using non-inlined let bindings
Not all let bindings are inlined when they occur in later
expressions. However, even if they are not inlined, they may be
used to prove the value of a condition.
"""
@T.prim_func
def before(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if i < 3:
if condition:
A[i] = condition
@T.prim_func
def expected(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if i < 3:
A[i] = condition |
class TestProveRepeatedLetCondition(BaseBeforeAfter):
"""Simplify conditions using non-inlined let bindings
A variable may be used as a literal constraint, and be recognized
as being True within the context of the constraint.
"""
@T.prim_func
def before(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if condition:
if condition:
A[i] = condition
@T.prim_func
def expected(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if condition:
A[i] = True |
class TestIfThenElseExpr(BaseBeforeAfter):
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if i < 12:
A[i] = T.if_then_else(i < 12, 1.0, 2.0, dtype="float32")
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if i < 12:
A[i] = 1.0 |
class TestCeilLog2Int(BaseBeforeAfter):
"""Simplify expressions resulting from topi.math.ceil_log2"""
@T.prim_func
def before(A: T.Buffer[1, "int32"]):
A[0] = T.cast(
T.ceil(T.log2(T.cast(14, "float64"), dtype="float64"), dtype="float64"), dtype="int32"
)
@T.prim_func
def expected(A: T.Buffer[1, "int32"]):
A[0] = 4 |
class TestLeftCeilLog2LowerBound(BaseBeforeAfter):
"""Integer bounds are propagated through topi.math.ceil_log2"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
x = T.cast(
T.ceil(T.log2(T.cast(i + 1024 + 1, "float64"), dtype="float64"), dtype="float64"),
dtype="int32",
)
if x == 11:
A[i] = 0.0
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
A[i] = 0.0 |
class TestLeftShiftLowerBound(BaseBeforeAfter):
"""Integer bounds are propagated through left shift
min(1 << i) = 1 << min(i)
= 1 << 0
= 1
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if T.shift_left(1, i, dtype="int32") >= 1:
A[i] = 0.0
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
A[i] = 0.0 |
class TestLeftShiftUpperBound(BaseBeforeAfter):
"""Integer bounds are propagated through left shift
max(31 << i) = 31 << max(i)
= 31 << 15
= 1015808
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if T.shift_left(31, i, dtype="int32") <= 1015808:
A[i] = 0.0
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
A[i] = 0.0 |
class TestLeftShiftOfNegativeValue(BaseBeforeAfter):
"""No const int bounds of left shift of negative value.
This is target dependent, and does not currently have a specified
behavior in TIR. For example, in CodeGenC, this generates C code
with undefined behavior.
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if -64 <= T.shift_left(-i, 4, dtype="int32"):
A[i] = 0.0
expected = before |
class TestLeftShiftByNegativeValue(BaseBeforeAfter):
"""No const int bounds of left shift by negative bit count.
This is target dependent, and does not currently have a specified
behavior in TIR. For example, in CodeGenC, this generates C code
with undefined behavior.
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if T.shift_left(16, -i, dtype="int32") <= 16:
A[i] = 0.0
expected = before |
class TestRemoveTransitivelyProvableCondition(BaseBeforeAfter):
"""Remove comparisons that may be proven using multiple others
For example, the `0 < i` and `i <= j` conditions can be used to prove
that `0 < j`.
"""
transitively_prove_inequalities = True
i, j, k = [tvm.tir.Var(name, "int32") for name in "ijk"]
zero = tvm.tir.IntImm("int32", 0)
test_case = tvm.testing.parameter(
(tvm.tir.all(zero < i, i <= j), zero < j, True),
(tvm.tir.all(i < j, j < k), i < k, True),
(tvm.tir.all(i < j, j == k), i < k, True),
(tvm.tir.all(i < j, j <= k), i < k, True),
(tvm.tir.all(i < j, j > k), i < k, False),
(tvm.tir.all(i < j, j >= k), i < k, False),
(tvm.tir.all(i < j, j != k), i < k, False),
(tvm.tir.all(i <= j, j < k), i < k, True),
(tvm.tir.all(i <= j, j == k), i == k, False),
(tvm.tir.all(i <= j, j == k), i <= k, True),
(tvm.tir.all(i <= j, j <= k), i <= k, True),
(tvm.tir.all(i <= j, j <= k), i < k, False),
(tvm.tir.all(i <= j, j > k), i < k, False),
(tvm.tir.all(i <= j, j >= k), i < k, False),
(tvm.tir.all(i <= j, j != k), i < k, False),
(tvm.tir.all(i > j, j > k), i > k, True),
(tvm.tir.all(i > j, j == k), i > k, True),
(tvm.tir.all(i > j, j >= k), i > k, True),
(tvm.tir.all(i > j, j < k), i > k, False),
(tvm.tir.all(i > j, j <= k), i > k, False),
(tvm.tir.all(i > j, j != k), i > k, False),
(tvm.tir.all(i >= j, j > k), i > k, True),
(tvm.tir.all(i >= j, j == k), i == k, False),
(tvm.tir.all(i >= j, j == k), i >= k, True),
(tvm.tir.all(i >= j, j >= k), i >= k, True),
(tvm.tir.all(i >= j, j >= k), i > k, False),
(tvm.tir.all(i >= j, j < k), i > k, False),
(tvm.tir.all(i >= j, j <= k), i > k, False),
(tvm.tir.all(i >= j, j != k), i > k, False),
(tvm.tir.all(i == j, j != k), i != k, True),
(tvm.tir.al |
l(i == j, j < k), i != k, True),
(tvm.tir.all(i == j, j > k), i != k, True),
(tvm.tir.all(i == j, j != k), i < k, False),
(tvm.tir.all(i == j, j != k), i > k, False),
(tvm.tir.all(i <= j - 1, j < k), i < k, True),
(tvm.tir.all(i <= j - 1, j == k), i < k, True),
(tvm.tir.all(i <= j - 1, j <= k), i < k, True),
(tvm.tir.all(i <= j - 1, j > k), i < k, False),
(tvm.tir.all(i <= j - 1, j >= k), i < k, False),
(tvm.tir.all(i <= j - 1, j != k), i < k, False),
(tvm.tir.all(i <= j + 5, j <= k + 7), i <= k + 12, True),
(tvm.tir.all(i <= j + 5, j <= k + 7), i <= k + 11, False),
(tvm.tir.all(i < j + 5, j < k + 7), i < k + 11, True),
(tvm.tir.all(i < j + 5, j < k + 7), i < k + 10, False),
)
@tvm.testing.fixture
def before(self, test_case):
priors, postulate, _ = test_case
@T.prim_func
def func(A: T.Buffer[1, "bool"]):
if priors:
A[0] = postulate
return func
@tvm.testing.fixture
def expected(self, test_case):
priors, postulate, provable = test_case
analyzer = tvm.arith.Analyzer()
priors = analyzer.canonical_simplify(priors)
if provable:
@T.prim_func
def func(A: T.Buffer[1, "bool"]):
if priors:
A[0] = True
return func
else:
postulate = analyzer.canonical_simplify(postulate)
@T.prim_func
def func(A: T.Buffer[1, "bool"]):
if priors:
A[0] = postulate
return func |
class TestSuppressTransitivelyProvableCondition(BaseBeforeAfter):
transitively_prove_inequalities = False
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
if i < j and j < k:
A[0] = i < k
expected = before |
class TestRewriteAsAndOfOrs(BaseBeforeAfter):
"""If enabled, rewrite boolean expressions into AND of OR"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[3, "bool"]):
T.evaluate(A[0] or (A[1] and A[2]))
def expected(A: T.Buffer[3, "bool"]):
T.evaluate((A[0] or A[1]) and (A[0] or A[2])) |
class TestSuppressRewriteAsAndOfOrs(BaseBeforeAfter):
"""Only rewrite into AND of OR when allowed"""
convert_boolean_to_and_of_ors = False
def before(A: T.Buffer[3, "bool"]):
T.evaluate(A[0] or (A[1] and A[2]))
expected = before |
class TestRewriteAsAndOfOrsWithTopLevelAnd(BaseBeforeAfter):
"""The expression being rewritten may start with an AND
Like TestRewriteAsAndOfOrs, but with an AndNode as the outermost
booelan operator. Even though it is primarily OR nodes that are
being rewritten, the call to SimplifyAsAndOfOrs should apply to
the outermost AndNode or OrNode in order to enable better
simplification.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[4, "bool"]):
T.evaluate((A[0] or A[1]) and (A[1] or (A[0] and A[2] and A[3])))
def expected(A: T.Buffer[4, "bool"]):
T.evaluate((A[0] or A[1]) and (A[1] or A[2]) and (A[1] or A[3])) |
class TestRewriteAsAndOfOrsWithSimplificationBetweenGroups(BaseBeforeAfter):
"""Apply rewrite rules between OR groups that differ by a single element
The expression `(k==20 and k!=30)` could be rewritten into `(k==20)`.
However, by default these two terms must appear as part of an explict part
of the simplified expression. The AndOfOr simplification checks for
rewrite patterns of the form `(A or B) and (A or C)`, where `(B and C)` can
simplify to a single expression `D`. These can be rewritten to `(A or D)`.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i == 0 or j == 10 or k == 20) and (i == 0 or j == 10 or k != 30)
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = i == 0 or j == 10 or k == 20 |
class TestRewriteAsAndOfOrsWithSimplificationBetweenReorderedGroups(BaseBeforeAfter):
"""Rewrite rules between OR groups do not depend on order
Like TestRewriteAsAndOfOrsWithSimplificationBetweenGroups, but the groups
are ordered differently. If this removes a group entirely, the result is
ordered according to the first group in the expression.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i == 0 or j == 10 or k == 20) and (j == 10 or k != 30 or i == 0)
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = i == 0 or j == 10 or k == 20 |
class TestRewriteAsAndOfOrUsingSimplificationAcrossAnd(BaseBeforeAfter):
"""Apply AndNode rewrites to non-adjacent expressions
The RewriteSimplifier rules only check for simplifications between
left/right branches of an And/Or node. Simplifications that would |
require
rearranging components in a chain of And/Or nodes are not performed.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (k == 20) and ((i == 0 or j == 10) and (k != 30))
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (k == 20) and (i == 0 or j == 10) |
class TestRewriteAsAndOfOrUsingSimplificationWithinOr(BaseBeforeAfter):
"""Rewrite rules between OR groups do not depend on order
The RewriteSimplifier rules only check for simplifications between
left/right branches of an And/Or node. Simplifications that would |
require
rearranging components in a chain of And/Or nodes are not performed.
This test validates that `(i == 20) or (i != 30)` can be rewritten to
`(i != 30)`, even when there's an intervening clause between the
clauses being simplified.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i == 20) or (j == 0) or (i != 30)
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i != 30) or (j == 0) |
class TestConditionalFloorMod(BaseBeforeAfter):
"""A regression test for negative floormod denominator
Previously, simplifying this function could throw an error. First, the
`canonical_simplify` would rewrite `floormod(0-i,2)` to the equivalent
`floormod(i,-2)`. Then, the rewrite_simplifier would enter a
constrained context in which `floormod(i,-2)==1`. Passing this
expression to `ModularSet::EnterConstraint`, which previously did not
support a negative value for the second argument, threw an error.
The analogous failure mode never occurred for `truncmod`, because
`truncmod(0-i,2)` would be canonicalized to `truncmod(i, -2) * -1`, and
the pattern matching in `ModularSet` didn't recognize the constant
factor.
This failure mode was resolved by supporting negative arguments in
`ModularSet`, using the same sign convention as is used by
`canonical_simplify`.
"""
def before(A: T.Buffer[1, "bool"], i: T.int32):
if T.floormod(0 - i, 2) == 0:
A[0] = T.floormod(i, 2) == 0
def expected(A: T.Buffer[1, "bool"], i: T.int32):
if T.floormod(i, -2) == 0:
A[0] = True |
class TestSimplifyRHSOfBooleanAndUsingLHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts.
In `A and B`, the result of `B` only matters when `A` is
true, and can be simplified under that context. This test
simplifies `n < 10` under the assumption that `n < 5`.
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5 and n < 10
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5 |
class TestSimplifyLHSOfBooleanAndUsingRHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts for their arguments.
Like TestSimplifyRHSOfBooleanAndUsingLHS, but using the RHS to
simplify the LHS.
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10 and n < 5
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5 |
class TestSimplifyRHSOfBooleanOrUsingLHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts.
In `A or B`, the result of `B` only matters when `A` is false, so
`B` can be simplified under the assumption that `A` is false.
This test simplifies `n < 5` under the assumption that `!(n < 10)`
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10 or n < 5
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10 |
class TestSimplifyLHSOfBooleanOrUsingRHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts for their arguments.
Like TestSimplifyRHSOfBooleanOrUsingLHS, but using the RHS to
simplify the LHS.
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5 or n < 10
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.