Skip to content

Commit 4d44344

Browse files
committed
Always enable grad before connecting to autograd
1 parent 1316673 commit 4d44344

3 files changed

Lines changed: 16 additions & 13 deletions

File tree

thunder/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -865,13 +865,14 @@ def fn_(*args, **kwargs) -> Any:
865865
cache_entry, inps, pro_to_epi = get_computation_and_inputs(*args, **kwargs)
866866

867867
result = cache_entry.computation_fn(*inps)
868-
# We must do this before connecting to autograd so that
869-
# grad_fn attribute will be set on the outputs accordingly
870-
pytorch.set_grad_enabled(cd.is_grad_enabled)
871868
result = maybe_connect_to_autograd(cache_entry, result)
872869
result = call_epilogue(cache_entry, result, pro_to_epi)
873870

874871
cs.last_computation = cache_entry.computation_fn
872+
873+
# Reflect the state of is_grad_enabled, as its changes have been recorded only inside Thunder
874+
pytorch.set_grad_enabled(cd.is_grad_enabled)
875+
875876
return result
876877

877878
if isinstance(fn, pytorch.nn.Module):

thunder/core/symbol.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,7 @@ def __call__(self, *args, **kwargs):
329329
if cd is not None and not cd.is_grad_enabled:
330330
flat_args, _ = tree_flatten((args, kwargs))
331331
flat_arg_ids = {id(arg) for arg in flat_args}
332+
332333
# If grad is disabled using `torch.no_grad` or `torch._C._set_grad_enabled(False)`,
333334
# tag the results with `DETACHED_AUTOGRAD_GRAPH` which makes this Symbol a constant for
334335
# vjp transform (applied later).

thunder/executors/torch_autograd.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -168,16 +168,17 @@ def connect_to_autograd(
168168
disable_split_autograd, lambda: "is_differentiable_outputs is not supported when split_autograd is enabled"
169169
)
170170

171-
dummy_res = ThunderFunction.apply(
172-
return_none_instead_of_grads,
173-
backward_fn,
174-
side_channel,
175-
saved_tensors,
176-
saved_other,
177-
is_differentiable_outputs,
178-
flat_output,
179-
*flat_args,
180-
)
171+
with torch.enable_grad():
172+
dummy_res = ThunderFunction.apply(
173+
return_none_instead_of_grads,
174+
backward_fn,
175+
side_channel,
176+
saved_tensors,
177+
saved_other,
178+
is_differentiable_outputs,
179+
flat_output,
180+
*flat_args,
181+
)
181182
if side_channel is not None:
182183
# we need to pass the inputs to avoid "leave has moved inside the graph"
183184
# if the function returns an argument as is

0 commit comments

Comments
 (0)