Iterable datasets with at least as many shards as processes skip and duplicate prompts in multi-process GRPO/RLOO/Distillation training
Reproduction
Runs on CPU in a few seconds with two processes, so it needs no GPU. It only iterates the training dataloader, which is what the Trainer loop feeds to _prepare_inputs, so no training step is needed. I launch it with torchrun because accelerate launch can only start several CPU processes through MPI; accelerate launch --multi_gpu itself runs torch.distributed.run, and the sharding happens in accelerator.prepare, so the launcher does not change the result.
# CUDA_VISIBLE_DEVICES="" torchrun --nproc_per_node 2 repro.py --num_shards 4
import argparse
from collections import Counter
from accelerate import PartialState
from accelerate.utils import gather_object
from datasets import Dataset
from trl import GRPOConfig, GRPOTrainer
parser = argparse.ArgumentParser()
parser.add_argument("--num_shards", type=int, required=True)
num_shards = parser.parse_args().num_shards
num_prompts = 16
dataset = Dataset.from_dict({"prompt": [f"P{i}" for i in range(num_prompts)]})
dataset = dataset.to_iterable_dataset(num_shards=num_shards) # like a streamed Hub dataset made of `num_shards` files
args = GRPOConfig(
output_dir="/tmp/repro",
report_to="none",
per_device_train_batch_size=2,
gradient_accumulation_steps=2, # steps_per_generation defaults to this
num_generations=2,
max_steps=4, # 2 ranks x 2 per device x 2 GA / 2 generations = 4 unique prompts per step -> one pass over 16
use_cpu=True,
)
trainer = GRPOTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
reward_funcs=lambda completions, **kwargs: [0.0] * len(completions),
args=args,
train_dataset=dataset,
)
# `_prepare_inputs` generates from the first batch of each `steps_per_generation` window and expects the rest of the
# window to be replays of it.
batches = [[example["prompt"] for example in batch] for batch in trainer.get_train_dataloader()]
generated_on = batches[:: args.steps_per_generation]
state = PartialState()
per_rank = gather_object([(state.process_index, batches, generated_on)])
if state.is_main_process:
counts = Counter()
for rank, rank_batches, rank_generated_on in per_rank:
print(f"rank {rank} micro-batches: {rank_batches}")
counts.update(prompt for batch in rank_generated_on for prompt in set(batch))
never = [f"P{i}" for i in range(num_prompts) if f"P{i}" not in counts]
twice = sorted(prompt for prompt, count in counts.items() if count > 1)
print(f"trained on {len(counts)}/{num_prompts} prompts; never seen: {never}; seen more than once: {twice}")
With --num_shards 1, every prompt is used once, and each window is one batch replayed:
rank 0 micro-batches: [['P6', 'P6', 'P15', 'P15'], ['P6', 'P6', 'P15', 'P15'], ['P9', 'P9', 'P3', 'P3'], ['P9', 'P9', 'P3', 'P3'], ...]
rank 1 micro-batches: [['P11', 'P11', 'P10', 'P10'], ['P11', 'P11', 'P10', 'P10'], ['P0', 'P0', 'P7', 'P7'], ['P0', 'P0', 'P7', 'P7'], ...]
trained on 16/16 prompts; never seen: []; seen more than once: []
With --num_shards 4, each window holds two different batches, so half the prompts are never generated on and the other half are generated on twice:
rank 0 micro-batches: [['P15', 'P15', 'P8', 'P8'], ['P14', 'P14', 'P11', 'P11'], ['P15', 'P15', 'P8', 'P8'], ['P14', 'P14', 'P11', 'P11'], ...]
rank 1 micro-batches: [['P7', 'P7', 'P0', 'P0'], ['P6', 'P6', 'P3', 'P3'], ['P7', 'P7', 'P0', 'P0'], ['P6', 'P6', 'P3', 'P3'], ...]
trained on 8/16 prompts; never seen: ['P1', 'P3', 'P4', 'P6', 'P9', 'P11', 'P12', 'P14']; seen more than once: ['P0', 'P10', 'P13', 'P15', 'P2', 'P5', 'P7', 'P8']
No error or warning is raised.
Cause
In the reproduction, each rank generates from 2 unique prompts per window (per_device_train_batch_size=2 × steps_per_generation=2 = 4 completions, / num_generations=2), so 4 unique prompts across both ranks. get_train_dataloader passes this global count to repeat_iterable_dataset, which builds blocks of 4 prompts, repeats each prompt num_generations times, and repeats the block steps_per_generation times:
[P6 P6 P15 P15 P11 P11 P10 P10] [P6 P6 P15 P15 P11 P11 P10 P10]
With dispatch_batches=False (forced for iterable datasets), Accelerate splits the stream across ranks in one of two ways. The threshold depends on the Accelerate version: n_shards >= num_processes since 1.14, n_shards > num_processes before.
- Fewer shards than the threshold: every rank reads the full stream above through
IterableDatasetShardand takes its part of each chunk. Each window is one batch repeated, as_prepare_inputsexpects:rank 0: [P6 P6 P15 P15], [P6 P6 P15 P15] rank 1: [P11 P11 P10 P10], [P11 P11 P10 P10] - At or above the threshold: Accelerate calls
dataset.shard(num_processes, index), so each rank reads only its own shards, andrepeat_iterable_datasetruns on each rank separately, still with the global block of 4 prompts. Each window now holds two different batches:rank 0: [P15 P15 P8 P8], [P14 P14 P11 P11], [P15 P15 P8 P8], [P14 P14 P11 P11], ..._prepare_inputsgenerates from the first batch of each window and ignores the rest, so P15 and P8 are trained on twice and P14 and P11 never.
The block size is right when all ranks share one stream, but too big when each rank reads its own shards.
GRPO and RLOO share this code. DistillationTrainer uses the same pattern (global generation_batch_size, repeat_count=gradient_accumulation_steps); I checked that one by reading the code, not by running it.
Fix
I've opened #7697, where I explained the solution.
The downside is that TRL copies a rule from Accelerate's internals, which already changed once (in 1.14). Happy to change the approach if you'd prefer something else.
How did you hit this?
I did not hit this in a real run. Cursor Bugbot flagged the pattern while reviewing my PR adding iterable dataset support to GOLD (#6438), which copies the GRPO code, and I confirmed it with the reproduction above.
A user would hit it by training GRPO, RLOO or Distillation on more than one GPU with a streamed Hub dataset that has at least as many files as GPUs (more files than GPUs before Accelerate 1.14). With N processes, only about 1/N of the stream is trained on, the rest is trained on repeatedly, and nothing in the logs says so. On a single GPU, or with a dataset that has fewer shards than processes, training is unaffected.
System Info
- Platform: Linux-7.0.0-38-generic-x86_64-with-glibc2.39
- Python version: 3.13.5
- TRL version: 1.16.0.dev0+b32aaa8
- PyTorch version: 2.13.0
- accelerator(s): NVIDIA GeForce RTX 5070 Ti (the reproduction runs on CPU)
- Transformers version: 5.19.0
- Accelerate version: 1.15.0
- Datasets version: 5.1.0
- HF Hub version: 2.2.0
- bitsandbytes version: 0.50.2
- DeepSpeed version: 0.19.7
- Liger-Kernel version: 0.8.4
- PEFT version: 0.21.2
- vLLM version: 0.29.0
I independently reproduced the data-shard discrepancy on TRL 1.15.0 with two CPU ranks. With one shard, the test saw 16/16 prompts; with four shards, only 8/16 were seen. This is an iteration-level reproduction, not a demonstrated training-quality impact or an upstream fix. I didn't test main because that path needed Triton in this environment.
Evidence: https://aibadgr.com/evidence/trl-7690-iterable-dataset-shards-skip-and-duplicate-prompts
I'm building Badgr to run and verify bounded CPU/GPU training workloads. If you have a real distributed training/evaluation job needing reproducible execution, I can offer $5 in eligible trial credits for a small test. Would that help?