Skip to content

fix(diff/implicit): fix memory leak of OOP APIs #113

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

Merged
merged 11 commits into from
Jan 15, 2023
Prev Previous commit
Next Next commit
fix: detach tensors
  • Loading branch information
XuehaiPan committed Jan 11, 2023
commit 7b3d708b45e2f7630f888a3714567c3ffbd93bcf
3 changes: 2 additions & 1 deletion torchopt/diff/implicit/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ def forward( # type: ignore[override] # pylint: disable=arguments-differ
f'solver_fn should be a torch.Tensor or a tuple of torch.Tensor. '
f'Got {output}'
)
output_detached = tuple(t.data for t in output)

(
args_treespec,
Expand All @@ -300,7 +301,7 @@ def forward( # type: ignore[override] # pylint: disable=arguments-differ
ctx.args_is_tensor_mask = args_is_tensor_mask
ctx.args_non_tensors = args_non_tensors

ctx.save_for_backward(*output, *args_tensors)
ctx.save_for_backward(*output_detached, *args_tensors)
ctx.output_is_tensor = output_is_tensor

return (*output, aux, output_is_tensor, type(output))
Expand Down
12 changes: 11 additions & 1 deletion torchopt/diff/implicit/nn/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,17 @@ def solver_fn(
**kwargs,
) -> Tuple[TupleOfTensors, Any]:
output = cls_solve(self, *input, **kwargs)
flat_optimal_params: TupleOfTensors = tuple(pytree.tree_leaves(params_containers)) # type: ignore[arg-type]

def detach_(t):
requires_grad = t.requires_grad
return t.detach_().requires_grad_(requires_grad)

flat_optimal_params: TupleOfTensors = tuple(
map(
detach_,
pytree.tree_leaves(params_containers), # type: ignore[arg-type]
)
)
return flat_optimal_params, output

# pylint: disable-next=unused-variable
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy