Fix python gc race condition with THPVariable_traverse #4437
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.
Fixes #3883: asserts being triggered in DataParallel for long training regiments like imagenet.
The bug is that a python Function in the computation graph gets garbage collected due to a C++ shared pointer to the C++ Function it wraps changing
use_count()
from 1 to more than 1 during python garbage collection. This happens because the "python state" of Variable changes: theTHPVariable_traverse
method indicates that when the shared pointer'suse_count()
is 1, the python Variable holds a python reference to the python Function, but not whenuse_count() > 1
. See this gist for a more detailed exploration of the diagnosis.The bug could be fixed by treating the shared pointer (a Variable's
grad_fn
) as part of the python state and intelligently grabbing the GIL when necessary. The downside to this approach is the complexity and potential overhead.Alternatively, after talking with @colesbury, we think it might be better to remove the checking of the shared pointer's
use_count()
inTHPVariable_traverse
. This effectively disables reference cycle garbage collection for python Functions.