Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions test/stateful_dataloader/test_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,10 @@ def test_sampler_state_dict(self):
def test_sampler_load_state_dict(self):

sampler = StatefulDistributedSampler(self.dataset, num_replicas=10, rank=0)
sampler.load_state_dict({"yielded": 3})
sampler.load_state_dict({"epoch": 0, "yielded": 3})
self.assertEqual(sampler.next_yielded, 3)
with self.assertRaises(ValueError):
sampler.load_state_dict({"yielded": -1})
sampler.load_state_dict({"epoch": 0, "yielded": -1})

def test_sampler_next_yielded(self):

Expand All @@ -108,7 +108,12 @@ def test_sampler_next_yielded(self):
next(iterator) # advance the iterator
self.assertEqual(sampler.yielded, 1)
self.assertIsNone(sampler.next_yielded)
sampler.load_state_dict({StatefulDistributedSampler._YIELDED: 5})
sampler.load_state_dict(
{
StatefulDistributedSampler._EPOCH: 0,
StatefulDistributedSampler._YIELDED: 5,
}
)
self.assertEqual(sampler.next_yielded, 5)
iterator = iter(sampler)
next(iterator) # advance the iterator again
Expand Down
6 changes: 5 additions & 1 deletion torchdata/stateful_dataloader/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ def __iter__(self):

class StatefulDistributedSampler(torch.utils.data.distributed.DistributedSampler):
_YIELDED = "yielded"
_EPOCH = "epoch"

def __init__(
self,
Expand All @@ -206,9 +207,12 @@ def __iter__(self):
yield idx

def state_dict(self) -> Dict[str, Any]:
return {self._YIELDED: self.yielded}
return {self._YIELDED: self.yielded, self._EPOCH: self.epoch, "NEXT_YIELDED": self.next_yielded}

def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
if self._EPOCH not in state_dict:
raise ValueError("Invalid state_dict")
self.set_epoch(state_dict[self._EPOCH])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If users are used to calling set_epoch in a certain in the main loop, then doing self.set_epoch(..) on load_state_dict might interfere with that ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the user is trying to set_epoch to something other than what was previously saved, then they are likely going to get repeated indices in the current epoch, which seems like broken behaviour. Perhaps we should warn in that case.

if self._YIELDED not in state_dict:
raise ValueError("Invalid state_dict")
if state_dict[self._YIELDED] < 0:
Expand Down