Overview
Training by gradient descent does not look at the whole dataset for each step. It looks at a small random group of samples, called a mini-batch, takes a step, and moves on to the next group. The loader is the part that deals out those groups. It decides the visiting order, cuts it into batches, fetches the samples and stacks them into arrays. Shuffling again every epoch (one full pass over the data) keeps the batches different from pass to pass, and a seed makes the whole sequence repeatable.
A short history
The data loader is an engineering pattern that follows from mini-batch stochastic gradient descent, whose roots are the 1951 stochastic approximation method of Robbins and Monro. Training on small shuffled batches became standard for neural networks in the 1990s and 2000s. Deep learning frameworks then separated the two roles: a dataset that returns one sample by index, and a loader that shuffles, batches and prefetches. PyTorch made this pair the familiar interface.
How it works
- Wrap the data in a dataset: anything with a length and a way to return sample number .
ArrayDatasetdoes this for arrays that share their first dimension. - At the start of each epoch the
DataLoaderdraws a new random order fromseed + epoch, or keeps dataset order ifshuffleis off. - It cuts the order into groups of
batch_size. A short final group is kept, or dropped whendrop_lastis on. - For each group it fetches the samples and stacks them with a collate function into one array per field.
pad_collatehandles sequences of different lengths: it pads each to the longest in the batch and also returns the true lengths.- With
prefetchabove zero, a background thread builds batches ahead of time and passes them through a bounded queue.
Watch out for
- Without shuffling, data sorted by class or by time gives batches that each show one slice of the data, and the gradient steps pull the model back and forth.
- A short last batch gives a noisier gradient and can upset layers that compute statistics over the batch. Use
drop_lastin that case. - Padding adds values that are not data. If the model does not use the returned lengths to ignore them, the padding changes the result.
- Prefetch here uses one background thread, a small stand-in for the worker processes of large frameworks, so it helps with slow reading but not with heavy Python computation.
Use cases
When to use it
Whenever a model is trained with mini-batch gradient descent. Turn shuffle off for validation and inference, and turn prefetch on when building a batch is slow enough to stall the training step.
In industry
- Computer vision
- Image classifiers are trained on shuffled batches of images that background workers decode and augment while the processor is busy with the previous batch.
- Natural language processing
- Sentences have different lengths. A collate function pads each batch to its longest sentence so the batch becomes one rectangular array.
- Recommendation
- Click logs hold far more rows than fit in one step. A loader feeds them to a ranking model in fixed-size batches, reshuffled every epoch.
Choosing it: what must hold
- A model trained by mini-batch gradient descent.
- Samples that can be fetched by index and whose count is known.
- Samples of one shape, or a collate function that pads them to a common shape.
When to choose something else
| If | Use instead |
|---|---|
| The model fits on the whole table at once, as most tree models and classical methods do | Pass the full arrays to the model, for example Random Forest or XGBoost |
| The data cannot be indexed because it is an endless stream or a file too large to load | The ingestion lesson, which reads in chunks |
| Several workers each need a disjoint part of the data | The distributed training lesson, which shards the indices |
Math foundations
Batches per epoch
The number of batches one pass over samples produces. This is what
len(loader)returns, and it is also the number of gradient steps per epoch.The mini-batch gradient
The average gradient over the samples of one batch. It stands in for the gradient over the whole dataset, at a fraction of the cost.
Why shuffling matters: an unbiased estimate
When the batch is a uniform random draw from the data, its gradient is right on average. A batch taken from sorted data does not have this property.
Noise shrinks with batch size
For independently drawn samples, the variance of the batch gradient falls in proportion to . Four times the batch size halves the typical error.
Symbols
- number of samples in the dataset
- batch_size
- number of batches in one epoch
- the set of sample indices in one batch
- loss of sample i at parameters theta
- mean loss over the whole dataset
- gradient estimate from one batch
- variance of a single sample's gradient
Worked by hand
A dataset has samples and the batch size is . Count the batches with and without drop_last, and compare the gradient noise of this batch size with batch size 1.
Keeping the last batch gives 3 steps per epoch and every sample is used. Dropping it gives 2 steps and leaves 2 samples out of that epoch. A batch of 4 has a quarter of the variance of a single sample.
Visual example
Loading the example.
Try this
- Press Next batch until the epoch ends, then watch the next epoch draw a new order.
- Turn drop_last on with n = 10 and b = 4: two samples sit out the epoch.
- Turn shuffle off and see every epoch serve the same batches in the same order.
Code sample
import numpy as np
from impl import ArrayDataset, DataLoader
from config import LoadersConfig
X = np.arange(20.0).reshape(10, 2)
y = np.arange(10)
loader = DataLoader(ArrayDataset(X, y), LoadersConfig(batch_size=4, shuffle=True, seed=0))
for epoch in range(2):
for xb, yb in loader: # shapes (4, 2) and (4,), the last batch has 2 samples
print(epoch, yb)Read the implementation (141 lines)
"""Dataset and DataLoader: turn indexed samples into shuffled mini-batches, optionally prefetched on a thread.
NumPy and the standard library only. A dataset is anything with `__len__` and `__getitem__(i)` returning a
tuple of arrays. The loader picks the order, cuts it into batches, fetches the samples and stacks them with a
collate function. `pad_collate` handles samples whose first field is a sequence of varying length.
"""
from __future__ import annotations
import queue
import threading
from typing import Callable, Iterator
import numpy as np
try:
from .config import LoadersConfig
except ImportError: # run from the template's own folder
from config import LoadersConfig
class ArrayDataset:
"""Samples held in arrays that share their first dimension. Sample i is (arrays[0][i], arrays[1][i], ...)."""
def __init__(self, *arrays) -> None:
if not arrays:
raise ValueError("ArrayDataset needs at least one array")
self.arrays = tuple(np.asarray(a) for a in arrays)
if len({a.shape[0] for a in self.arrays}) != 1:
raise ValueError(f"arrays differ in length: {[a.shape[0] for a in self.arrays]}")
def __len__(self) -> int:
return self.arrays[0].shape[0]
def __getitem__(self, index: int) -> tuple:
return tuple(a[index] for a in self.arrays)
def default_collate(samples: list[tuple]) -> tuple:
"""Stack field k of every sample into one array with a new leading batch dimension."""
return tuple(np.stack([sample[k] for sample in samples]) for k in range(len(samples[0])))
def pad_sequences(sequences, pad_value: float = 0.0) -> tuple[np.ndarray, np.ndarray]:
"""Pad sequences of different lengths to the longest one.
sequences: list of arrays, each of shape (length_i, ...) with the same trailing shape.
Returns (padded, lengths): padded has shape (batch, max_length, ...), lengths has shape (batch,).
"""
sequences = [np.asarray(s) for s in sequences]
lengths = np.array([s.shape[0] for s in sequences], dtype=int)
longest = int(lengths.max()) if len(sequences) else 0
padded = np.full((len(sequences), longest) + sequences[0].shape[1:], pad_value, dtype=sequences[0].dtype)
for i, sequence in enumerate(sequences):
padded[i, : sequence.shape[0]] = sequence
return padded, lengths
def pad_collate(samples: list[tuple]) -> tuple:
"""Collate for samples (sequence, other fields...): returns (padded, lengths, stacked other fields...)."""
padded, lengths = pad_sequences([sample[0] for sample in samples])
rest = tuple(np.stack([sample[k] for sample in samples]) for k in range(1, len(samples[0])))
return (padded, lengths) + rest
_END = object() # marks the end of an epoch in the prefetch queue
class DataLoader:
"""Iterate a dataset in mini-batches. Each `for batch in loader` is one epoch.
dataset: anything with __len__ and __getitem__(i) -> tuple of arrays.
collate_fn: turns a list of samples into a batch. Default: stack each field.
"""
def __init__(self, dataset, config: LoadersConfig | None = None, collate_fn: Callable | None = None) -> None:
self.dataset = dataset
self.config = config or LoadersConfig()
self.collate_fn = collate_fn or default_collate
self.epoch = 0 # number of epochs started so far
def __len__(self) -> int:
"""Number of batches in one epoch."""
n, b = len(self.dataset), self.config.batch_size
return n // b if self.config.drop_last else -(-n // b)
def batch_indices(self, epoch: int) -> list[np.ndarray]:
"""The sample indices of every batch of the given epoch, in order."""
cfg = self.config
order = np.arange(len(self.dataset))
if cfg.shuffle:
order = np.random.default_rng(cfg.seed + epoch).permutation(order)
batches = [order[i: i + cfg.batch_size] for i in range(0, len(order), cfg.batch_size)]
if cfg.drop_last and batches and len(batches[-1]) < cfg.batch_size:
batches.pop()
return batches
def _batches(self, epoch: int) -> Iterator[tuple]:
for indices in self.batch_indices(epoch):
yield self.collate_fn([self.dataset[int(i)] for i in indices])
def _prefetched(self, epoch: int) -> Iterator[tuple]:
"""Same batches as `_batches`, built on a background thread and handed over through a bounded queue."""
ready: queue.Queue = queue.Queue(maxsize=self.config.prefetch)
stop = threading.Event()
def put(item) -> bool:
while not stop.is_set():
try:
ready.put(item, timeout=0.05)
return True
except queue.Full:
continue
return False
def work() -> None:
try:
for batch in self._batches(epoch):
if not put(batch):
return
put(_END)
except BaseException as error: # hand the error to the consumer instead of dying silently
put(error)
worker = threading.Thread(target=work, daemon=True)
worker.start()
try:
while True:
item = ready.get()
if item is _END:
return
if isinstance(item, BaseException):
raise item
yield item
finally:
stop.set() # also reached when the consumer stops early, so the worker does not block forever
worker.join()
def __iter__(self) -> Iterator[tuple]:
epoch = self.epoch
self.epoch += 1
return self._prefetched(epoch) if self.config.prefetch else self._batches(epoch)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Create DataLoader(ArrayDataset(X, y), LoadersConfig(batch_size=4, shuffle=True, seed=0)) on 10 samples. Print loader.batch_indices(0) and loader.batch_indices(1), then build a second loader with the same seed and confirm it gives the same batches. Repeat with drop_last=True and check len(loader).
Check on learning
- Your training data is sorted by label and you forget to shuffle. Describe what the first few hundred gradient steps do to the model.
A way to think about it
Each batch contains one class only. Ask what the best prediction is for such a batch and where the step moves the output layer.
- Why does the loader derive the shuffle from
seed + epochinstead of using the same order every epoch or an unseeded random order?A way to think about it
List what you want: different batches each pass, and the ability to rerun an experiment and get the same numbers. Check each option against both.
- Doubling the batch size halves the steps per epoch and reduces gradient noise. Is the larger batch then always better?
A way to think about it
Compare the cost of one step, the number of steps, and how accurate each step needs to be. Some noise also helps a model leave poor regions.
- A batch holds sequences of lengths 3, 4 and 50. How much of the padded array is real data, and how could you waste less?
A way to think about it
Count real entries against . Then think about what happens if sequences of similar length are grouped into the same batch.
- With
prefetch=2the training loop is no faster than before. What does that tell you about where the time goes?A way to think about it
Prefetch only helps if the consumer would otherwise wait for a batch. Compare the time to build a batch with the time of one training step.