|
| 1 | +Stateful DataLoader Tutorial |
| 2 | +============================ |
| 3 | + |
| 4 | +Saving and loading state |
| 5 | +------------------------ |
| 6 | + |
| 7 | +Stateful DataLoader adds the ``load_state_dict``, ``state_dict`` methods to the ``torch.utils.data.DataLoader``. State fetch and set can be done as follows: |
| 8 | + |
| 9 | +.. code:: python |
| 10 | +
|
| 11 | + from torchdata.stateful_dataloader import StatefulDataLoader |
| 12 | +
|
| 13 | + dataloader = StatefulDataLoader(dataset, num_workers=2) |
| 14 | + for i, batch in enumerate(dataloader): |
| 15 | + ... |
| 16 | + if i == 10: |
| 17 | + state_dict = dataloader.state_dict() |
| 18 | + break |
| 19 | +
|
| 20 | + # Training run resumes with the previous checkpoint |
| 21 | + dataloader = StatefulDataLoader(dataset, num_workers=2) |
| 22 | + # Resume state with DataLoader |
| 23 | + dataloader.load_state_dict(state_dict) |
| 24 | + for i, batch in enumerate(dataloader): |
| 25 | + ... |
| 26 | +
|
| 27 | +Saving Custom State with Map-Style Datasets |
| 28 | +------------------------------------------- |
| 29 | + |
| 30 | +For efficient resuming of `Map-style datasets <https://pytorch.org/docs/stable/data.html#map-style-datasets>`_, you can resume iteration by defining ``state_dict`` / ``load_state_dict`` methods in your sampler. If your dataset has worker-specific state (eg RNG transform state) you can add ``state_dict`` / ``load_state_dict`` methods to your dataset. |
| 31 | + |
| 32 | +.. code:: python |
| 33 | +
|
| 34 | + from typing import * |
| 35 | + import torch |
| 36 | + import torch.utils.data |
| 37 | + from torchdata.stateful_dataloader import StatefulDataLoader |
| 38 | +
|
| 39 | + # If you are using the default RandomSampler and BatchSampler in torch.utils.data, they are patched when you import torchdata.stateful_dataloader so that defining, a custom sampler here is unnecessary |
| 40 | + class MySampler(torch.utils.data.Sampler[int]): |
| 41 | + def __init__(self, high: int, seed: int, limit: int): |
| 42 | + self.seed, self.high, self.limit = seed, high, limit |
| 43 | + self.g = torch.Generator() |
| 44 | + self.g.manual_seed(self.seed) |
| 45 | + self.i = 0 |
| 46 | +
|
| 47 | + def __iter__(self): |
| 48 | + while self.i < self.limit: |
| 49 | + val = int(torch.randint(high=self.high, size=(1,), generator=self.g)) |
| 50 | + self.i += 1 |
| 51 | + yield val |
| 52 | +
|
| 53 | + def load_state_dict(self, state_dict: Dict[str, Any]): |
| 54 | + self.i = state_dict["i"] |
| 55 | + self.g.set_state(state_dict["rng"]) |
| 56 | +
|
| 57 | + def state_dict(self) -> Dict[str, Any]: |
| 58 | + return {"i": self.i, "rng": self.g.get_state()} |
| 59 | +
|
| 60 | + # Optional: save dataset random transform state |
| 61 | + class NoisyRange(torch.utils.data.Dataset): |
| 62 | + def __init__(self, high: int, mean: float, std: float): |
| 63 | + self.high, self.mean, self.std = high, torch.tensor([float(mean)]), float(std) |
| 64 | +
|
| 65 | + def __len__(self): |
| 66 | + return self.high |
| 67 | +
|
| 68 | + def __getitem__(self, idx: int) -> float: |
| 69 | + if not (0 <= idx < self.high): |
| 70 | + raise IndexError() |
| 71 | + x = torch.normal(self.mean, self.std) |
| 72 | + noise = x.item() |
| 73 | + return idx + noise |
| 74 | +
|
| 75 | + def load_state_dict(self, state_dict): |
| 76 | + torch.set_rng_state(state_dict["rng"]) |
| 77 | +
|
| 78 | + def state_dict(self): |
| 79 | + return {"rng": torch.get_rng_state()} |
| 80 | +
|
| 81 | + # Test both single/multiprocess dataloading |
| 82 | + for num_workers in [0, 2]: |
| 83 | + print(f"{num_workers=}") |
| 84 | + dl = StatefulDataLoader(NoisyRange(5, 1, 1), sampler=MySampler(5, 1, 10), |
| 85 | + batch_size=2, drop_last=False, num_workers=num_workers) |
| 86 | +
|
| 87 | + batches = [] |
| 88 | + for i, batch in enumerate(dl): |
| 89 | + batches.append(batch) |
| 90 | + if i == 2: |
| 91 | + sd = dl.state_dict() |
| 92 | +
|
| 93 | + dl.load_state_dict(sd) |
| 94 | + batches2 = list(dl) |
| 95 | +
|
| 96 | + print(batches[3:]) |
| 97 | + print(batches2) |
| 98 | +
|
| 99 | + """ |
| 100 | + Output: |
| 101 | + num_workers=0 |
| 102 | + [tensor([-0.4526, 3.7948], dtype=torch.float64), tensor([6.5494, 3.0470], dtype=torch.float64)] |
| 103 | + [tensor([-0.4526, 3.7948], dtype=torch.float64), tensor([6.5494, 3.0470], dtype=torch.float64)] |
| 104 | + num_workers=2 |
| 105 | + [tensor([3.7412, 1.2438], dtype=torch.float64), tensor([4.4807, 4.0036], dtype=torch.float64)] |
| 106 | + [tensor([3.7412, 1.2438], dtype=torch.float64), tensor([4.4807, 4.0036], dtype=torch.float64)] |
| 107 | + """ |
| 108 | +
|
| 109 | +Saving Custom State with Iterable-Style Datasets |
| 110 | +------------------------------------------------ |
| 111 | + |
| 112 | +Tracking iteration order with `Iterable-style datasets <https://pytorch.org/docs/stable/data.html#iterable-style-datasets>`_ requires state from each worker-level instance of the dataset to be captured. You can define ``state_dict`` / ``load_state_dict`` methods on your dataset which capture worker-level state. :class:`StatefulDataLoader` will handle aggregation across workers and distribution back to the workers. Calling ``load_state_dict`` requires :class:`StatefulDataLoader`` to have same ``num_workers`` as those of the provided ``state_dict``. |
| 113 | + |
| 114 | +.. code:: python |
| 115 | +
|
| 116 | + from typing import * |
| 117 | + import torch |
| 118 | + import torch.utils.data |
| 119 | + from torchdata.stateful_dataloader import StatefulDataLoader |
| 120 | +
|
| 121 | +
|
| 122 | + class MyIterableDataset(torch.utils.data.IterableDataset): |
| 123 | + def __init__(self, high: int, seed: int): |
| 124 | + self.high, self.seed = high, seed |
| 125 | + self.g = torch.Generator() |
| 126 | + self.i = 0 |
| 127 | +
|
| 128 | + def __iter__(self): |
| 129 | + worker_info = torch.utils.data.get_worker_info() |
| 130 | + if worker_info is not None: |
| 131 | + worker_id = worker_info.id |
| 132 | + num_workers = worker_info.num_workers |
| 133 | + else: |
| 134 | + worker_id = 0 |
| 135 | + num_workers = 1 |
| 136 | + self.g.manual_seed(self.seed) |
| 137 | + arr = torch.randperm(self.high, generator=self.g) |
| 138 | + arr = arr[worker_id:self.high:num_workers] |
| 139 | + for idx in range(self.i, len(arr)): |
| 140 | + self.i += 1 |
| 141 | + yield arr[idx] |
| 142 | + self.i = 0 |
| 143 | +
|
| 144 | + def state_dict(self): |
| 145 | + return {"i": self.i} |
| 146 | +
|
| 147 | + def load_state_dict(self, state_dict): |
| 148 | + self.i = state_dict["i"] |
| 149 | +
|
| 150 | + # Test both single/multiprocess dataloading |
| 151 | + for num_workers in [0, 2]: |
| 152 | + print(f"{num_workers=}") |
| 153 | + dl = StatefulDataLoader( |
| 154 | + MyIterableDataset(12, 0), batch_size=2, drop_last=False, |
| 155 | + num_workers=num_workers) |
| 156 | +
|
| 157 | + batches = [] |
| 158 | + for i, batch in enumerate(dl): |
| 159 | + batches.append(batch) |
| 160 | + if i == 2: |
| 161 | + sd = dl.state_dict() |
| 162 | +
|
| 163 | + dl.load_state_dict(sd) |
| 164 | + batches2 = list(dl) |
| 165 | +
|
| 166 | + print(batches[3:]) |
| 167 | + print(batches2) |
| 168 | +
|
| 169 | + """ |
| 170 | + Output: |
| 171 | + num_workers=0 |
| 172 | + [tensor([ 2, 10]), tensor([3, 1]), tensor([11, 6])] |
| 173 | + [tensor([ 2, 10]), tensor([3, 1]), tensor([11, 6])] |
| 174 | + num_workers=2 |
| 175 | + [tensor([ 4, 10]), tensor([ 3, 11]), tensor([1, 6])] |
| 176 | + [tensor([ 4, 10]), tensor([ 3, 11]), tensor([1, 6])] |
| 177 | + """ |
0 commit comments