Skip to content
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

Fix LR scheduler behaviour with AMP #16229

Open
wants to merge 24 commits into
base: master
Choose a base branch
from

Conversation

milesial
Copy link

@milesial milesial commented Jan 3, 2023

What does this PR do?

When training when native AMP and a LR scheduler, we get this warning that indicates that a LR step has been taken when an optimizer step was skipped (expected at the beginning of the training with native AMP):

/usr/local/lib/python3.8/dist-packages/torch/optim/lr_scheduler.py:138: UserWarning: Detected call of `lr_scheduler.step()` before `optimizer.step()`. In PyTorch 1.1.0 and later, you should call them in the opposite order: `optimizer.step()` before `lr_scheduler.step()`.  Failure to do this will result in PyTorch skipping the first value of the learning rate schedule. See more details at https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate

Fixes #16228 #5558

Does your PR introduce any breaking changes? If yes, please list them.

No

Before submitting

  • Was this discussed/approved via a GitHub issue? (not for typos and docs)
  • Did you read the contributor guideline, Pull Request section?
  • Did you make sure your PR does only one thing, instead of bundling different changes together?
  • Did you make sure to update the documentation with your changes? (if necessary)
  • Did you write any new necessary tests? (not for typos and docs)
  • Did you verify new and existing tests pass locally with your changes?
  • Did you list all the breaking changes introduced by this pull request?
  • Did you update the CHANGELOG? (not for typos, docs, test updates, or minor internal changes/refactors)

PR review

Anyone in the community is welcome to review the PR.
Before you start reviewing, make sure you have read the review guidelines. In short, see the following bullet-list:

  • Is this pull request ready for review? (if not, please submit in draft mode)
  • Check that all items from Before submitting are resolved
  • Make sure the title is self-explanatory and the description concisely explains the PR
  • Add labels and milestones (and optionally projects) to the PR so it can be classified

@milesial
Copy link
Author

milesial commented Jan 3, 2023

In the process of fixing tests I discovered and fixed a bug where the scheduler wouldn't match its optimizer when multiple optimizers are instantiated with frequencies. Now the optimizers and schedulers match and alternate as they should, resetting the cycle every epoch.

@milesial
Copy link
Author

milesial commented Jan 9, 2023

@carmocca Ready for final review

@@ -390,7 +391,7 @@ def update_lr_schedulers(self, interval: str, update_plateau_schedulers: bool) -
if interval == "step" and self._should_accumulate():
return
active_optimizers = _get_active_optimizers(
self.trainer.optimizers, self.trainer.optimizer_frequencies, self.total_batch_idx
self.trainer.optimizers, self.trainer.optimizer_frequencies, self.batch_idx
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a test to verify this works properly ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I modified the third case of test_step_scheduling_for_multiple_optimizers_with_frequency so that it tests that

@awaelchli awaelchli added community This PR is from the community optimization labels Jan 9, 2023
@carmocca carmocca requested a review from Borda as a code owner January 10, 2023 16:13
Copy link
Member

@carmocca carmocca left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you check the failing tests?

setup.cfg Outdated
@@ -34,6 +34,7 @@ markers =
cloud:Run the cloud tests for example
filterwarnings =
error::FutureWarning
error:Detected call of `lr_scheduler.step\(\)` before `optimizer.step\(\)`:UserWarning
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added this line so that our CI fails if this warning appears. This way it tests that your patch works as expected.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, but this also makes IPU tests fail, this PR is focused on GPU. Not sure where to fix the issue on IPUs

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@milesial IMHO, we could just skip the IPU test failures as done in my old PR #11755 for now.

@milesial
Copy link
Author

milesial commented Jan 10, 2023

The way I fixed the tests/tests_pytorch/models/test_hooks.py::test_trainer_model_hook_system_fit[True-kwargs1] tests is very flaky, so I'd appreciate if someone more familiar with these tests comes up with a better fix.
edit: seems like it didn't even fix it...

@milesial
Copy link
Author

I also modified native_amp.py in both lightning_fabric and pytorch_lightning. It doesn't seem like the lightning_fabric one is called for a typical workflow, so I don't know if it's the right way

@stale stale bot added the won't fix This will not be worked on label Mar 18, 2023
@stale stale bot removed the won't fix This will not be worked on label Mar 20, 2023
@stale stale bot added the won't fix This will not be worked on label Apr 13, 2023
@Lightning-AI Lightning-AI deleted a comment from stale bot Apr 14, 2023
@stale stale bot removed the won't fix This will not be worked on label Apr 14, 2023
@mrembalski
Copy link

Hi @Borda, I also encounter the same issue. Will this be merged?

@Lightning-AI Lightning-AI deleted a comment from stale bot Apr 25, 2023
@Borda
Copy link
Member

Borda commented Apr 25, 2023

Hi @Borda, I also encounter the same issue. Will this be merged?

Let me check what is missing here...

@mergify mergify bot removed the has conflicts label Apr 26, 2023
@alimoezzi
Copy link

Is this PR merged already? I'm still having this issue.

@Borda
Copy link
Member

Borda commented May 23, 2023

there were some failing tests, @milesial mind have a look?

Copy link

gitguardian bot commented Nov 18, 2023

⚠️ GitGuardian has uncovered 2 secrets following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secrets in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
- Generic High Entropy Secret 78fa3af tests/tests_app/utilities/test_login.py View secret
- Base64 Basic Authentication 78fa3af tests/tests_app/utilities/test_login.py View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Our GitHub checks need improvements? Share your feedbacks!

Copy link

codecov bot commented Nov 18, 2023

Codecov Report

Merging #16229 (965fc03) into master (6497e36) will decrease coverage by 54%.
Report is 1 commits behind head on master.
The diff coverage is 29%.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #16229      +/-   ##
==========================================
- Coverage      83%      29%     -54%     
==========================================
  Files         450      442       -8     
  Lines       38089    37941     -148     
==========================================
- Hits        31803    11015   -20788     
- Misses       6286    26926   +20640     

@mergify mergify bot removed the has conflicts label Feb 16, 2024
@carmocca carmocca removed their assignment May 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
community This PR is from the community fabric lightning.fabric.Fabric optimization pl Generic label for PyTorch Lightning package
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Wrong LR scheduler behaviour when using AMP
8 participants