-
Notifications
You must be signed in to change notification settings - Fork 661
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
Implements NDScope to automatically close NDArray in the scope #2321
Merged
frankfliu
merged 10 commits into
deepjavalibrary:master
from
enpasos:reference-counting
Jan 26, 2023
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
5677f11
[api] Fixes toDebugString() IllegalStateException if NDArray is closed
frankfliu 4f6ab89
Implements NDScope based on JavaCPP PointerScope
6ae6600
Simplify RCScope implementation
frankfliu 8c5c502
missing NDScope.register
85e3f3d
enhanced test to sport subtle bug on equals method + fix
c0b94ac
problem on unregister: if two NDArrays on different device equals thr…
af04eab
removed unregister from detach
d0530d0
equals solved in NDScope internally - test on instance
35f403b
Update api/src/main/java/ai/djl/ndarray/NDScope.java
enpasos dcf1414
using IdentityHashMap
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
/* | ||
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance | ||
* with the License. A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES | ||
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions | ||
* and limitations under the License. | ||
*/ | ||
package ai.djl.ndarray; | ||
|
||
import java.util.ArrayDeque; | ||
import java.util.Deque; | ||
import java.util.IdentityHashMap; | ||
|
||
/** | ||
* A class that tracks {@link NDResource} objects created in the try-with-resource block and close | ||
* them automatically when out of the block scope. | ||
* | ||
* <p>This class has been derived from {@code org.bytedeco.javacpp.PointerScope} by Samuel Audet | ||
*/ | ||
public class NDScope implements AutoCloseable { | ||
|
||
private static final ThreadLocal<Deque<NDScope>> SCOPE_STACK = | ||
ThreadLocal.withInitial(ArrayDeque::new); | ||
|
||
private IdentityHashMap<NDArray, NDArray> resources; | ||
|
||
/** Constructs a new {@code NDScope} instance. */ | ||
public NDScope() { | ||
resources = new IdentityHashMap<>(); | ||
SCOPE_STACK.get().addLast(this); | ||
} | ||
|
||
/** | ||
* Registers {@link NDArray} object to this scope. | ||
* | ||
* @param array the {@link NDArray} object | ||
*/ | ||
public static void register(NDArray array) { | ||
Deque<NDScope> queue = SCOPE_STACK.get(); | ||
if (queue.isEmpty()) { | ||
return; | ||
} | ||
queue.getLast().resources.put(array, array); | ||
} | ||
|
||
/** | ||
* Unregisters {@link NDArray} object from this scope. | ||
* | ||
* @param array the {@link NDArray} object | ||
*/ | ||
public static void unregister(NDArray array) { | ||
Deque<NDScope> queue = SCOPE_STACK.get(); | ||
if (queue.isEmpty()) { | ||
return; | ||
} | ||
queue.getLast().resources.remove(array); | ||
} | ||
|
||
/** {@inheritDoc} */ | ||
@Override | ||
public void close() { | ||
for (NDArray array : resources.keySet()) { | ||
array.close(); | ||
} | ||
SCOPE_STACK.get().remove(this); | ||
} | ||
|
||
/** | ||
* A method that does nothing. | ||
* | ||
* <p>You may use it if you do not have a better way to suppress the warning of a created but | ||
* not explicitly used scope. | ||
*/ | ||
public void suppressNotUsedWarning() { | ||
// do nothing | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
/* | ||
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance | ||
* with the License. A copy of the License is located at | ||
* | ||
* http://aws.amazon.com/apache2.0/ | ||
* | ||
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES | ||
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions | ||
* and limitations under the License. | ||
*/ | ||
package ai.djl.ndarray; | ||
|
||
import org.testng.Assert; | ||
import org.testng.annotations.Test; | ||
|
||
public class NDScopeTest { | ||
|
||
@Test | ||
@SuppressWarnings("try") | ||
public void testNDScope() { | ||
NDArray detached; | ||
NDArray inside; | ||
NDArray uninvolved; | ||
try (NDManager manager = NDManager.newBaseManager()) { | ||
try (NDScope scope = new NDScope()) { | ||
scope.suppressNotUsedWarning(); | ||
try (NDScope ignore = new NDScope()) { | ||
uninvolved = manager.create(new int[] {1}); | ||
uninvolved.close(); | ||
inside = manager.create(new int[] {1}); | ||
// not tracked by any NDScope, but still managed by NDManager | ||
NDScope.unregister(inside); | ||
} | ||
|
||
detached = manager.create(new int[] {1}); | ||
detached.detach(); // detached from NDManager | ||
NDScope.unregister(detached); // and unregistered from NDScope | ||
} | ||
|
||
Assert.assertFalse(inside.isReleased()); | ||
} | ||
Assert.assertTrue(inside.isReleased()); | ||
Assert.assertFalse(detached.isReleased()); | ||
detached.close(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NDArray.detach()
is called, user want to return the NDArray from the function.Which means user has to call both function in most of time. And we documented that once NDArray is detached, user must manually close it.
So I feel we should unregister from the NDScope when
NDArray.detach()
is called.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like we are abusing
NDArray.detach()
in many internal place (attache()
, they should only detach from NDManager only. Introducing twodetach(boolean)
function seems too much. Requires user to call both should be fine for now.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is your intention to introduce NDScope?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My intention would be: Implement it because you need it to close a memory leak that you cannot solve otherwise. So I would not use NDScope if I did not have to. But if I have a leak - which I unfortunately do - I would put the NDScope where I think no NDArray should leak through - no matter if inside or outside of NDManager and no matter how they are used. And in that case I would not want NDArrays to leak through for whatever reason.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree that if there was a convenient method where the user knew exactly that he/she was also unregistering from NDScope, there should be no problem.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we leave it as it is for this PR?