-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Fix double iteration bug when resumed from a checkpoint. #20775
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
Open
sudiptob2
wants to merge
6
commits into
Lightning-AI:master
Choose a base branch
from
sudiptob2:fix/19427/double-iter
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+87
−1
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8119224
Fix double iteration bug when resumed from a checkpoint.
sudiptob2 5c0b122
Apply suggestions from code review
Borda e124950
update wording in the comments.
sudiptob2 130102c
update test
sudiptob2 e9aae7a
Merge branch 'master' into fix/19427/double-iter
Borda 0e99ffe
Merge branch 'master' into fix/19427/double-iter
Borda 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
77 changes: 77 additions & 0 deletions
77
tests/tests_pytorch/loops/test_double_iter_in_iterable_dataset.py
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,77 @@ | ||
# Copyright The Lightning AI team. | ||
# | ||
# 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. | ||
# | ||
# This test tests the resuming of training from a checkpoint file using an IterableDataset. | ||
# And contains code mentioned in the issue: #19427. | ||
# Ref: https://github.com/Lightning-AI/pytorch-lightning/issues/19427 | ||
import multiprocessing as mp | ||
import os | ||
from collections.abc import Iterator | ||
from pathlib import Path | ||
from queue import Queue | ||
|
||
import numpy as np | ||
from torch.utils.data import DataLoader, IterableDataset | ||
|
||
from lightning.pytorch import Trainer | ||
from lightning.pytorch.demos.boring_classes import BoringModel | ||
|
||
|
||
class QueueDataset(IterableDataset): | ||
def __init__(self, queue: Queue) -> None: | ||
super().__init__() | ||
self.queue = queue | ||
|
||
def __iter__(self) -> Iterator: | ||
for _ in range(5): | ||
tensor, _ = self.queue.get(timeout=5) | ||
yield tensor | ||
|
||
|
||
def create_queue() -> Queue: | ||
q = mp.Queue() | ||
arr = np.random.random([1, 32]).astype(np.float32) | ||
for ind in range(20): | ||
q.put((arr, ind)) | ||
return q | ||
|
||
|
||
def train_model(queue: Queue, max_epochs: int, ckpt_path: Path) -> None: | ||
dataloader = DataLoader(QueueDataset(queue), num_workers=1, batch_size=None, persistent_workers=True) | ||
trainer = Trainer( | ||
max_epochs=max_epochs, | ||
enable_progress_bar=False, | ||
enable_checkpointing=False, | ||
devices=1, | ||
logger=False, | ||
) | ||
if ckpt_path.exists(): | ||
trainer.fit(BoringModel(), dataloader, ckpt_path=str(ckpt_path)) | ||
else: | ||
trainer.fit(BoringModel(), dataloader) | ||
trainer.save_checkpoint(str(ckpt_path)) | ||
|
||
|
||
def test_resume_training_with(tmp_path): | ||
"""Test resuming training from checkpoint file using a IterableDataset.""" | ||
queue = create_queue() | ||
max_epoch = 2 | ||
ckpt_path = tmp_path / "model.ckpt" | ||
train_model(queue, max_epoch, ckpt_path) | ||
|
||
assert os.path.exists(ckpt_path), f"Checkpoint file '{ckpt_path}' wasn't created" | ||
ckpt_size = os.path.getsize(ckpt_path) | ||
assert ckpt_size > 0, f"Checkpoint file is empty (size: {ckpt_size} bytes)" | ||
|
||
train_model(queue, max_epoch + 2, ckpt_path) |
Oops, something went wrong.
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.
Looking at how the
_loaded_from_state_dict
is used, and there is no direct wrap for loading, meaning set it as true/false when loading starts, and switch back when it ends so for that we my need to add another/new attributeThere 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.
Hi! Thanks for taking a look at it. I am not sure why we need that.
_loaded_from_state_dict
is already made True and False when necessary so I am using_loaded_from_state_dict
to detect checkpoint resumption.I might have missed something, could you please suggest what changes we need here?
pytorch-lightning/src/lightning/pytorch/loops/loop.py
Line 89 in 1e88899
pytorch-lightning/src/lightning/pytorch/loops/loop.py
Lines 102 to 105 in 1e88899