Uh oh!
There was an error while loading. Please reload this page.
[PyTorch] Fix fuser so it releases tensors properly - #2750
Conversation
Greptile SummaryThis PR fixes a memory leak in
Confidence Score: 5/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant FW as forward()
participant PyTorch as PyTorch Autograd
participant BW as backward()
FW->>FW: prepare_for_saving(*to_save)<br/>→ tensors_to_save, tensor_objects
FW->>PyTorch: save_for_backward(*tensors_to_save)<br/>(cleared automatically by PyTorch)
FW->>PyTorch: func_ctx.tensor_objects = tensor_objects<br/>(NOT cleared automatically)
Note over PyTorch: Forward pass completes.<br/>func_ctx kept alive by PyTorch<br/>until next iteration.
PyTorch->>BW: backward() invoked
BW->>BW: restore_from_saved(func_ctx.tensor_objects,<br/>func_ctx.saved_tensors)
Note over BW: saved_tensors are released<br/>by PyTorch automatically ✅
BW->>BW: func_ctx.tensor_objects = None<br/>(PR fix: manually release ✅)
Note over PyTorch: tensor_objects can now be<br/>garbage-collected immediately,<br/>rather than waiting until<br/>the next training iteration.
Last reviewed commit: 8bbc047 |
ptrendx
commented
Mar 10, 2026
/te-ci pytorch |
ksivaman
commented
Mar 10, 2026
@kainzhong Could you take a look at the failed CI? |
Signed-off-by: Kaining Zhong <kainingz@nvidia.com>
e945732 to
491779cComparekainzhong
commented
Mar 11, 2026
OK I think the mocked |
kainzhong
commented
Mar 11, 2026
/te-ci pytorch |
Uh oh!
There was an error while loading. Please reload this page.
Description
When training llama3 405B we observe OOMs with passing
use_te_op_fuser=Truein Megatron. This is becauseOperationFuserfails to properly release tensors that are saved for backward.Type of change
Changes
Please list the changes introduced in this PR:
In
_OperationFuserAutogradFunction's backward, we useto restore the saved tensor from backward. However, we didn't detach
tensor_objectsfromfunc_ctx, wherefunc_ctxwill not be released until the next iteration due to pytorch's internal mechanism (pytorch would clear tensor saved bysave_for_backward, but not for tensors attached toctxdirectly). Therefore the attached tensors are not be released in time and caused higher memory usage. After manually setfunc_ctx.tensor_objectsto None these tensors can be properly freed.In addition, inRemoved this from the PR because it's not compatible with the mocked fuser backward in tests.BasicLinear's backward, I manually calledclear_tensor_dataon the weight tensor if it's allocated by the quantizer (w is not self.weight). This is not necessary since with the previous fix where the weight tensor will still be released after fuser's backward, so it's more of an optimization.(Tested on Megatron-LM's llama3 8B example with manually setting
use_te_op_fuser=Trueingpt_builders)Checklist: