accelerate icon indicating copy to clipboard operation
accelerate copied to clipboard

BatchSamplerShard.__len__ overcounts for some ranks when split_batches=True and even_batches=False

Open ErenAta16 opened this issue 4 months ago • 6 comments

System Info

Reproduced against the current main branch source of src/accelerate/data_loader.py (BatchSamplerShard), with torch installed locally. Pure CPU-side logic, no distributed launch or GPU needed to reproduce.

Information

  • [x] The official example scripts
  • [ ] My own modified scripts

Tasks

  • [ ] One of the scripts in the examples/ folder of Accelerate or an officially supported no_trainer script in the examples folder of the transformers repo (such as run_no_trainer_glue.py)
  • [x] My own task or dataset (give details below)

Reproduction

BatchSamplerShard.__len__ reports the wrong length when split_batches=True and even_batches=False, whenever the underlying sampler's length isn't evenly divisible.

from torch.utils.data import BatchSampler, SequentialSampler
from accelerate.data_loader import BatchSamplerShard

sampler = SequentialSampler(range(3))
batch_sampler = BatchSampler(sampler, batch_size=2, drop_last=False)  # yields [0,1], [2]

for p in (0, 1):
    shard = BatchSamplerShard(
        batch_sampler,
        num_processes=2,
        process_index=p,
        split_batches=True,
        even_batches=False,
    )
    print(f"process_index={p}: len(shard)={len(shard)}, actual batches={list(shard)}")

Output:

process_index=0: len(shard)=2, actual batches=[[0], [2]]
process_index=1: len(shard)=2, actual batches=[[1]]

For process_index=1, len(shard) reports 2 but iterating only yields 1 batch.

I also ran a broader sweep across dataset sizes 1-19, batch sizes 2/4/6, and process counts 2/3 (171 combinations with split_batches=True, even_batches=False): 50 of them show this same len(shard) != len(list(shard)) mismatch.

Root cause

BatchSamplerShard.__len__ (src/accelerate/data_loader.py):

def __len__(self):
    if self.split_batches:
        # Split batches does not change the length of the batch sampler
        return len(self.batch_sampler)
    ...

When split_batches=True, this unconditionally returns len(self.batch_sampler) for every process, regardless of even_batches.

But _iter_with_split (the actual iteration path used when split_batches=True) does not give every process the same number of batches when even_batches=False:

if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size:
    if not self.even_batches:
        if len(batch) > batch_length * self.process_index:
            yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)]
    else:
        ...

The last, partial batch is only yielded to processes whose slice actually fits inside it. With even_batches=False, some processes get one fewer batch than __len__ claims, exactly like the split_batches=False branch already accounts for via its process_index < len(self.batch_sampler) % self.num_processes check a few lines below, that same process-index-dependent logic isn't applied in the split_batches=True branch.

Expected behavior

len(shard) should equal len(list(shard)) for every process index, the same invariant that already holds for split_batches=False. For the reproduction above, process_index=1 should report len(shard)=1 to match what iteration actually yields.

Impact

I only verified the length/iteration mismatch itself, not a full distributed training run, but the likely downstream effect: len(dataloader) built on top of this is used for progress bars, math.ceil(len(dataloader) / gradient_accumulation_steps)-style step counting, and LR scheduler total-step computation. Since the mismatch is process-index-dependent (some ranks get the "true" count, others are overcounted by one), a training loop that iterates len(dataloader) times per rank could see the affected rank's iterator raise StopIteration one step early while other ranks continue, which in a distributed run with synchronized collectives (gradient all-reduce, etc.) would likely stall the remaining ranks. I haven't reproduced that end-to-end hang, just the underlying length/iteration mismatch that would cause it.

ErenAta16 avatar Jul 17 '26 00:07 ErenAta16

Hi, I'd like to investigate and fix this BatchSamplerShard.len mismatch logic. Could you please assign this issue to me?

lokeshps321 avatar Jul 28 '26 12:07 lokeshps321

Hey @lokeshps321, thanks for offering to take this on, always good to see someone pick up a niggly sharding bug.

Heads up before you sink time into it though: @pepepeboom already has #4127 open against this issue since Jul 18 (data_loader.py +9/-2 plus a test). It hasn't been reviewed yet, so it's not merged, but the fix is written. I'd hate for you to redo work that's already sitting there.

I'm not the maintainer so I can't assign anyone, that's up to the accelerate folks. A couple of ways you could jump in that wouldn't collide:

  • Review #4127. It's been sitting a week and a half with no eyes on it, and a second opinion on the even_batches=False + split_batches=True arithmetic would probably help it land faster than a competing PR would. The bit I'd want checked is whether the length now matches actual iteration for every rank, not just the ones that were previously overcounted.
  • If #4127 goes stale and the author doesn't come back, picking it up then is fair game and nobody would object.

Either way, if you do end up working on it, the repro in the issue body is self-contained (no distributed launch needed, just construct the sharded sampler and compare len() against the actual number of yielded batches per process_index), so you can iterate on it quickly.

Also worth flagging for whoever reviews: I only verified the length/iteration mismatch itself, not an end-to-end distributed hang. So the fix should be judged on making __len__ agree with iteration, not on the downstream stall I speculated about.

ErenAta16 avatar Jul 28 '26 15:07 ErenAta16

Thanks for the heads-up! I'll take a look at PR #4127 and review it.

lokeshps321 avatar Jul 28 '26 17:07 lokeshps321

Sounds good. One concrete thing to check while you're in there, since it's the part most likely to be wrong and least likely to be covered:

__len__ should agree with actual iteration for every process_index, not only the ranks that were previously overcounted. The original bug is process-index-dependent, so a fix can easily correct the over-counting ranks while leaving another rank off by one in the other direction, and both a single-process test and a "does the total add up" test would pass.

The cheapest way to check that is empirical rather than by reading the arithmetic: for each rank, build the sharded sampler and compare len(sampler) against sum(1 for _ in sampler). Run it across the grid of split_batches x even_batches x a dataset size that doesn't divide evenly by num_processes, since the remainder handling is where the discrepancy lives. No distributed launch needed, you can instantiate the sampler directly with an explicit process_index.

Also worth flagging for @pepepeboom: the issue as I filed it only documents the length/iteration mismatch. I speculated about a downstream distributed hang but never reproduced it, so the PR should be judged on making __len__ match iteration, not on the hang.

ErenAta16 avatar Jul 28 '26 20:07 ErenAta16

Hey @ErenAta16, I checked out PR #4127 and verified the fix locally like you suggested. Here is what I tested:

Ran pytest tests/test_data_loader.py — all 28 tests passed. Wrote a Python script to sweep across dataset sizes 1–30, batch sizes (2, 4, 6), and process counts (2, 3) on CPU, Verified len(shard) == sum(1 for _ in shard) for all process ranks across every combination of split_batches, even_batches, and drop_last (~2,800 total configs tested), The length matches the actual iteration count for every rank with 0 mismatches. Fix looks good to merge.

lokeshps321 avatar Jul 30 '26 16:07 lokeshps321

This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the contributing guidelines are likely to be ignored.

github-actions[bot] avatar Aug 24 '26 15:08 github-actions[bot]