-
Notifications
You must be signed in to change notification settings - Fork 97
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
prefetch: use a separate temporary cache for prefetching #730
Open
skshetry
wants to merge
7
commits into
main
Choose a base branch
from
prefetch-cache
base: main
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.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1a3318b
use separate cache for prefetch by default
skshetry f5482b3
prefetch: disable for huggingface
skshetry 3804445
add tests for prefetch
skshetry 84e615b
cancel future and wait for it
skshetry b8809d7
hoist temporary cache creation to Mapper
skshetry a516de8
refactor udfs
skshetry 1f57dc6
pytorchdataset: use weakref.finalize to cleanup temporary cache
skshetry 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 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 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 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 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 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 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 |
---|---|---|
@@ -1,5 +1,8 @@ | ||
import logging | ||
from collections.abc import Iterator | ||
import os | ||
import weakref | ||
from collections.abc import Generator, Iterable, Iterator | ||
from contextlib import closing | ||
from typing import TYPE_CHECKING, Any, Callable, Optional | ||
|
||
from PIL import Image | ||
|
@@ -9,11 +12,13 @@ | |
from torchvision.transforms import v2 | ||
|
||
from datachain import Session | ||
from datachain.asyn import AsyncMapper | ||
from datachain.cache import get_temp_cache | ||
from datachain.catalog import Catalog, get_catalog | ||
from datachain.lib.dc import DataChain | ||
from datachain.lib.settings import Settings | ||
from datachain.lib.text import convert_text | ||
from datachain.progress import CombinedDownloadCallback | ||
from datachain.query.dataset import get_download_callback | ||
|
||
if TYPE_CHECKING: | ||
from torchvision.transforms.v2 import Transform | ||
|
@@ -75,6 +80,18 @@ | |
if (prefetch := dc_settings.prefetch) is not None: | ||
self.prefetch = prefetch | ||
|
||
if self.cache or not self.prefetch: | ||
self._cache = catalog.cache | ||
else: | ||
tmp_dir = catalog.cache.tmp_dir | ||
assert tmp_dir | ||
self._cache = get_temp_cache(tmp_dir, prefix="prefetch-") | ||
weakref.finalize(self, self.close) | ||
|
||
def close(self) -> None: | ||
if not self.cache: | ||
self._cache.destroy() | ||
|
||
def _init_catalog(self, catalog: "Catalog"): | ||
# For compatibility with multiprocessing, | ||
# we can only store params in __init__(), as Catalog isn't picklable | ||
|
@@ -89,9 +106,15 @@ | |
ms = ms_cls(*ms_args, **ms_kwargs) | ||
wh_cls, wh_args, wh_kwargs = self._wh_params | ||
wh = wh_cls(*wh_args, **wh_kwargs) | ||
return Catalog(ms, wh, **self._catalog_params) | ||
catalog = Catalog(ms, wh, **self._catalog_params) | ||
catalog.cache = self._cache | ||
return catalog | ||
|
||
def _rows_iter(self, total_rank: int, total_workers: int): | ||
def _row_iter( | ||
self, | ||
total_rank: int, | ||
total_workers: int, | ||
) -> Generator[tuple[Any, ...], None, None]: | ||
catalog = self._get_catalog() | ||
session = Session("PyTorch", catalog=catalog) | ||
ds = DataChain.from_dataset( | ||
|
@@ -104,16 +127,32 @@ | |
ds = ds.chunk(total_rank, total_workers) | ||
yield from ds.collect() | ||
|
||
def __iter__(self) -> Iterator[Any]: | ||
total_rank, total_workers = self.get_rank_and_workers() | ||
rows = self._rows_iter(total_rank, total_workers) | ||
if self.prefetch > 0: | ||
from datachain.lib.udf import _prefetch_input | ||
|
||
rows = AsyncMapper(_prefetch_input, rows, workers=self.prefetch).iterate() | ||
yield from map(self._process_row, rows) | ||
def _iter_with_prefetch(self) -> Generator[tuple[Any], None, None]: | ||
from datachain.lib.udf import _prefetch_inputs | ||
|
||
def _process_row(self, row_features): | ||
total_rank, total_workers = self.get_rank_and_workers() | ||
download_cb = CombinedDownloadCallback() | ||
if os.getenv("DATACHAIN_SHOW_PREFETCH_PROGRESS"): | ||
download_cb = get_download_callback( | ||
f"{total_rank}/{total_workers}", position=total_rank | ||
) | ||
Comment on lines
+135
to
+138
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. This shows a prefetch download progressbar for each worker which will be useful for debugging. We cannot enable this by default, as this will mess up user's progressbar due to multiprocessing. |
||
|
||
rows = self._row_iter(total_rank, total_workers) | ||
rows = _prefetch_inputs( | ||
rows, | ||
self.prefetch, | ||
download_cb=download_cb, | ||
after_prefetch=download_cb.increment_file_count, | ||
) | ||
|
||
with download_cb, closing(rows): | ||
yield from rows | ||
|
||
def __iter__(self) -> Iterator[list[Any]]: | ||
with closing(self._iter_with_prefetch()) as rows: | ||
yield from map(self._process_row, rows) | ||
|
||
def _process_row(self, row_features: Iterable[Any]) -> list[Any]: | ||
row = [] | ||
for fr in row_features: | ||
if hasattr(fr, "read"): | ||
|
Oops, something went wrong.
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.
.cancel()
does not immediately cancel the task the underlyingasyncio
task.We could add a
.result()
to wait for the future, but that does not seem to work either for the cancelled future fromrun_coroutine_threadsafe()
. See python/cpython#105836.So, I have added
wait(...)
as it seems to wait the cancelled future, and wait for underlying asyncio task.Alternatively, we could add an
asyncio.Event
and wait for it.