Workers, Pinned Memory & Samplers

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A GPU that waits for the next batch is an expensive space heater. Once a model is correct, the next question is almost always whether the input pipeline can keep the accelerator busy. This page covers the knobs of torch.utils.data.DataLoader that control throughput (worker processes, prefetching, pinned memory), the pitfalls of multi-process loading (per-worker randomness, dataset copies, pickling), the sampler classes that decide which indices are drawn, and the StatefulDataLoader from torchdata for mid-epoch checkpointing. How to write a Dataset and the basic DataLoader arguments are in Datasets & DataLoader; here we assume you already have one.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) and torchdata 0.11 on 2026-10-31, as scripts, so the multi-worker examples also ran under the spawn start method of macOS; the DistributedSampler example ran in a single-process Gloo group. Timings are something you must measure yourself, with the tools in Profiling with torch.profiler.

The DataLoader signature

The 2.15 reference gives the following signature:

DataLoader(dataset, batch_size=1, shuffle=None, sampler=None, batch_sampler=None,
           num_workers=0, collate_fn=None, pin_memory=False, drop_last=False,
           timeout=0, worker_init_fn=None, multiprocessing_context=None,
           generator=None, *, prefetch_factor=None, persistent_workers=False,
           pin_memory_device='', in_order=True)

Note that prefetch_factor, persistent_workers, pin_memory_device and in_order are keyword-only. The performance options are described one by one below.

flowchart LR S["Sampler: yields indices"] --> W1["worker 0: fetch + collate"] S --> W2["worker 1: fetch + collate"] S --> W3["worker N-1: fetch + collate"] W1 --> Q["queue of ready batches"] W2 --> Q W3 --> Q Q --> P["pin-memory thread (optional)"] P --> M["main process: training loop"] M --> G["batch.to(device, non_blocking=True)"]

With num_workers=0 everything in the diagram except the sampler happens in the main process, serially with the training step. With num_workers greater than zero each worker is a separate process that receives a batch of indices, reads the samples, runs the dataset transforms and the collate_fn, and returns the finished batch to the main process.

Worker processes: num_workers

num_workers is the number of loader processes. The default 0 loads data in the main process; a positive integer starts that many workers every time an iterator is created (that is, at the start of every for batch in loader loop unless persistent_workers is set).

Guidelines that follow from how the loader works:

  • Start with a small number (2 to 4 per GPU) and measure samples per second; raise it until the GPU is no longer starved or until you run out of CPU cores. More workers than cores does not help.

  • Each worker holds its own copy of the dataset object. A dataset that stores a large in-memory list of Python objects is duplicated in every worker (copy-on-write pages are touched by reference counting). Store large data in NumPy arrays or tensors, memory-mapped files or an on-disk format so that workers share pages.

  • Workers are processes, so the dataset, the collate_fn and worker_init_fn must be picklable when the start method is spawn (the default on Windows and macOS). Lambdas and locally defined functions fail with a pickling error.

  • On platforms using spawn, wrap the script entry point in if __name__ == "__main__":, otherwise each worker re-executes the training script.

  • Debugging is easier with num_workers=0: exceptions then come with a normal traceback instead of being re-raised from a worker.

  • Avoid launching CUDA work inside the dataset or inside a worker. Workers should produce CPU tensors; the main process moves them to the device.

  • If workers use libraries that spawn their own threads (OpenCV, NumPy with a threaded BLAS), limit those threads inside worker_init_fn, otherwise many workers times many threads oversubscribes the CPU.

multiprocessing_context accepts a start-method string such as "fork", "spawn" or "forkserver", or a context object. The default is the operating-system default. timeout (default 0, meaning wait forever) sets how long the main process waits for a batch from workers.

Prefetching and persistent workers

prefetch_factor is the number of batches each worker loads in advance. It is None when num_workers=0 and defaults to 2 otherwise, so the loader buffers num_workers * prefetch_factor batches. Setting it with num_workers=0 raises an error. Increase it when per-batch latency is bursty (network storage) and memory allows.

persistent_workers=True keeps the worker processes alive after a pass over the dataset instead of shutting them down and starting new ones for the next epoch. It removes the start-up cost, which is visible with expensive imports or datasets that are slow to initialise, and it requires num_workers > 0. The price is that the dataset instances (and whatever they cache) stay in memory between epochs, and that a worker-side state such as a random generator continues across epochs rather than restarting.

in_order=True (the default) delivers batches in the order the sampler produced them. Setting in_order=False lets a fast worker deliver first, which can reduce stalls with uneven sample cost but makes the batch order, and therefore reproducibility, depend on timing (see Reproducibility & Determinism).

import torch
from torch.utils.data import DataLoader, Dataset


class SyntheticImages(Dataset):
    def __init__(self, n: int = 10_000):
        self.n = n

    def __len__(self) -> int:
        return self.n

    def __getitem__(self, idx: int):
        g = torch.Generator().manual_seed(idx)  # deterministic per sample
        return torch.randn(3, 64, 64, generator=g), idx % 10


def make_loader(train: bool = True) -> DataLoader:
    return DataLoader(
        SyntheticImages(),
        batch_size=128,
        shuffle=train,
        drop_last=train,            # keep batch shapes constant for training
        num_workers=4,
        prefetch_factor=4,
        persistent_workers=True,
        pin_memory=torch.cuda.is_available(),
    )


if __name__ == "__main__":
    loader = make_loader()
    for epoch in range(2):
        for x, y in loader:
            pass

Pinned memory and non_blocking transfers

A tensor in ordinary (pageable) host memory can be swapped out by the operating system, so a copy to the GPU first goes through a temporary staging buffer. Pinned (page-locked) memory cannot be swapped, which allows faster and more predictable host-to-device copies and is the prerequisite for copies that overlap with computation.

DataLoader(pin_memory=True) makes the loader copy each fetched batch into pinned memory in a separate thread of the main process, so the pinning does not block the training loop. In 2.15 the current accelerator is used for pinning; the pin_memory_device argument is deprecated. A custom batch type is pinned only if it defines a pin_memory() method (the default collate output of tensors, tuples, lists and dicts is handled automatically).

The second half is tensor.to(device, non_blocking=True). A non-blocking copy returns to Python immediately instead of waiting for the transfer, so many transfers can be queued and the program synchronises once later. The official guide on non_blocking and pin_memory() makes several points worth remembering:

  • Pinning a pageable tensor yourself right before a transfer usually does not pay off: pinning is itself a blocking host operation, and in its benchmarks the combined pin-then-copy path was often slower than a plain copy. Let the DataLoader pin in its background thread instead.

  • non_blocking=True can help even with pageable memory (it skips a host-side synchronisation), but true overlap of a copy with kernels needs a pinned source, a non-default stream and a GPU copy engine that is free.

  • If you modify a pinned source tensor after queuing a non-blocking CPU-to-GPU copy, the GPU may receive corrupted data. Do not reuse or mutate a source buffer until the copy is known to be complete.

  • A non-blocking GPU-to-CPU copy must be followed by an explicit synchronisation (for example torch.cuda.synchronize() or an event) before the CPU reads the data, otherwise it may read stale values.

  • Pinned memory is scarce, locked RAM; pinning too much can starve other processes. Benchmark on your hardware: few or very small tensors gain little.

import torch

if __name__ == "__main__":
    device = torch.accelerator.current_accelerator() or torch.device("cpu")
    loader = make_loader()  # pin_memory=True when CUDA is available

    model = torch.nn.Sequential(torch.nn.Flatten(), torch.nn.Linear(3 * 64 * 64, 10)).to(device)

    for x, y in loader:
        x = x.to(device, non_blocking=True)
        y = y.to(device, non_blocking=True)
        logits = model(x)
        break

Collation: collate_fn and batching

The collate_fn turns a list of samples into one batch. The default, default_collate, adds a leading batch dimension, converts NumPy arrays and Python numbers to tensors and preserves the structure of dicts, tuples and namedtuples. When automatic batching is disabled (batch_size=None) the loader uses default_convert instead and each sample is returned as-is (converted to tensors).

A custom collate_fn is the right place for variable-length data, for example padding text sequences. Doing the padding there, per batch, is much cheaper than padding the whole dataset to the global maximum length.

import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader


def collate_padded(batch):
    seqs, labels = zip(*batch)
    lengths = torch.tensor([len(s) for s in seqs])
    padded = pad_sequence(seqs, batch_first=True, padding_value=0)
    return padded, lengths, torch.tensor(labels)


data = [(torch.randint(1, 100, (n,)), n % 2) for n in (5, 9, 3, 7)]
loader = DataLoader(data, batch_size=2, collate_fn=collate_padded)
for padded, lengths, labels in loader:
    print(padded.shape, lengths.tolist(), labels.tolist())

The collate_fn runs in the worker processes, so it must be a module-level function when spawn is used.

Randomness and per-worker state

Each worker gets a distinct seed derived from the base seed of the loader, and PyTorch seeds its own generator in the worker with it. Other libraries are not seeded for you in a way that differs between workers, and a classic pitfall is a NumPy or random based augmentation that produces identical "random" values in every worker. worker_init_fn(worker_id) is called in each worker after seeding and before data loading; torch.utils.data.get_worker_info() returns the worker id, the number of workers, the seed and the worker’s dataset copy (it returns None in the main process).

import random

import numpy as np
import torch
from torch.utils.data import DataLoader, IterableDataset, get_worker_info


def seed_worker(worker_id: int) -> None:
    worker_seed = torch.initial_seed() % 2**32
    np.random.seed(worker_seed)
    random.seed(worker_seed)


class Stream(IterableDataset):
    """Each worker must read a different shard, otherwise samples repeat."""

    def __init__(self, n: int = 100):
        self.n = n

    def __iter__(self):
        info = get_worker_info()
        if info is None:                 # single-process loading
            start, step = 0, 1
        else:                            # shard by worker id
            start, step = info.id, info.num_workers
        yield from range(start, self.n, step)


if __name__ == "__main__":
    g = torch.Generator()
    g.manual_seed(0)

    loader = DataLoader(Stream(), batch_size=10, num_workers=2,
                        worker_init_fn=seed_worker, generator=g)
    print([b.tolist() for b in loader][:2])

For an IterableDataset, every worker gets a copy of the same iterator, so without sharding by get_worker_info() each sample is returned num_workers times. The generator argument of the loader seeds the sampler and the base seed of the workers, which is what makes a seeded run repeatable.

Samplers

A sampler yields dataset indices; a batch sampler yields lists of indices. The relevant arguments interact: shuffle=True creates a RandomSampler, shuffle=False a SequentialSampler, and passing an explicit sampler is mutually exclusive with shuffle. batch_sampler is mutually exclusive with batch_size, shuffle, sampler and drop_last.

Class Behaviour

SequentialSampler

Indices in order. Default for evaluation.

RandomSampler

Random permutation; optionally with replacement, a fixed num_samples and a generator.

SubsetRandomSampler

Random order over a given list of indices (a cheap way to make train/validation splits of one dataset).

WeightedRandomSampler

Draws indices with probabilities given by weights; used for imbalanced classes. Not normalised: weights need not sum to one.

BatchSampler

Wraps another sampler and yields lists of indices of size batch_size; used for datasets that can fetch a whole batch at once.

DistributedSampler

Gives each process a disjoint shard in distributed training. Call set_epoch(epoch) every epoch or the shuffling order will repeat.

import torch
from torch.utils.data import DataLoader, TensorDataset, WeightedRandomSampler

torch.manual_seed(0)

# 900 samples of class 0 and 100 of class 1.
labels = torch.cat([torch.zeros(900, dtype=torch.long), torch.ones(100, dtype=torch.long)])
features = torch.randn(1000, 8)
ds = TensorDataset(features, labels)

class_counts = torch.bincount(labels)
sample_weights = (1.0 / class_counts.float())[labels]   # rare class gets larger weight

sampler = WeightedRandomSampler(sample_weights, num_samples=len(ds), replacement=True)
loader = DataLoader(ds, batch_size=100, sampler=sampler)

_, y = next(iter(loader))
print("fraction of class 1 in a batch:", y.float().mean().item())  # 0.62 here; 0.5 on average

Re-sampling with WeightedRandomSampler changes the training distribution, so predicted probabilities become miscalibrated for the real class balance; alternatives are class weights in the loss (see Loss Functions) or threshold adjustment afterwards. The theory of imbalance and calibration is in Problem Framing & ML Projects.

DistributedSampler

In data-parallel training each process must see a different slice of the data. DistributedSampler(dataset, num_replicas, rank, shuffle=True, seed=0, drop_last=False) splits indices across ranks; when the dataset size is not divisible it pads by repeating indices unless drop_last=True. The shuffle is seeded from seed + epoch, so you must call sampler.set_epoch(epoch) at the start of each epoch; forgetting it makes every epoch use the same order. Launching and the process groups are covered in DistributedDataParallel.

from torch.utils.data import DataLoader, DistributedSampler

sampler = DistributedSampler(train_ds, shuffle=True, seed=0)
loader = DataLoader(train_ds, batch_size=64, sampler=sampler, num_workers=4)

for epoch in range(num_epochs):
    sampler.set_epoch(epoch)      # different shuffle each epoch
    for x, y in loader:
        ...

Resumable loading with StatefulDataLoader

A plain DataLoader cannot be checkpointed: after a crash you can restore the model and optimizer, but the loader restarts the epoch from batch zero. The torchdata package provides torchdata.stateful_dataloader.StatefulDataLoader, documented as a drop-in replacement for torch.utils.data.DataLoader with the same arguments plus snapshot_every_n_steps (default 1, how often worker state is passed to the loader). It adds state_dict() and load_state_dict() for mid-epoch checkpointing. By default the state records the number of batches yielded and resuming fast-forwards the sampler or dataset by that count; if the sampler or dataset defines its own state methods, those are used. State is gathered across the worker processes but not across ranks, so in distributed training each rank saves its own loader state. For large dataset state, raise snapshot_every_n_steps to match your checkpoint frequency.

pip install torchdata
import torch
from torchdata.stateful_dataloader import StatefulDataLoader

if __name__ == "__main__":
    loader = StatefulDataLoader(SyntheticImages(), batch_size=64, num_workers=2,
                                snapshot_every_n_steps=100)

    it = iter(loader)
    for step, (x, y) in enumerate(it):
        if step == 100:                 # 157 batches per epoch here
            torch.save(loader.state_dict(), "loader_state.pt")
            break

    # Later, in a new process: rebuild the loader and resume mid-epoch.
    resumed = StatefulDataLoader(SyntheticImages(), batch_size=64, num_workers=2,
                                 snapshot_every_n_steps=100)
    resumed.load_state_dict(torch.load("loader_state.pt"))
    for x, y in resumed:
        ...  # continues after batch 100

Saving it with torch.load later uses the safe weights_only=True default for plain data (see Saving & Loading Models). The old torchdata DataPipes API and DataLoader2 were removed in torchdata 0.10 (see Legacy APIs & Migration).

Diagnosing a slow input pipeline

  1. Time a loop that only iterates the loader and does nothing else. If this alone cannot reach the training step speed, the loader is the bottleneck.

  2. Compare num_workers=0 with 2, 4 and 8. Flat results mean the bottleneck is I/O, a single-threaded transform, or the collate function.

  3. Check the CPU: workers pegged at 100 percent mean decoding or augmentation is expensive; move decoding to the GPU (see torchvision) or pre-process once and cache.

  4. Look for synchronisation points in the training step (.item(), .cpu(), printing a tensor every step), which stop the CPU from queuing work ahead of the GPU.

  5. Use the profiler to see whether the GPU idles between steps (Profiling with torch.profiler).

Common pitfalls, summarised:

  • prefetch_factor set while num_workers=0 is an error.

  • persistent_workers=True without workers is an error.

  • Lambdas, nested functions or open file handles in the dataset break spawn.

  • A NumPy random call inside __getitem__ repeats across workers unless the workers are seeded.

  • Forgetting DistributedSampler.set_epoch repeats the same order every epoch.

  • drop_last=False with torch.compile or CUDA graphs yields a smaller last batch that can trigger recompilation (see torch.compile).