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

fix(optim/meta): torch tensor memory not release due to gradient link #219

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
19 changes: 10 additions & 9 deletions torchopt/optim/meta/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,21 +72,22 @@ def step(self, loss: torch.Tensor) -> None: # pylint: disable=too-many-locals
):
flat_params: TupleOfTensors
flat_params, container_treespec = pytree.tree_flatten_as_tuple(param_container) # type: ignore[arg-type]
if isinstance(state, UninitializedState):
state = self.impl.init(flat_params)
grads = torch.autograd.grad(
loss,
flat_params,
create_graph=True,
allow_unused=True,
)
updates, new_state = self.impl.update(
grads,
state,
params=flat_params,
inplace=False,
)
self.state_groups[i] = new_state
with torch.no_grad():
if isinstance(state, UninitializedState):
state = self.impl.init(flat_params)
updates, new_state = self.impl.update(
grads,
state,
params=flat_params,
inplace=False,
)
self.state_groups[i] = new_state
Comment on lines +84 to +90
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updates can be detached from the graph while new_state should remain in the graph for explicit gradient computation. We need to add a new test for this. cc @JieRen98

flat_new_params = apply_updates(flat_params, updates, inplace=False)
new_params: ModuleTensorContainers = pytree.tree_unflatten( # type: ignore[assignment]
container_treespec,
Expand Down
Loading