Resuming with load_state + skip_first_batches (checkpointing example) does not restore the shuffle order
System Info
- `Accelerate` version: 1.15.0 (also checked: `main` is unchanged in the relevant code)
- Platform: macOS-27.0-arm64-arm-64bit (CPU only)
- Python version: 3.12.8
- Numpy version: 2.5.3
- PyTorch version: 2.14.0
- torchdata: 0.11.0
- `Accelerate` default config: none (Accelerator(cpu=True) in the script)Information
- The official example scripts
- My own modified scripts
Tasks
- One of the scripts in the examples/ folder of Accelerate or an officially supported
no_trainerscript in theexamplesfolder of thetransformersrepo (such asrun_no_trainer_glue.py) - My own task or dataset (give details below)
Reproduction
The resume pattern of examples/by_feature/checkpointing.py is load_state, then skip_first_batches(dl, n) for the resumed epoch, then the original loader for later epochs. With shuffle=True it does not continue the data order of the uninterrupted run. A single process on CPU reproduces it in a few seconds:
# python repro.py save [--seedable] && python repro.py resume [--seedable]
import sys
import torch
from torch.utils.data import DataLoader
from accelerate import Accelerator
from accelerate.utils import DataLoaderConfiguration, set_seed
MODE, SEEDABLE = sys.argv[1], "--seedable" in sys.argv
EPOCHS, SAVE_AT = 2, 3 # checkpoint after 3 batches of epoch 0
accelerator = Accelerator(cpu=True, dataloader_config=DataLoaderConfiguration(use_seedable_sampler=SEEDABLE))
set_seed(42)
dl = accelerator.prepare(DataLoader(list(range(32)), batch_size=4, shuffle=True))
if MODE == "save":
batches = []
for epoch in range(EPOCHS):
for step, batch in enumerate(dl):
batches.append(batch.tolist())
if epoch == 0 and step + 1 == SAVE_AT:
accelerator.save_state("ckpt")
torch.save(batches, "uninterrupted.pt")
else:
accelerator.load_state("ckpt")
batches = []
for epoch in range(EPOCHS):
# the resume pattern of examples/by_feature/checkpointing.py
active = accelerator.skip_first_batches(dl, SAVE_AT) if epoch == 0 else dl
batches += [batch.tolist() for batch in active]
full, per_epoch = torch.load("uninterrupted.pt"), len(dl)
expected = full[SAVE_AT:] # what the uninterrupted run trained on after the checkpoint
for name, got, exp in (("rest of epoch 0", batches[: per_epoch - SAVE_AT], expected[: per_epoch - SAVE_AT]),
("epoch 1", batches[per_epoch - SAVE_AT :], expected[per_epoch - SAVE_AT :])):
g, e = {i for b in got for i in b}, {i for b in exp for i in b}
print(f"{name}: same order {got == exp}; {len(g - e)} samples not in the uninterrupted run, {len(e - g)} missing")
print("resumed epoch 1 == uninterrupted epoch 0:", batches[per_epoch - SAVE_AT :] == full[:per_epoch])Default sampler:
rest of epoch 0: same order False; 6 samples not in the uninterrupted run, 6 missing
epoch 1: same order False; 0 samples not in the uninterrupted run, 0 missing
resumed epoch 1 == uninterrupted epoch 0: FalseWith --seedable (use_seedable_sampler=True):
rest of epoch 0: same order True; 0 samples not in the uninterrupted run, 0 missing
epoch 1: same order False; 0 samples not in the uninterrupted run, 0 missing
resumed epoch 1 == uninterrupted epoch 0: TrueThere are two separate problems:
- Default sampler.
RandomSamplerdraws its permutation when iteration starts, so a mid-epochsave_statestores RNG state from after the current epoch's draw. Afterload_state, the skipped loader draws a new permutation, which is the one the next epoch would have used, and then skipsnbatches of it. The rest of the epoch repeats samples that were already trained on and drops others. Keeping the global RNG unchanged acrossload_statemakes the resumed epoch exact. use_seedable_sampler=True. The resumed epoch is correct, but the loader returned byskip_first_batchescarries the epoch counter (#4071), while the original prepared loader'siterationnever advances. The nextfor batch in dltherefore callsset_epochwith the resumed epoch again, and epoch 1 replays epoch 0's permutation. Setting the returned loader'siterationto the checkpointed epoch, and the source loader's to epoch + 1, makes it exact.
With 2 processes (gloo, CPU), the default sampler also replays epoch 0's permutation at the restored position when the checkpoint falls inside epoch ≥ 1. Restoring the epoch counter doesn't fix that case. It is consistent with the sampler generator's state not being part of the checkpoint.
Closed PRs #4232 and #4233 described these mechanisms, and #4233 notes that examples/by_feature/checkpointing.py has exactly this shape. Neither was merged, and I found no open issue tracking this. #4238 addresses only the use_stateful_dataloader path. Its description says single-process runs are unaffected, which the first case above contradicts.
Possible directions, for the maintainers to choose from:
- In
save_state/load_state, persist each prepared dataloader's epoch counter and the sampler generator state as of the start of the current epoch, soskip_first_batchesskips within the right permutation. This was the approach of #4232/#4233. - When the loader returned by
skip_first_batchesfinishes, advance the source loader'siteration, so the next epoch does not repeat the resumed permutation. - At minimum, note in
examples/by_feature/checkpointing.pyand the checkpointing guide that this pattern does not resume the shuffle order, and say which configuration does.
Expected behavior
After load_state + skip_first_batches, the rest of the resumed epoch and every later epoch yield the same batches, in the same order, as the uninterrupted run.
Source: huggingface/accelerate