Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[autodiff] Clear all dual fields when exiting context manager #5716

Merged
merged 1 commit into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions python/taichi/ad/_ad.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,11 @@ def shape_flatten(shape):
else:
assert parameters_shape_flatten == len(self.seed)

# Clear gradients
if self.clear_gradients:
# TODO: the clear gradients should be controlled to clear adjoint/dual/adjoint_visited respectively
clear_all_gradients()

# Set seed for each variable
if len(self.seed) == 1:
if len(self.param.shape) == 0:
Expand All @@ -294,11 +299,6 @@ def shape_flatten(shape):
else:
self.param.dual.from_numpy(np.array(self.seed, dtype=np.float32))

# Clear gradients
if self.clear_gradients:
for ls in self.loss:
ls.dual.fill(0)

# Attach the context manager to the runtime
self.runtime.fwd_mode_manager = self

Expand Down
20 changes: 20 additions & 0 deletions tests/python/test_ad_basics_fwd.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,23 @@ def func():

with ti.ad.FwdMode(loss=d, param=c):
func()


@test_utils.test()
def test_clear_all_dual_field():
x = ti.field(float, shape=(), needs_dual=True)
y = ti.field(float, shape=(), needs_dual=True)
loss = ti.field(float, shape=(), needs_dual=True)

x[None] = 2.0
y[None] = 3.0

@ti.kernel
def clear_dual_test():
y[None] = x[None]**2
loss[None] += y[None]

for _ in range(5):
with ti.ad.FwdMode(loss=loss, param=x):
clear_dual_test()
assert y.dual[None] == 4.0