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

Ensure restarting from checkpoints leads to consistent internal counters #20379

Merged
merged 17 commits into from
Nov 13, 2024

Conversation

lantiga
Copy link
Collaborator

@lantiga lantiga commented Oct 31, 2024

What does this PR do?

Fixes #14579

The following code

import torch
from torch.utils.data import DataLoader, Dataset
 
import lightning as L
from lightning.pytorch.callbacks import ModelCheckpoint

 
class RandomDataset(Dataset):
   def __init__(self, size, length):
       self.len = length
       self.data = torch.randn(length, size)
 
   def __getitem__(self, index):
       return self.data[index]
 
   def __len__(self):
       return self.len
 
 
class BoringModel(L.LightningModule):
   def __init__(self):
       super().__init__()
       self.layer = torch.nn.Linear(32, 2)
 
   def forward(self, x):
       return self.layer(x)
 
   def training_step(self, batch, batch_idx):
       loss = self(batch).sum()
       return {"loss": loss}
 
   def configure_optimizers(self):
       return torch.optim.SGD(self.layer.parameters(), lr=0.1)

 
train_data = DataLoader(RandomDataset(32, 24), batch_size=2)
 
model = BoringModel()

trainer = L.Trainer(
   default_root_dir=".",
   max_steps=10,
   enable_model_summary=False,
   accelerator="cpu",
   callbacks=ModelCheckpoint(dirpath="./lightning_logs/checkpoints", save_last=True, save_top_k=-1, every_n_train_steps=10),
)
trainer.fit(model, train_data)

trainer = L.Trainer(
   default_root_dir=".",
   max_steps=20,
   enable_model_summary=False,
   accelerator="cpu",
   callbacks=ModelCheckpoint(dirpath="./lightning_logs/checkpoints", save_last=True, save_top_k=-1, every_n_train_steps=10),
)
trainer.fit(model, train_data, ckpt_path='last')

will produce skewed progress information in the checkpoints, compared to the case where there is no restart.

This is due to the fact that when ModelCheckpoint is triggered on on_train_batch_end, it won't see batch_progress.total.completed updated to the latest batch that was processed, because progress is updated right after the hook is called.

However, upon restart, there won't be any opportunity to register the actual completion of the batch, causing a skew that is proportional to the number of restarts. This impacts the time at which validation is called, which itself becomes dependent from restarts.

This PR addresses this issue by reconciling progress upon restart.

It adds tests and tightens the behavior when restarting in multiple cases, namely when checkpoints are saved:

  • on batch end
  • on batch end with validation
  • on epoch end
  • on epoch end with validation
  • on last
  • on last with validation
  • on exception
Before submitting
  • Was this discussed/agreed 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:

Reviewer checklist
  • 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

📚 Documentation preview 📚: https://pytorch-lightning--20379.org.readthedocs.build/en/20379/

cc @Borda

@github-actions github-actions bot added the pl Generic label for PyTorch Lightning package label Oct 31, 2024
Copy link
Contributor

github-actions bot commented Oct 31, 2024

⚡ Required checks status: All passing 🟢

Groups summary

🟢 pytorch_lightning: Tests workflow
Check ID Status
pl-cpu (macOS-13, lightning, 3.9, 2.1, oldest) success
pl-cpu (macOS-14, lightning, 3.10, 2.1) success
pl-cpu (macOS-14, lightning, 3.11, 2.2.2) success
pl-cpu (macOS-14, lightning, 3.11, 2.3) success
pl-cpu (macOS-14, lightning, 3.12, 2.4.1) success
pl-cpu (macOS-14, lightning, 3.12, 2.5.1) success
pl-cpu (ubuntu-20.04, lightning, 3.9, 2.1, oldest) success
pl-cpu (ubuntu-20.04, lightning, 3.10, 2.1) success
pl-cpu (ubuntu-20.04, lightning, 3.11, 2.2.2) success
pl-cpu (ubuntu-20.04, lightning, 3.11, 2.3) success
pl-cpu (ubuntu-22.04, lightning, 3.12, 2.4.1) success
pl-cpu (ubuntu-22.04, lightning, 3.12, 2.5.1) success
pl-cpu (windows-2022, lightning, 3.9, 2.1, oldest) success
pl-cpu (windows-2022, lightning, 3.10, 2.1) success
pl-cpu (windows-2022, lightning, 3.11, 2.2.2) success
pl-cpu (windows-2022, lightning, 3.11, 2.3) success
pl-cpu (windows-2022, lightning, 3.12, 2.4.1) success
pl-cpu (windows-2022, lightning, 3.12, 2.5.1) success
pl-cpu (macOS-14, pytorch, 3.9, 2.1) success
pl-cpu (ubuntu-20.04, pytorch, 3.9, 2.1) success
pl-cpu (windows-2022, pytorch, 3.9, 2.1) success
pl-cpu (macOS-13, pytorch, 3.10, 2.1) success
pl-cpu (ubuntu-22.04, pytorch, 3.10, 2.1) success
pl-cpu (windows-2022, pytorch, 3.10, 2.1) success

These checks are required after the changes to src/lightning/pytorch/loops/evaluation_loop.py, src/lightning/pytorch/loops/fit_loop.py, src/lightning/pytorch/loops/loop.py, src/lightning/pytorch/loops/progress.py, src/lightning/pytorch/loops/training_epoch_loop.py, tests/tests_pytorch/loops/test_loops.py, tests/tests_pytorch/models/test_hooks.py.

🟢 pytorch_lightning: Azure GPU
Check ID Status
pytorch-lightning (GPUs) (testing Lightning | latest) success
pytorch-lightning (GPUs) (testing PyTorch | latest) success

These checks are required after the changes to src/lightning/pytorch/loops/evaluation_loop.py, src/lightning/pytorch/loops/fit_loop.py, src/lightning/pytorch/loops/loop.py, src/lightning/pytorch/loops/progress.py, src/lightning/pytorch/loops/training_epoch_loop.py, tests/tests_pytorch/loops/test_loops.py, tests/tests_pytorch/models/test_hooks.py.

🟢 pytorch_lightning: Benchmarks
Check ID Status
lightning.Benchmarks success

These checks are required after the changes to src/lightning/pytorch/loops/evaluation_loop.py, src/lightning/pytorch/loops/fit_loop.py, src/lightning/pytorch/loops/loop.py, src/lightning/pytorch/loops/progress.py, src/lightning/pytorch/loops/training_epoch_loop.py.

🟢 pytorch_lightning: Docs
Check ID Status
docs-make (pytorch, doctest) success
docs-make (pytorch, html) success

These checks are required after the changes to src/lightning/pytorch/loops/evaluation_loop.py, src/lightning/pytorch/loops/fit_loop.py, src/lightning/pytorch/loops/loop.py, src/lightning/pytorch/loops/progress.py, src/lightning/pytorch/loops/training_epoch_loop.py.

🟢 mypy
Check ID Status
mypy success

These checks are required after the changes to src/lightning/pytorch/loops/evaluation_loop.py, src/lightning/pytorch/loops/fit_loop.py, src/lightning/pytorch/loops/loop.py, src/lightning/pytorch/loops/progress.py, src/lightning/pytorch/loops/training_epoch_loop.py.

🟢 install
Check ID Status
install-pkg (ubuntu-22.04, fabric, 3.9) success
install-pkg (ubuntu-22.04, fabric, 3.11) success
install-pkg (ubuntu-22.04, pytorch, 3.9) success
install-pkg (ubuntu-22.04, pytorch, 3.11) success
install-pkg (ubuntu-22.04, lightning, 3.9) success
install-pkg (ubuntu-22.04, lightning, 3.11) success
install-pkg (ubuntu-22.04, notset, 3.9) success
install-pkg (ubuntu-22.04, notset, 3.11) success
install-pkg (macOS-13, fabric, 3.9) success
install-pkg (macOS-13, fabric, 3.11) success
install-pkg (macOS-13, pytorch, 3.9) success
install-pkg (macOS-13, pytorch, 3.11) success
install-pkg (macOS-13, lightning, 3.9) success
install-pkg (macOS-13, lightning, 3.11) success
install-pkg (macOS-13, notset, 3.9) success
install-pkg (macOS-13, notset, 3.11) success
install-pkg (windows-2022, fabric, 3.9) success
install-pkg (windows-2022, fabric, 3.11) success
install-pkg (windows-2022, pytorch, 3.9) success
install-pkg (windows-2022, pytorch, 3.11) success
install-pkg (windows-2022, lightning, 3.9) success
install-pkg (windows-2022, lightning, 3.11) success
install-pkg (windows-2022, notset, 3.9) success
install-pkg (windows-2022, notset, 3.11) success

These checks are required after the changes to src/lightning/pytorch/loops/evaluation_loop.py, src/lightning/pytorch/loops/fit_loop.py, src/lightning/pytorch/loops/loop.py, src/lightning/pytorch/loops/progress.py, src/lightning/pytorch/loops/training_epoch_loop.py.


Thank you for your contribution! 💜

Note
This comment is automatically generated and updates for 60 minutes every 180 seconds. If you have any other questions, contact carmocca for help.

@lantiga lantiga changed the title Bump completed progress on load with checkpoints saved on_train_batch_end Ensure restarting from checkpoints leads to consistent internal counters Nov 11, 2024
@lantiga lantiga added the ready PRs ready to be merged label Nov 12, 2024
@mergify mergify bot removed the ready PRs ready to be merged label Nov 12, 2024
Copy link

codecov bot commented Nov 12, 2024

Codecov Report

Attention: Patch coverage is 97.20280% with 4 lines in your changes missing coverage. Please review.

Project coverage is 81%. Comparing base (61a403a) to head (8aa1b9a).
Report is 3 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (61a403a) and HEAD (8aa1b9a). Click for more details.

HEAD has 102 uploads less than BASE
Flag BASE (61a403a) HEAD (8aa1b9a)
cpu 48 24
python3.10 12 6
lightning_fabric 7 0
pytest 28 2
lightning 38 19
python3.9 12 6
gpu 4 2
python3.11 12 6
python3.12 12 6
Additional details and impacted files
@@            Coverage Diff            @@
##           master   #20379     +/-   ##
=========================================
- Coverage      89%      81%     -8%     
=========================================
  Files         267      264      -3     
  Lines       23070    23147     +77     
=========================================
- Hits        20579    18739   -1840     
- Misses       2491     4408   +1917     

@lantiga lantiga added the ready PRs ready to be merged label Nov 12, 2024
@lantiga lantiga merged commit 9358898 into master Nov 13, 2024
78 of 79 checks passed
@lantiga lantiga deleted the luca/restart-batch-fix branch November 13, 2024 10:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pl Generic label for PyTorch Lightning package ready PRs ready to be merged
Projects
None yet
Development

Successfully merging this pull request may close these issues.

TrainingEpochLoop._should_check_val_fx discrepancy between continued run <> restore from ckpt
2 participants