import taichi as ti
ti.init()
N = 16
x = ti.field(dtype=ti.f32, shape=N, needs_grad=True)
loss = ti.field(dtype=ti.f32, shape=(2), needs_grad=True)
@ti.kernel
def func():
for i in x:
loss[0] += x[i] ** 2
loss[1] += x[i]
for i in range(N):
x[i] = i
# Set the `grad` of the output variables to `1` before calling `func.grad()`.
loss.grad[0] = 1
loss.grad[1] = 1
func()
func.grad()
print(x.grad.shape)
# is it possible to get a 2 * 16 jacobian if func.grad() is only executed once?
import taichi as ti
ti.init()
N = 16
x = ti.field(dtype=ti.f32, shape=N, needs_grad=True)
loss = ti.field(dtype=ti.f32, shape=(2), needs_grad=True)
@ti.kernel
def func():
for i in x:
loss[0] += x[i] ** 2
loss[1] += x[i]
for i in range(N):
x[i] = i
for _ in range(10):
loss.grad[0] = 1
loss.grad[1] = 1
func()
func.grad()
print(x.grad)
#ti.ad.clear_all_gradients()
# if not, grad will be accumulated