|
| 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 | +from abc import ABC, abstractmethod |
| 15 | +from functools import lru_cache |
| 16 | +from typing import Any, List |
| 17 | + |
| 18 | +import numpy as np |
| 19 | + |
| 20 | +from lightning.data.datasets.env import _DistributedEnv |
| 21 | +from lightning.data.streaming import Cache |
| 22 | + |
| 23 | + |
| 24 | +class Shuffle(ABC): |
| 25 | + """Shuffle describe how to distribute chunked datasets across processes and workers.""" |
| 26 | + |
| 27 | + def __init__(self, cache: Cache, seed: int): |
| 28 | + self.cache = cache |
| 29 | + self.seed = seed |
| 30 | + self.random_state = None |
| 31 | + |
| 32 | + @abstractmethod |
| 33 | + def get_len(self, distributed_env: _DistributedEnv, current_epoch: int) -> int: |
| 34 | + pass |
| 35 | + |
| 36 | + @abstractmethod |
| 37 | + def get_chunks_and_intervals_per_process(self, distributed_env: _DistributedEnv, current_epoch: int) -> Any: |
| 38 | + pass |
| 39 | + |
| 40 | + @abstractmethod |
| 41 | + def __call__(self, array: np.ndarray) -> List[int]: |
| 42 | + pass |
| 43 | + |
| 44 | + |
| 45 | +class NoShuffle(Shuffle): |
| 46 | + """NoShuffle doesn't shuffle the items and ensure all the processes receive the same number of items.""" |
| 47 | + |
| 48 | + @lru_cache(maxsize=10) |
| 49 | + def get_len(self, distributed_env: _DistributedEnv, current_epoch: int) -> int: |
| 50 | + _, intervals_per_process = self.get_chunks_and_intervals_per_process(distributed_env, current_epoch) |
| 51 | + min_items_per_process = min( |
| 52 | + [sum([(interval[-1] - interval[0]) for interval in intervals]) for intervals in intervals_per_process] |
| 53 | + ) |
| 54 | + return min_items_per_process |
| 55 | + |
| 56 | + @lru_cache(maxsize=10) |
| 57 | + def get_chunks_and_intervals_per_process(self, distributed_env: _DistributedEnv, current_epoch: int) -> Any: |
| 58 | + self.random_state = np.random.RandomState(seed=self.seed + current_epoch) # type: ignore |
| 59 | + chunk_intervals = self.cache.get_chunk_intervals() |
| 60 | + indexes = list(range(len(chunk_intervals))) |
| 61 | + shuffled_chunk_intervals = np.asarray(chunk_intervals)[indexes] |
| 62 | + |
| 63 | + chunks_per_process: List[List[int]] = [[] for _ in range(distributed_env.world_size)] |
| 64 | + intervals_per_process: List[List[List[int]]] = [[] for _ in range(distributed_env.world_size)] |
| 65 | + for index, (chunk_index, chunk_interval) in enumerate(zip(indexes, shuffled_chunk_intervals)): |
| 66 | + replica_index = index % distributed_env.world_size |
| 67 | + chunks_per_process[replica_index].append(chunk_index) |
| 68 | + intervals_per_process[replica_index].append(chunk_interval) |
| 69 | + |
| 70 | + return chunks_per_process, intervals_per_process |
| 71 | + |
| 72 | + def __call__(self, array: np.ndarray) -> List[int]: |
| 73 | + return array.tolist() |
| 74 | + |
| 75 | + |
| 76 | +class TruncatedShuffle(Shuffle): |
| 77 | + """TruncatedShuffle shuffles the chunks and associates them to the ranks. |
| 78 | +
|
| 79 | + As the number of items in a chunk varies, it is possible for a rank to end up with more or less items. |
| 80 | +
|
| 81 | + To ensure the same fixed dataset length for all ranks, we compute the minimum number of items across all ranks. |
| 82 | +
|
| 83 | + For the ranks with more items than the minimum, the remaining items are dropped. |
| 84 | +
|
| 85 | + Note: This is the fastest sampling strategy but at the cost of losing items. |
| 86 | +
|
| 87 | + """ |
| 88 | + |
| 89 | + @lru_cache(maxsize=10) |
| 90 | + def get_len(self, distributed_env: _DistributedEnv, current_epoch: int) -> int: |
| 91 | + _, intervals_per_process = self.get_chunks_and_intervals_per_process(distributed_env, current_epoch) |
| 92 | + min_items_per_process = min( |
| 93 | + [sum([(interval[-1] - interval[0]) for interval in intervals]) for intervals in intervals_per_process] |
| 94 | + ) |
| 95 | + return min_items_per_process |
| 96 | + |
| 97 | + @lru_cache(maxsize=10) |
| 98 | + def get_chunks_and_intervals_per_process(self, distributed_env: _DistributedEnv, current_epoch: int) -> Any: |
| 99 | + self.random_state = np.random.RandomState(seed=self.seed + current_epoch) # type: ignore |
| 100 | + chunk_intervals = self.cache.get_chunk_intervals() |
| 101 | + indexes = range(len(chunk_intervals)) |
| 102 | + shuffled_indexes = self.random_state.permutation(indexes) |
| 103 | + shuffled_chunk_intervals = np.asarray(chunk_intervals)[shuffled_indexes] |
| 104 | + |
| 105 | + chunks_per_process: List[List[int]] = [[] for _ in range(distributed_env.world_size)] |
| 106 | + intervals_per_process: List[List[List[int]]] = [[] for _ in range(distributed_env.world_size)] |
| 107 | + for index, (chunk_index, chunk_interval) in enumerate(zip(shuffled_indexes, shuffled_chunk_intervals)): |
| 108 | + replica_index = index % distributed_env.world_size |
| 109 | + chunks_per_process[replica_index].append(chunk_index) |
| 110 | + intervals_per_process[replica_index].append(chunk_interval) |
| 111 | + |
| 112 | + return chunks_per_process, intervals_per_process |
| 113 | + |
| 114 | + def __call__(self, array: np.ndarray) -> List[int]: |
| 115 | + assert self.random_state |
| 116 | + return self.random_state.permutation(array).tolist() |
| 117 | + |
| 118 | + |
| 119 | +class FullShuffle(Shuffle): |
| 120 | + """FullShuffle shuffles the chunks and associates them to the ranks. |
| 121 | +
|
| 122 | + As the number of items in a chunk varies, it is possible for a rank to end up with more or less items. |
| 123 | +
|
| 124 | + To ensure the same fixed dataset length for all ranks while dropping as few items as possible, |
| 125 | +
|
| 126 | + we adopt the following strategy. |
| 127 | +
|
| 128 | + We compute the maximum number of items per rank (M) and iterate through the chunks and ranks |
| 129 | +
|
| 130 | + until we have associated at least M items per rank. |
| 131 | +
|
| 132 | + As a result, we lose at most (number of ranks) items. However, as some chunks are shared across ranks. This leads to |
| 133 | + the same chunk to be downloaded multiple times. |
| 134 | +
|
| 135 | + """ |
| 136 | + |
| 137 | + @lru_cache(maxsize=10) |
| 138 | + def get_len(self, distributed_env: _DistributedEnv, current_epoch: int) -> int: |
| 139 | + _, intervals_per_process = self.get_chunks_and_intervals_per_process(distributed_env, current_epoch) |
| 140 | + min_items_per_process = min([sum([(i[-1] - i[0]) for i in intervals]) for intervals in intervals_per_process]) |
| 141 | + return min_items_per_process |
| 142 | + |
| 143 | + @lru_cache(maxsize=10) |
| 144 | + def get_chunks_and_intervals_per_process(self, distributed_env: _DistributedEnv, current_epoch: int) -> Any: |
| 145 | + self.random_state = np.random.RandomState(seed=self.seed + current_epoch) # type: ignore |
| 146 | + chunk_intervals = self.cache.get_chunk_intervals() |
| 147 | + indexes = range(len(chunk_intervals)) |
| 148 | + shuffled_indexes = self.random_state.permutation(indexes) |
| 149 | + shuffled_chunk_intervals = np.asarray(chunk_intervals)[shuffled_indexes] |
| 150 | + |
| 151 | + num_items = sum([(interval[-1] - interval[0]) for interval in chunk_intervals]) |
| 152 | + num_items_per_process: List[int] = [ |
| 153 | + num_items // distributed_env.world_size for _ in range(distributed_env.world_size) |
| 154 | + ] |
| 155 | + chunks_per_process: List[List[int]] = [[] for _ in range(distributed_env.world_size)] |
| 156 | + intervals_per_process: List[List[List[int]]] = [[] for _ in range(distributed_env.world_size)] |
| 157 | + for chunk_index, chunk_interval in zip(shuffled_indexes, shuffled_chunk_intervals): |
| 158 | + process_index = 0 |
| 159 | + |
| 160 | + while True: |
| 161 | + if process_index == len(num_items_per_process): |
| 162 | + break |
| 163 | + |
| 164 | + items_left_to_assign = num_items_per_process[process_index] |
| 165 | + |
| 166 | + if items_left_to_assign == 0: |
| 167 | + process_index += 1 |
| 168 | + continue |
| 169 | + |
| 170 | + items_in_chunk = chunk_interval[-1] - chunk_interval[0] |
| 171 | + |
| 172 | + if items_in_chunk == 0: |
| 173 | + break |
| 174 | + |
| 175 | + if items_in_chunk > items_left_to_assign: |
| 176 | + chunks_per_process[process_index].append(chunk_index) |
| 177 | + begin, end = chunk_interval |
| 178 | + intervals_per_process[process_index].append([begin, begin + items_left_to_assign]) |
| 179 | + chunk_interval = (begin + items_left_to_assign + 1, end) |
| 180 | + num_items_per_process[process_index] = 0 |
| 181 | + process_index += 1 |
| 182 | + else: |
| 183 | + chunks_per_process[process_index].append(chunk_index) |
| 184 | + intervals_per_process[process_index].append(chunk_interval) |
| 185 | + num_items_per_process[process_index] -= items_in_chunk |
| 186 | + break |
| 187 | + |
| 188 | + return chunks_per_process, intervals_per_process |
| 189 | + |
| 190 | + def __call__(self, array: np.ndarray) -> List[int]: |
| 191 | + assert self.random_state |
| 192 | + return self.random_state.permutation(array).tolist() |
0 commit comments