Datasets & DataLoader
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Training speed and correctness depend as much on the data pipeline as on the model. PyTorch separates the pipeline into a Dataset (how to get one sample), a Sampler (which samples, in which order), a collate_fn (how to merge samples into a batch) and the DataLoader that orchestrates them, optionally with worker processes. This page covers the API and its defaults; throughput tuning (worker counts, pinned memory, prefetching, stateful loaders) continues in Workers, Pinned Memory & Samplers. Image-specific datasets and transforms are in torchvision: Transforms v2, Models & Weights. Splitting data into train, validation and test sets without leakage is a modelling matter discussed in Generalization & Regularization and, for tabular data, in Model Evaluation.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31; the multi-worker example ran as a script under the spawn start method of macOS. Defaults that depend on the platform (the multiprocessing start method) are called out because they change how code must be written.
Two kinds of dataset
Map-style datasets implement __getitem__(self, idx) and __len__; they map an index to a sample, which allows shuffling, random access and splitting. Iterable-style datasets subclass IterableDataset and implement __iter__; they suit streams, databases and remote sources where random access or the length is unknown. Samplers cannot be used with iterable-style datasets because there are no indices; ordering and shuffling are the dataset’s own responsibility.
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
class NoisySines(Dataset):
"""Map-style dataset generated on demand."""
def __init__(self, n: int = 1000, length: int = 64, seed: int = 0):
rng = np.random.default_rng(seed)
self.freq = rng.uniform(1, 5, size=n).astype("float32")
self.length = length
def __len__(self) -> int:
return len(self.freq)
def __getitem__(self, idx: int):
t = torch.linspace(0, 1, self.length)
x = torch.sin(2 * torch.pi * self.freq[idx] * t) + 0.1 * torch.randn(self.length)
y = torch.tensor(int(self.freq[idx] > 3)) # label: high or low frequency
return x, y
ds = NoisySines()
loader = DataLoader(ds, batch_size=32, shuffle=True)
xb, yb = next(iter(loader))
print(xb.shape, yb.shape, yb.dtype) # (32, 64) (32,) torch.int64
Guidelines for __getitem__:
-
Do the expensive, per-sample work (decoding an image, tokenizing text) here, because it is the part that worker processes parallelize. Do the cheap, batch-level work in
collate_fn. -
Keep references to large arrays out of per-sample Python containers. With worker processes, Python objects that are refcounted can be copied into every worker over time; storing data in NumPy arrays, pandas or PyArrow structures avoids the growth that the documentation warns about.
-
Return plain tensors, numbers, NumPy arrays, dicts, lists or tuples so
default_collatecan batch them. -
Random augmentation inside
__getitem__needs correct per-worker seeding, covered below.
Built-in dataset utilities
-
TensorDataset(*tensors): indexes tensors along their first dimension; all must have the same length. Ideal for data already in memory. -
StackDataset: combines datasets into tuples (positional arguments) or dicts (keyword arguments). -
ConcatDataset(datasets): concatenates map-style datasets;ChainDataset(datasets)chains iterable-style ones. -
Subset(dataset, indices): a view on selected indices. If a subclass overrides__getitem__it must also override__getitems__, or theDataLoaderraisesNotImplementedError. -
random_split(dataset, lengths, generator=...): lengths can be integers or fractions that sum to one; remainders are distributed round-robin. Pass a seededtorch.Generatorfor a reproducible split.
import torch
from torch.utils.data import TensorDataset, random_split, DataLoader
X = torch.randn(1000, 20)
y = torch.randint(0, 3, (1000,))
full = TensorDataset(X, y)
g = torch.Generator().manual_seed(42)
train_ds, val_ds, test_ds = random_split(full, [0.7, 0.15, 0.15], generator=g)
print(len(train_ds), len(val_ds), len(test_ds))
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True)
val_loader = DataLoader(val_ds, batch_size=256, shuffle=False)
A random split does not respect groups (several samples of the same patient or user) or time order. For those cases build index lists yourself (for example with scikit-learn’s group or time-series splitters, see scikit-learn) and wrap them in Subset. Normalization statistics must come from the training subset only.
DataLoader
The 2.15 signature and defaults:
| Argument | Meaning |
|---|---|
|
The dataset object. |
|
Samples per batch. |
|
Shuffle every epoch (builds a |
|
Custom index order or custom batches. |
|
|
|
Merges a list of samples into a batch. The default is |
|
Copies batches into page-locked memory for faster, asynchronous host-to-GPU copies. |
|
Drop the final smaller batch. |
|
Seconds to wait for a batch from workers; |
|
Called in each worker after seeding and before loading, with the worker id. |
|
Keyword-only. Batches prefetched per worker; |
|
Keep workers alive between epochs, avoiding start-up cost. |
|
Choose the start method; supply the generator used for shuffling and worker base seeds. |
|
Return batches in order. |
|
Deprecated: the current accelerator is used when |
Behaviour worth knowing:
-
len(loader)isceil(len(dataset) / batch_size), orfloorwithdrop_last=True. Use it for schedulers (see Learning-Rate Schedulers & SWA/EMA). -
A loader is re-iterable: each
iter(loader)starts a new epoch (and, with workers, new worker processes unlesspersistent_workers=True). -
For map-style datasets the main process draws the indices, so shuffling happens there and the order depends on the loader’s generator, not on worker count.
-
Use
shuffle=Truefor training andshuffle=Falsefor validation; use a largebatch_sizefor evaluation since no gradients are stored. -
A final batch of size one breaks batch norm in training; use
drop_last=Trueor a different normalization (see Embeddings, Normalization, Dropout & Activations).
The diagram shows how a map-style dataset flows through the loader to produce one batch.
Collation
default_collate stacks tensors and numbers into a batch dimension, converts NumPy arrays and Python numbers to tensors, and preserves dict, list, tuple and namedtuple structure. It fails for samples of different shapes, which is the usual case for text and audio. Write a collate_fn that pads:
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset
class TokenDataset(Dataset):
def __init__(self, sequences, labels):
self.sequences, self.labels = sequences, labels
def __len__(self):
return len(self.sequences)
def __getitem__(self, idx):
return torch.tensor(self.sequences[idx]), self.labels[idx]
def collate_pad(batch, pad_id: int = 0):
seqs, labels = zip(*batch)
lengths = torch.tensor([len(s) for s in seqs])
padded = pad_sequence(seqs, batch_first=True, padding_value=pad_id) # (N, max_len)
mask = padded != pad_id # True = real token
return {"input_ids": padded, "mask": mask, "lengths": lengths, "labels": torch.tensor(labels)}
data = TokenDataset([[5, 6, 7], [8, 9], [1, 2, 3, 4]], [0, 1, 0])
loader = DataLoader(data, batch_size=3, collate_fn=collate_pad)
batch = next(iter(loader))
print(batch["input_ids"].shape, batch["lengths"])
If the padding value can also be a real token the mask above is wrong; build the mask from lengths instead. Sorting batches by length (bucketing, through a custom batch sampler) reduces padding. When a collate_fn returns a custom batch type and you use pin_memory=True, give that type a pin_memory() method so it can be pinned. Define collate_fn at module level so it can be pickled when workers start with spawn.
Samplers
Samplers yield indices. The built-ins are SequentialSampler, RandomSampler(replacement=False, num_samples=None, generator=None), SubsetRandomSampler(indices, generator=None), WeightedRandomSampler(weights, num_samples, replacement=True, generator=None), BatchSampler(sampler, batch_size, drop_last) and DistributedSampler. Class imbalance is a typical use of the weighted sampler:
import torch
from torch.utils.data import DataLoader, TensorDataset, WeightedRandomSampler
y = torch.cat([torch.zeros(950), torch.ones(50)]).long()
X = torch.randn(1000, 8)
ds = TensorDataset(X, y)
class_counts = torch.bincount(y)
sample_weights = (1.0 / class_counts.float())[y] # one weight per sample
sampler = WeightedRandomSampler(sample_weights, num_samples=len(ds), replacement=True)
loader = DataLoader(ds, batch_size=64, sampler=sampler) # do not also pass shuffle=True
yb = torch.cat([b[1] for b in loader])
print(yb.float().mean()) # close to 0.5
In distributed training use DistributedSampler(dataset, num_replicas=None, rank=None, shuffle=True, seed=0, drop_last=False) and call sampler.set_epoch(epoch) at the start of every epoch, before creating the iterator, or every epoch will see the same order (see DistributedDataParallel).
Iterable-style datasets and workers
With an IterableDataset and num_workers > 0, every worker gets its own copy of the dataset, so without sharding each sample is produced once per worker. Use torch.utils.data.get_worker_info() (which returns None in the main process, and id, num_workers, seed and dataset inside a worker) to split the stream. drop_last then applies per worker, and len(loader) is only an estimate.
import math
import torch
from torch.utils.data import IterableDataset, DataLoader, get_worker_info
class RangeStream(IterableDataset):
def __init__(self, start: int, end: int):
self.start, self.end = start, end
def __iter__(self):
info = get_worker_info()
if info is None: # single-process loading
lo, hi = self.start, self.end
else: # split the range across workers
per_worker = math.ceil((self.end - self.start) / info.num_workers)
lo = self.start + info.id * per_worker
hi = min(lo + per_worker, self.end)
return iter(range(lo, hi))
if __name__ == "__main__":
loader = DataLoader(RangeStream(0, 20), batch_size=4, num_workers=2)
print(sorted(int(v) for batch in loader for v in batch)) # 0..19, each exactly once
Multi-process loading: start methods and pitfalls
-
Start method. The documentation lists
forkon Unix before Python 3.14,forkserverfrom Python 3.14, andspawnon Windows and macOS. Underspawnthe main script is re-imported in each worker, so the code that builds the loader must sit underif __name__ == "__main__":, and the dataset,collate_fnandworker_init_fnmust be picklable top-level objects; a lambdaworker_init_fnfails. Targeting Python 3.13, Linux still usesforkby default. -
Randomness. Each worker’s PyTorch seed is
base_seed + worker_id, where the base seed comes from the main process RNG or the loader’sgenerator. Seeds of other libraries (NumPy’s legacy global state,random) may repeat across workers, giving identical augmentations. Seed them inworker_init_fnfromtorch.initial_seed()orget_worker_info().seed. Reproducibility more broadly is the subject of Reproducibility & Determinism. -
CUDA in workers. The documentation discourages returning CUDA tensors from workers; load on the CPU and use
pin_memory=Trueplus.to(device, non_blocking=True)in the training loop. -
Memory. Workers hold copies of the dataset object; load large arrays lazily (memory-mapped files,
np.load(..., mmap_mode="r")) rather than as Python lists. -
Debugging. Set
num_workers=0to get readable stack traces and to use a debugger; many "worker died" errors are ordinary exceptions in__getitem__. -
Shared memory. Containers with too small
/dev/shm(default Docker) cause "bus error" crashes with many workers; raise the container’s shared memory.
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, TensorDataset
def seed_worker(worker_id: int) -> None:
seed = torch.initial_seed() % 2**32 # already base_seed + worker_id
np.random.seed(seed)
random.seed(seed)
g = torch.Generator().manual_seed(0)
ds = TensorDataset(torch.randn(256, 8))
loader = DataLoader(
ds, batch_size=32, shuffle=True, num_workers=2,
worker_init_fn=seed_worker, generator=g, persistent_workers=True,
)
Transforms and the torchvision tutorials
The data and transforms tutorials show the common arrangement: a Dataset subclass that stores file paths, applies transform to the input and target_transform to the label in __getitem__, and a DataLoader on top. Transforms are plain callables, so any function works. Keep augmentation (random, training only) separate from preprocessing (deterministic, shared by training and evaluation) by building two dataset instances with different transforms over the same indices.
Datapipes and other libraries
The older torchdata DataPipes API is deprecated and not the recommended route for new code; see Legacy APIs & Migration. For resumable, checkpointable loaders on large corpora look at the stateful loader described in Workers, Pinned Memory & Samplers. Hugging Face datasets offers memory-mapped storage and streaming that plug into a DataLoader (see AI).
Checklist
-
Training loader:
shuffle=True,drop_last=Truewhen batch norm or fixed shapes matter; validation loader:shuffle=False. -
Fixed seeds: seeded
generatorforrandom_splitand the loader,worker_init_fnfor other libraries. -
Variable-length samples:
collate_fnwith padding and an explicit mask. -
Imbalanced classes:
WeightedRandomSampleror class weights in the loss (see Loss Functions), not both blindly. -
Distributed:
DistributedSamplerandset_epoch. -
Speed: profile first (
num_workers,pin_memory,persistent_workers); the loader is often the bottleneck only on small GPUs or slow storage.