-
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
7
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.
+90
−1
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ef5f4f5
Fix double iteration bug when resumed from a checkpoint.
sudiptob2 08c953e
Apply suggestions from code review
Borda 40c2726
update wording in the comments.
sudiptob2 7000eae
update test
sudiptob2 de108ca
Add independent flag to track checkpoint resumption.
sudiptob2 2f9cd44
lint
sudiptob2 656ef3c
Merge branch 'master' into fix/19427/double-iter
bhimrazy 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) |
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
This variable
_resuming_from_checkpoint
seems a bit redundant. From the naming and context, it looks like_loaded_from_state_dict
might already be serving a similar purpose. wdyt @sudiptob2 ?cc: @Borda