Repository navigation
Skip long-lived objects in the per-step gc.collect() of QAT and QAD #3104
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
Merged
Merged
Changes from all commits
Commits
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 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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License 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. | ||
|
|
||
| import gc | ||
| import weakref | ||
|
|
||
| import pytest | ||
| import torch | ||
| from torch import nn | ||
|
|
||
| transformers = pytest.importorskip("transformers") | ||
|
|
||
| from modelopt.torch.opt.plugins.transformers import ModelOptHFTrainer, ModelOptTrainerArguments | ||
|
|
||
|
|
||
| class _TinyModel(nn.Module): | ||
| def __init__(self): | ||
| super().__init__() | ||
| self.embed = nn.Embedding(32, 8) | ||
| self.lm_head = nn.Linear(8, 32) | ||
|
|
||
| def forward(self, input_ids, labels=None, **kwargs): | ||
| logits = self.lm_head(self.embed(input_ids)) | ||
| loss = nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1)) | ||
| return {"loss": loss, "logits": logits} | ||
|
|
||
|
|
||
| class _FreezeCounts(transformers.TrainerCallback): | ||
| def __init__(self): | ||
| self.after_step = {} | ||
|
|
||
| def on_step_end(self, args, state, control, **kwargs): | ||
| self.after_step[state.global_step] = gc.get_freeze_count() | ||
|
|
||
|
|
||
| def test_manual_gc_freezes_during_train_and_unfreezes_after(tmp_path): | ||
| """``manual_gc`` freezes what lives through training and ``train()`` unfreezes it. | ||
|
|
||
| Collections skip frozen objects, which is the speed-up. A frozen object in a reference cycle is | ||
| never collected, so without the unfreeze the model would outlive the trainer. | ||
| """ | ||
| frozen_before = gc.get_freeze_count() # Python itself starts with a few hundred frozen objects | ||
| freeze_counts = _FreezeCounts() | ||
| model = _TinyModel() | ||
| model.__dict__["_cycle"] = [model] # only the cycle collector can free it | ||
| model_ref = weakref.ref(model) | ||
| dataset = [ | ||
| {"input_ids": torch.randint(0, 32, (8,)), "labels": torch.randint(0, 32, (8,))} | ||
| for _ in range(8) | ||
| ] | ||
| args = transformers.TrainingArguments( | ||
| output_dir=str(tmp_path), | ||
| max_steps=3, | ||
| per_device_train_batch_size=2, | ||
| report_to="none", | ||
| use_cpu=True, | ||
| ) | ||
| trainer = ModelOptHFTrainer( | ||
| model=model, | ||
| args=args, | ||
| trainer_args=ModelOptTrainerArguments(manual_gc=True), | ||
| train_dataset=dataset, | ||
| callbacks=[freeze_counts], | ||
| ) | ||
| try: | ||
| trainer.train() | ||
| # The collection before the second step freezes the model and optimizer state. | ||
| assert all(freeze_counts.after_step[step] > frozen_before for step in (2, 3)) | ||
| # gc.unfreeze() also returns the objects frozen before training. | ||
| assert gc.get_freeze_count() == 0 | ||
| del trainer, model | ||
| gc.collect() | ||
| assert model_ref() is None | ||
| finally: | ||
| gc.unfreeze() | ||
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.
Required: this test only guards
gc.unfreeze(). I ran it at this head: it fails with theunfreezeremoved, but it still passes withgc.freeze()removed, so nothing guards the speed-up and a refactor could turn the freeze into a no-op.Please assert the freeze too. For example, add a
TrainerCallbackwhoseon_step_endrecordsgc.get_freeze_count(), and check aftertrain()that the count was above its starting value from step 2 on, and that it is back at the starting value oncetrain()returns. Python starts with a few hundred frozen objects, so compare against the count taken beforetrain().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.
Done in 36dbabd: a callback records
gc.get_freeze_count()after each step, and the test checks it is above the pre-train()count from step 2 on, and 0 oncetrain()returns. It is 0 rather than the starting count becausegc.unfreeze()also returns the objects Python freezes at startup (the comment at the unfreeze says so). On B200 (NeMo 26.08, transformers 5.18) it passes in 1.2 s, and fails with eithergc.freeze()orgc.unfreeze()removed.