Skip to content

Commit

Permalink
Fix memory leak in zeroGradients().
Browse files Browse the repository at this point in the history
  • Loading branch information
neutrino committed Sep 29, 2023
1 parent 963332d commit 7d61e5c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,10 @@ public void zeroGradients() {
NDManager systemManager = MxNDManager.getSystemManager();
for (NDArray array : systemManager.getManagedArrays()) {
if (array.hasGradient()) {
array.getGradient().subi(array.getGradient());
// To prevent memory leak we must close gradient after use.
try (NDArray gradient = array.getGradient()) {
gradient.subi(gradient);
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,9 @@ private void backward(NDArray target, NDArray grad, boolean keepGraph, boolean c
public void zeroGradients() {
NDManager systemManager = PtNDManager.getSystemManager();
for (NDArray array : systemManager.getManagedArrays()) {
if (array.hasGradient()) {
array.getGradient().subi(array.getGradient());
// To prevent memory leak we must close gradient after use.
try (NDArray gradient = array.getGradient()) {
gradient.subi(gradient);
}
}
}
Expand Down

0 comments on commit 7d61e5c

Please sign in to comment.