|
| 1 | +# Copyright The Lightning AI team. |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +import json |
| 15 | +import os |
| 16 | +from typing import Any, Dict, List, Optional, Tuple |
| 17 | + |
| 18 | +from lightning.data.cache.constants import _INDEX_FILENAME, _TORCH_2_1_0_AVAILABLE |
| 19 | +from lightning.data.cache.downloader import get_downloader_cls |
| 20 | +from lightning.data.cache.sampler import ChunkedIndex |
| 21 | + |
| 22 | +if _TORCH_2_1_0_AVAILABLE: |
| 23 | + from torch.utils._pytree import treespec_loads |
| 24 | + |
| 25 | + |
| 26 | +class ChunksConfig: |
| 27 | + def __init__(self, cache_dir: str, remote_dir: Optional[str]): |
| 28 | + """The ChunksConfig reads the index files associated a chunked dataset and enables to map an index to its |
| 29 | + chunk. |
| 30 | +
|
| 31 | + Arguments: |
| 32 | + cache_dir: The path to cache folder. |
| 33 | + remote_dir: The path to a remote folder where the data are located. |
| 34 | + The scheme needs to be added to the path. |
| 35 | +
|
| 36 | + """ |
| 37 | + self._cache_dir = cache_dir |
| 38 | + self._intervals: List[Tuple[int, int]] = [] |
| 39 | + self._config = None |
| 40 | + self._chunks = [] |
| 41 | + self._remote_dir = remote_dir |
| 42 | + |
| 43 | + with open(os.path.join(self._cache_dir, _INDEX_FILENAME)) as f: |
| 44 | + data = json.load(f) |
| 45 | + |
| 46 | + self._config = data["config"] |
| 47 | + |
| 48 | + self._chunks.extend(data["chunks"]) |
| 49 | + |
| 50 | + self._config["data_spec"] = treespec_loads(self._config["data_spec"]) |
| 51 | + |
| 52 | + for chunk in self._chunks: |
| 53 | + start, end = chunk["interval"] |
| 54 | + if (end - start) != chunk["chunk_size"]: |
| 55 | + raise Exception( |
| 56 | + "The config intervals doesn't match the number of samples. This shouldn't have happened." |
| 57 | + ) |
| 58 | + self._intervals.append((chunk["interval"][0], chunk["interval"][1])) |
| 59 | + |
| 60 | + self._length = sum([chunk["chunk_size"] for chunk in self._chunks]) |
| 61 | + |
| 62 | + self._downloader = None |
| 63 | + |
| 64 | + if remote_dir: |
| 65 | + self._downloader = get_downloader_cls(remote_dir)(remote_dir, cache_dir, self._chunks) |
| 66 | + |
| 67 | + def download_chunk_from_index(self, chunk_index: int) -> None: |
| 68 | + chunk_filename = self._chunks[chunk_index]["filename"] |
| 69 | + |
| 70 | + local_chunkpath = os.path.join(self._cache_dir, chunk_filename) |
| 71 | + |
| 72 | + if os.path.exists(local_chunkpath): |
| 73 | + return |
| 74 | + |
| 75 | + if self._downloader is None: |
| 76 | + raise RuntimeError("The downloader should be defined.") |
| 77 | + |
| 78 | + self._downloader.download_chunk_from_index(chunk_index) |
| 79 | + |
| 80 | + @property |
| 81 | + def intervals(self) -> List[Tuple[int, int]]: |
| 82 | + if self._intervals is None: |
| 83 | + raise RuntimeError("The intervals should be defined.") |
| 84 | + return self._intervals |
| 85 | + |
| 86 | + @property |
| 87 | + def data_format(self) -> Any: |
| 88 | + if self._config is None: |
| 89 | + raise RuntimeError("The config should be defined.") |
| 90 | + return self._config["data_format"] |
| 91 | + |
| 92 | + @property |
| 93 | + def config(self) -> Dict[str, Any]: |
| 94 | + if self._config is None: |
| 95 | + raise RuntimeError("The config should be defined.") |
| 96 | + return self._config |
| 97 | + |
| 98 | + def _get_chunk_index_from_index(self, index: int) -> int: |
| 99 | + for chunk_index, internal in enumerate(self._intervals): |
| 100 | + if internal[0] <= index < internal[1]: |
| 101 | + return chunk_index |
| 102 | + raise ValueError( |
| 103 | + f"The provided index {index} didn't find a match within the chunk intervals {self._intervals}." |
| 104 | + ) |
| 105 | + |
| 106 | + def __getitem__(self, index: ChunkedIndex) -> Tuple[str, int, int]: |
| 107 | + """Find the associated chunk metadata.""" |
| 108 | + chunk = self._chunks[index.chunk_index] |
| 109 | + return os.path.join(self._cache_dir, chunk["filename"]), *self._intervals[index.chunk_index] |
| 110 | + |
| 111 | + @classmethod |
| 112 | + def load(cls, cache_dir: str, remote_dir: Optional[str] = None) -> Optional["ChunksConfig"]: |
| 113 | + cache_index_filepath = os.path.join(cache_dir, _INDEX_FILENAME) |
| 114 | + |
| 115 | + if isinstance(remote_dir, str): |
| 116 | + downloader = get_downloader_cls(remote_dir)(remote_dir, cache_dir, []) |
| 117 | + downloader.download_file(os.path.join(remote_dir, _INDEX_FILENAME), cache_index_filepath) |
| 118 | + |
| 119 | + if not os.path.exists(cache_index_filepath): |
| 120 | + return None |
| 121 | + |
| 122 | + return ChunksConfig(cache_dir, remote_dir) |
| 123 | + |
| 124 | + def __len__(self) -> int: |
| 125 | + return self._length |
0 commit comments