forked from taichi-dev/taichi
-
Notifications
You must be signed in to change notification settings - Fork 69
/
test_kernel_templates.py
129 lines (96 loc) · 2.53 KB
/
test_kernel_templates.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import taichi as ti
from tests import test_utils
@test_utils.test()
def test_kernel_template_basic():
x = ti.field(ti.i32)
y = ti.field(ti.f32)
n = 16
ti.root.dense(ti.i, n).place(x, y)
@ti.kernel
def inc(a: ti.template(), b: ti.template()):
for i in a:
a[i] += b
inc(x, 1)
inc(y, 2)
for i in range(n):
assert x[i] == 1
assert y[i] == 2
@ti.kernel
def inc2(z: ti.i32, a: ti.template(), b: ti.i32):
for i in a:
a[i] += b + z
inc2(10, x, 1)
for i in range(n):
assert x[i] == 12
@test_utils.test()
def test_kernel_template_gradient():
x = ti.field(ti.f32)
y = ti.field(ti.f32)
z = ti.field(ti.f32)
loss = ti.field(ti.f32)
ti.root.dense(ti.i, 16).place(x, y, z)
ti.root.place(loss)
ti.root.lazy_grad()
@ti.kernel
def double(a: ti.template(), b: ti.template()):
for i in range(16):
b[i] = a[i] * 2 + 1
@ti.kernel
def compute_loss():
for i in range(16):
ti.atomic_add(loss[None], z[i])
for i in range(16):
x[i] = i
with ti.ad.Tape(loss):
double(x, y)
double(y, z)
compute_loss()
for i in range(16):
assert z[i] == i * 4 + 3
assert x.grad[i] == 4
@test_utils.test()
def test_func_template():
a = [ti.field(dtype=ti.f32) for _ in range(2)]
b = [ti.field(dtype=ti.f32) for _ in range(2)]
for l in range(2):
ti.root.dense(ti.ij, 16).place(a[l], b[l])
@ti.func
def sample(x: ti.template(), l: ti.template(), I):
return x[l][I]
@ti.kernel
def fill(l: ti.template()):
for I in ti.grouped(a[l]):
a[l][I] = l
@ti.kernel
def aTob(l: ti.template()):
for I in ti.grouped(b[l]):
b[l][I] = sample(a, l, I)
for l in range(2):
fill(l)
aTob(l)
for l in range(2):
for i in range(16):
for j in range(16):
assert b[l][i, j] == l
@test_utils.test()
def test_func_template2():
a = ti.field(dtype=ti.f32)
b = ti.field(dtype=ti.f32)
ti.root.dense(ti.ij, 16).place(a, b)
@ti.func
def sample(x: ti.template(), I):
return x[I]
@ti.kernel
def fill():
for I in ti.grouped(a):
a[I] = 1.0
@ti.kernel
def aTob():
for I in ti.grouped(b):
b[I] = sample(a, I)
for l in range(2):
fill()
aTob()
for i in range(16):
for j in range(16):
assert b[i, j] == 1.0