Avoid retaining saved tensors in fused norm custom ops under no_grad#2012
Open
LeSingh1 wants to merge 1 commit into
Open
Avoid retaining saved tensors in fused norm custom ops under no_grad#2012LeSingh1 wants to merge 1 commit into
LeSingh1 wants to merge 1 commit into
Conversation
The custom-op forward path for FusedRMSNorm/FusedLayerNorm registers an autograd setup_context that unconditionally calls save_for_backward. For torch.library custom ops these saved tensors are retained in autograd metadata that is not released after the call returns, so each forward under torch.no_grad() leaks the saved activation and the invvar tensor (two CUDA tensors per call), accumulating linearly in long-running inference (issue NVIDIA#1999). Skip the save_for_backward calls when grad is disabled, since backward can never run in that case. The grad-enabled training path is unchanged. Signed-off-by: LeSingh1 <sshaurya914@gmail.com>
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Problem
FusedRMSNorm(and the sibling fused layer/RMS norm custom ops) leak two CUDA tensors per forward call undertorch.no_grad(), as reported in #1999. On thetorch.library.custom_oppath (PyTorch >= 2.4) thesetup_contextfunctions unconditionally callsave_for_backward; those saved tensors are retained in autograd metadata that is not released after ano_gradforward, leaking the saved activation + invvar each call.Fix
In each affected
setup_context(apex/normalization/fused_layer_norm.py), assign the scalarctxfields first, then return early whentorch.is_grad_enabled()isFalse, skippingsave_for_backward. Backward can never run underno_grad, so nothing is lost, and the grad-enabled training path is unchanged.Testing / verification status
Addresses #1999