Share Parameter/Buffer Storage When Cloning Split GraphModules to Eliminate Redundant Tensor Copies #2509
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.
Description
Summary
This PR replaces a full copy.deepcopy of the split GraphModule with a lightweight clone that shares Parameter and buffer tensors with the original module. This avoids duplicating model weights during graph splitting and significantly reduces peak memory.
Motivation
copy.deepcopy(split_gm) duplicates every Parameter and registered buffer. For large models this can momentarily double memory usage and trigger OOMs. The splitter only needs a structural snapshot of the module; it does not mutate weights. Sharing tensor storage is therefore safe and much more memory-efficient.
What’s changed
Added _copy_without_tensors(module: nn.Module) -> nn.Module
Uses copy.deepcopy with a pre-populated memo so that all Parameters and registered buffers are reused rather than copied.
Replaced copy.deepcopy(split_gm) with _copy_without_tensors(split_gm) when capturing original_split_gm.
Minor: import itertools (for chain) and improved inline comments.
Implementation notes
The helper clones Python/FX structure while mapping each tensor id in parameters() and buffers() back to the original object:
Behavior of the splitter is unchanged; only memory characteristics improve.