Sign in

Loaders

Dataset and data loader

A dataset and data loader pair that serves shuffled mini-batches from indexed samples, with padding for sequences and optional background prefetch.

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

  1. Wrap the data in a dataset: anything with a length and a way to return sample number ii. ArrayDataset does this for arrays that share their first dimension.
  2. At the start of each epoch the DataLoader draws a new random order from seed + epoch, or keeps dataset order if shuffle is off.
  3. It cuts the order into groups of batch_size. A short final group is kept, or dropped when drop_last is on.
  4. For each group it fetches the samples and stacks them with a collate function into one array per field.
  5. pad_collate handles sequences of different lengths: it pads each to the longest in the batch and also returns the true lengths.
  6. With prefetch above 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_last in 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

IfUse instead
The model fits on the whole table at once, as most tree models and classical methods doPass 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 loadThe ingestion lesson, which reads in chunks
Several workers each need a disjoint part of the dataThe distributed training lesson, which shards the indices

Math foundations

  1. Batches per epoch

    B=⌈nb⌉(keep the last batch),B=⌊nb⌋(drop it)B = \left\lceil \frac{n}{b} \right\rceil \quad (\text{keep the last batch}), \qquad B = \left\lfloor \frac{n}{b} \right\rfloor \quad (\text{drop it})

    The number of batches one pass over nn samples produces. This is what len(loader) returns, and it is also the number of gradient steps per epoch.

  2. The mini-batch gradient

    gB=1b∑i∈B∇θ ℓi(θ)g_{\mathcal{B}} = \frac{1}{b} \sum_{i \in \mathcal{B}} \nabla_{\theta}\, \ell_i(\theta)

    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.

  3. Why shuffling matters: an unbiased estimate

    E[gB]=∇θL(θ),L(θ)=1n∑i=1nℓi(θ)\mathbb{E}\big[g_{\mathcal{B}}\big] = \nabla_{\theta} L(\theta), \qquad L(\theta) = \frac{1}{n} \sum_{i=1}^{n} \ell_i(\theta)

    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.

  4. Noise shrinks with batch size

    Var⁡[gB]=σ2b\operatorname{Var}\big[g_{\mathcal{B}}\big] = \frac{\sigma^{2}}{b}

    For independently drawn samples, the variance of the batch gradient falls in proportion to 1/b1/b. Four times the batch size halves the typical error.

Symbols

nn
number of samples in the dataset
bb
batch_size
BB
number of batches in one epoch
B\mathcal{B}
the set of sample indices in one batch
ℓi(θ)\ell_i(\theta)
loss of sample i at parameters theta
L(θ)L(\theta)
mean loss over the whole dataset
gBg_{\mathcal{B}}
gradient estimate from one batch
σ2\sigma^{2}
variance of a single sample's gradient

Worked by hand

A dataset has n=10n = 10 samples and the batch size is b=4b = 4. Count the batches with and without drop_last, and compare the gradient noise of this batch size with batch size 1.

⌈104⌉=3batches of sizes 4,  4,  2\left\lceil \frac{10}{4} \right\rceil = 3 \quad \text{batches of sizes } 4,\; 4,\; 2
⌊104⌋=2batches of sizes 4,  4\left\lfloor \frac{10}{4} \right\rfloor = 2 \quad \text{batches of sizes } 4,\; 4
Var⁡[gb=4]Var⁡[gb=1]=σ2/4σ2=14\frac{\operatorname{Var}[g_{b=4}]}{\operatorname{Var}[g_{b=1}]} = \frac{\sigma^{2}/4}{\sigma^{2}} = \frac{1}{4}

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

  1. 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.

  2. Why does the loader derive the shuffle from seed + epoch instead 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.

  3. 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.

  4. 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 3×503 \times 50. Then think about what happens if sequences of similar length are grouped into the same batch.

  5. With prefetch=2 the 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.