example_elementwise_add.py 2.3 KB
Newer Older
1
2
3
import argparse
import itertools
import torch
4
5
6
7
import tilelang
import tilelang.language as T


8
9
10
11
def ref_program(x, y):
    return x + y


12
13
14
15
16
17
18
19
20
def get_configs():
    block_M = [64, 128, 256]
    block_N = [64, 128, 256]
    threads = [64, 128, 256]
    configs = list(itertools.product(block_M, block_N, threads))
    return [{"block_M": bm, "block_N": bn, "threads": th} for bm, bn, th in configs]


@tilelang.autotune(configs=get_configs())
21
@tilelang.jit(out_idx=[-1])
22
def elementwise_add(M, N, block_M, block_N, in_dtype, out_dtype, threads):
23
    @T.prim_func
24
    def elem_add(A: T.Tensor((M, N), in_dtype), B: T.Tensor((M, N), in_dtype), C: T.Tensor((M, N), out_dtype)):
25
        with T.Kernel(T.ceildiv(N, block_N), T.ceildiv(M, block_M), threads=threads) as (bx, by):
26
27
28
29
30
31
32
            A_shared = T.alloc_shared((block_M, block_N), in_dtype)
            B_shared = T.alloc_shared((block_M, block_N), in_dtype)
            C_local = T.alloc_fragment((block_M, block_N), out_dtype)
            C_shared = T.alloc_shared((block_M, block_N), out_dtype)

            T.copy(A[by * block_M, bx * block_N], A_shared)
            T.copy(B[by * block_M, bx * block_N], B_shared)
33
            for local_y, local_x in T.Parallel(block_M, block_N):
34
35
36
                C_local[local_y, local_x] = A_shared[local_y, local_x] + B_shared[local_y, local_x]
            T.copy(C_local, C_shared)
            T.copy(C_shared, C[by * block_M, bx * block_N])
37

38
    return elem_add
39
40


41
def main(M=1024, N=1024, use_autotune=False):
42
43
44
    a = torch.randn(M, N, dtype=torch.float32, device="cuda")
    b = torch.randn(M, N, dtype=torch.float32, device="cuda")

45
46
    if use_autotune:
        kernel = elementwise_add(M, N, in_dtype="float32", out_dtype="float32")
47
48
    else:
        # Default config
49
        config = {"block_M": 32, "block_N": 32, "threads": 128}
50
        kernel = elementwise_add(M, N, **config, in_dtype="float32", out_dtype="float32")
51

52
53
    out = kernel(a, b)
    torch.testing.assert_close(out, ref_program(a, b), rtol=1e-2, atol=1e-2)
54
55
56


if __name__ == "__main__":
57
58
59
60
61
62
    parser = argparse.ArgumentParser()
    parser.add_argument("--m", type=int, default=1024)
    parser.add_argument("--n", type=int, default=1024)
    parser.add_argument("--use_autotune", action="store_true", default=False)
    args, _ = parser.parse_known_args()
    main(args.m, args.n, args.use_autotune)