Build iterator for each epoch. This class simply creates pytorch DataLoader except for the following points: - The random seed is decided according to the number of epochs. This feature guarantees reproducibility when resuming from middle of training process. - Enable to restrict
| 33 | |
| 34 | |
| 35 | class SequenceIterFactory(AbsIterFactory): |
| 36 | """Build iterator for each epoch. |
| 37 | |
| 38 | This class simply creates pytorch DataLoader except for the following points: |
| 39 | - The random seed is decided according to the number of epochs. This feature |
| 40 | guarantees reproducibility when resuming from middle of training process. |
| 41 | - Enable to restrict the number of samples for one epoch. This features |
| 42 | controls the interval number between training and evaluation. |
| 43 | |
| 44 | """ |
| 45 | |
| 46 | @typechecked |
| 47 | def __init__( |
| 48 | self, |
| 49 | dataset, |
| 50 | batches: Union[AbsSampler, Sequence[Sequence[Any]]], |
| 51 | num_iters_per_epoch: Optional[int] = None, |
| 52 | seed: int = 0, |
| 53 | shuffle: bool = False, |
| 54 | shuffle_within_batch: bool = False, |
| 55 | num_workers: int = 0, |
| 56 | collate_fn=None, |
| 57 | pin_memory: bool = False, |
| 58 | ): |
| 59 | |
| 60 | if not isinstance(batches, AbsSampler): |
| 61 | self.sampler = RawSampler(batches) |
| 62 | else: |
| 63 | self.sampler = batches |
| 64 | |
| 65 | self.dataset = dataset |
| 66 | self.num_iters_per_epoch = num_iters_per_epoch |
| 67 | self.shuffle = shuffle |
| 68 | self.shuffle_within_batch = shuffle_within_batch |
| 69 | self.seed = seed |
| 70 | self.num_workers = num_workers |
| 71 | self.collate_fn = collate_fn |
| 72 | # https://discuss.pytorch.org/t/what-is-the-disadvantage-of-using-pin-memory/1702 |
| 73 | self.pin_memory = pin_memory |
| 74 | |
| 75 | def build_iter(self, epoch: int, shuffle: bool = None) -> DataLoader: |
| 76 | if shuffle is None: |
| 77 | shuffle = self.shuffle |
| 78 | |
| 79 | if self.num_iters_per_epoch is not None: |
| 80 | N = len(self.sampler) |
| 81 | # If corpus size is larger than the num_per_epoch |
| 82 | if self.num_iters_per_epoch < N: |
| 83 | N = len(self.sampler) |
| 84 | real_epoch, offset = divmod(self.num_iters_per_epoch * epoch, N) |
| 85 | |
| 86 | if offset >= self.num_iters_per_epoch: |
| 87 | current_batches = self.sampler.generate(real_epoch + self.seed) |
| 88 | if shuffle: |
| 89 | np.random.RandomState(real_epoch + self.seed).shuffle( |
| 90 | current_batches |
| 91 | ) |
| 92 | batches = current_batches[ |
no outgoing calls
searching dependent graphs…