-
Notifications
You must be signed in to change notification settings - Fork 3.6k
[Bug] Add SharedCycleIteratorState #8889
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
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -14,8 +14,9 @@ | |||||
|
|
||||||
| import os | ||||||
| from collections.abc import Iterable, Iterator, Mapping, Sequence | ||||||
| from dataclasses import dataclass, field | ||||||
| from functools import partial | ||||||
| from typing import Any, Callable, Dict, Generator, Optional, Tuple, Union | ||||||
| from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union | ||||||
|
|
||||||
| import torch | ||||||
| from torch import Tensor | ||||||
|
|
@@ -170,12 +171,35 @@ def to_disk(self) -> None: | |||||
| torch.save(outputs, fp) | ||||||
|
|
||||||
|
|
||||||
| @dataclass | ||||||
| class SharedCycleIteratorState: | ||||||
|
|
||||||
| mode: str = "max_size_cycle" | ||||||
| dataloaders: List[DataLoader] = field(default_factory=lambda: []) | ||||||
| has_finished: Dict[int, bool] = field(default_factory=lambda: {}) | ||||||
| has_reset: bool = False | ||||||
|
|
||||||
| def reset(self) -> None: | ||||||
| for dataloader in self.dataloaders: | ||||||
| self.has_finished[id(dataloader)] = False | ||||||
| self.has_reset = True | ||||||
|
|
||||||
| @property | ||||||
| def done(self) -> bool: | ||||||
| if not self.has_reset: | ||||||
| raise MisconfigurationException("Please, call reset once all dataloaders have been added.") | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
with the comma in there it sounds a bit passive-aggressive 🤣 |
||||||
| if len(self.dataloaders) == 1: | ||||||
| return False | ||||||
| decision_fn = all if self.mode == "max_size_cycle" else any | ||||||
| return decision_fn(self.has_finished.values()) | ||||||
|
|
||||||
|
|
||||||
| class CycleIterator: | ||||||
| """ | ||||||
| Iterator for restarting a dataloader if it runs out of samples | ||||||
| """ | ||||||
|
|
||||||
| def __init__(self, loader: Any, length: Optional[int] = None): | ||||||
| def __init__(self, loader: Any, length: Optional[int] = None, state: SharedCycleIteratorState = None): | ||||||
| """ | ||||||
| Args: | ||||||
| loader: the loader to restart for cyclic (and optionally infinite) sampling | ||||||
|
|
@@ -185,6 +209,15 @@ def __init__(self, loader: Any, length: Optional[int] = None): | |||||
| if length is None: | ||||||
| length = float("inf") | ||||||
|
|
||||||
| if not state: | ||||||
| state = SharedCycleIteratorState() | ||||||
| state.dataloaders.append(loader) | ||||||
| state.reset() | ||||||
| else: | ||||||
| state.dataloaders.append(loader) | ||||||
|
|
||||||
| self.state = state | ||||||
|
|
||||||
| self.length = length | ||||||
| self.loader = loader | ||||||
| self._loader_iter = None | ||||||
|
|
@@ -205,21 +238,27 @@ def __next__(self) -> Any: | |||||
| """ | ||||||
| Fetches the next batch from internal dataloader and restarts | ||||||
| it if necessary | ||||||
|
|
||||||
| Returns: | ||||||
| Any: the resulting batch | ||||||
|
|
||||||
| Raises: | ||||||
| StopIteration: if more then :attr:`length` batches have been returned | ||||||
| """ | ||||||
| # Note: if self.length is `inf`, then the iterator will never stop | ||||||
| if self.counter >= self.__len__(): | ||||||
| if self.counter >= self.__len__() or self.state.done: | ||||||
| raise StopIteration | ||||||
|
|
||||||
| try: | ||||||
| return next(self._loader_iter) | ||||||
|
|
||||||
| except StopIteration: | ||||||
|
|
||||||
| # inform the shared state this loader has completed | ||||||
| self.state.has_finished[id(self.loader)] = True | ||||||
|
|
||||||
| # check if iteration should be stopped. | ||||||
| if self.state.done: | ||||||
| raise StopIteration | ||||||
|
|
||||||
| self._loader_iter = iter(self.loader) | ||||||
| return next(self._loader_iter) | ||||||
|
|
||||||
|
|
@@ -468,10 +507,14 @@ def _wrap_loaders_max_size_cycle(self) -> Any: | |||||
|
|
||||||
| # multiple loaders | ||||||
| if isinstance(self.loaders, (Sequence, Mapping)): | ||||||
| state = SharedCycleIteratorState() | ||||||
|
|
||||||
| self.loaders = apply_to_collection( | ||||||
| self.loaders, Iterable, CycleIterator, length=length, wrong_dtype=(Sequence, Mapping) | ||||||
| self.loaders, Iterable, CycleIterator, length=length, state=state, wrong_dtype=(Sequence, Mapping) | ||||||
| ) | ||||||
|
|
||||||
| state.reset() | ||||||
|
|
||||||
| def __iter__(self) -> Any: | ||||||
| """ | ||||||
| Create and return an iterator, `CombinedLoaderIterator`, for the combined loader. | ||||||
|
|
||||||
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
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.
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.
What do you think of these docs? Did I get it right?