TExcelTAD

Dataset and DataLoader

A training loop wants one thing from the data: an endless supply of correctly shaped, correctly typed, well-shuffled mini-batches, delivered fast enough that the model never waits. PyTorch splits that job into small replaceable parts. A Dataset knows how to produce example number i. A sampler decides the order of the indices. A collate_fn turns a list of examples into batch tensors. The DataLoader runs the three, optionally in several worker processes. Most data bugs (a model that sees the classes in order, two workers producing the same "random" augmentation, sequences that cannot be stacked) live in one of these parts, so it pays to know each one.

The examples use the course's Digits split: 1797 images of 8 by 8 pixels, scaled to [0, 1], split with a fixed seed into 1077 training, 360 validation and 360 test images. Choices are made on validation; the test set is used once, at the end of a project.

both run in each of num_workers processes Samplerorder of indices Dataset[i]one (x, y) pair collate_fnlist to tensors batchxb, yb shuffle + generatorweighted, subsetdrop_last __len__, __getitem__transform, augmentworker_init_fn seeds default: torch.stackcustom: pad sequenceslengths, masks pin_memory.to(device)training loop batch_size indices per batch; one pass over the sampler = one epoch

A mini-batch iterator in NumPy

Before the PyTorch classes, the whole idea in a few lines that run in the browser: a permutation from a seeded generator, slices of it as batches, an optional drop_last, and the dtypes PyTorch will expect (float32 images in the (N, C, H, W) layout and int64 labels).

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)

def batches(X, y, batch_size, rng=None, drop_last=False):
    idx = np.arange(len(X)) if rng is None else rng.permutation(len(X))
    stop = len(X) - len(X) % batch_size if drop_last else len(X)
    for s in range(0, stop, batch_size):
        b = idx[s:s + batch_size]
        yield X[b].reshape(-1, 1, 8, 8).astype(np.float32), y[b].astype(np.int64)

print("train", len(X_tr), "validation", len(X_va), "test", len(X_te))
sizes = [len(yb) for _, yb in batches(X_tr, y_tr, 64)]
print("batches", len(sizes), "last batch", sizes[-1])
print("drop_last: batches", sum(1 for _ in batches(X_tr, y_tr, 64, drop_last=True)))
xb, yb = next(batches(X_tr, y_tr, 64, rng=np.random.default_rng(0)))
print("first batch", xb.shape, xb.dtype, yb.dtype, "labels", yb[:8].tolist())
again = next(batches(X_tr, y_tr, 64, rng=np.random.default_rng(0)))[1]
print("same seed, same order:", bool((again == yb).all()))
rng = np.random.default_rng(0)
e1 = next(batches(X_tr, y_tr, 64, rng))[1]; e2 = next(batches(X_tr, y_tr, 64, rng))[1]
print("one generator, two epochs differ:", not bool((e1 == e2).all()))
seen = np.concatenate([yb for _, yb in batches(X_tr, y_tr, 64, np.random.default_rng(1))])
print("every example once per epoch:", len(seen), np.bincount(seen).tolist())
train 1077 validation 360 test 360
batches 17 last batch 53
drop_last: batches 16
first batch (64, 1, 8, 8) float32 int64 labels [5, 6, 3, 7, 5, 2, 5, 2]
same seed, same order: True
one generator, two epochs differ: True
every example once per epoch: 1077 [107, 109, 106, 109, 109, 109, 109, 107, 104, 108]

1077 examples in batches of 64 give 16 full batches and a last one of 53; drop_last throws those 53 away (useful when a layer such as batch norm misbehaves on a tiny last batch, or when every step must have the same shape). The generator is created once and reused, so each epoch gets a new order while the whole run stays reproducible from the seed 0. An epoch visits every example exactly once: 1077 labels, with the class counts of the training set.

A map-style Dataset

A map-style dataset implements __len__ and __getitem__(i). Per-example preprocessing and augmentation go in __getitem__, usually as a transform callable, so they run on demand (and in the worker processes, below). Here the transform shifts each image one pixel to the right, a stand-in for real augmentation.

python · try it yourself
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)

class Digits(Dataset):
    def __init__(self, X, y, transform=None):
        self.X = torch.tensor(X, dtype=torch.float32).reshape(-1, 1, 8, 8)
        self.y = torch.tensor(y, dtype=torch.int64)
        self.transform = transform
    def __len__(self):
        return len(self.y)
    def __getitem__(self, i):
        x = self.X[i]
        if self.transform is not None:
            x = self.transform(x)
        return x, self.y[i]

def shift_right(x):                        # a tiny augmentation: move the image one pixel right
    return torch.roll(x, shifts=1, dims=-1)

train_ds = Digits(X_tr, y_tr, transform=shift_right)
val_ds = Digits(X_va, y_va)
x0, y0 = train_ds[0]
print("len", len(train_ds), "| item", tuple(x0.shape), x0.dtype, "label", y0.item(), y0.dtype)

g = torch.Generator().manual_seed(0)
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True, generator=g)
val_loader = DataLoader(val_ds, batch_size=256, shuffle=False)
xb, yb = next(iter(train_loader))
print("batch", tuple(xb.shape), tuple(yb.shape), "| batches per epoch", len(train_loader), "| val", len(val_loader))
print("first labels", yb[:8].tolist())
g2 = torch.Generator().manual_seed(0)
again = next(iter(DataLoader(train_ds, batch_size=64, shuffle=True, generator=g2)))[1]
print("same generator seed, same first batch:", torch.equal(again, yb))
second_epoch = next(iter(train_loader))[1]
print("next epoch reshuffles:", not torch.equal(second_epoch, yb))
print("drop_last:", len(DataLoader(train_ds, batch_size=64, drop_last=True)), "batches, sizes",
      sorted({len(b[1]) for b in DataLoader(train_ds, batch_size=64)}))
len 1077 | item (1, 8, 8) torch.float32 label 7 torch.int64
batch (64, 1, 8, 8) (64,) | batches per epoch 17 | val 2
first labels [9, 4, 1, 4, 5, 9, 7, 0]
same generator seed, same first batch: True
next epoch reshuffles: True
drop_last: 16 batches, sizes [53, 64]

The default collate_fn stacked 64 items of shape (1, 8, 8) into a batch of shape (64, 1, 8, 8) and 64 scalar labels into (64,). len(loader) is the number of batches (17 for training, 2 for validation at batch size 256). The order differs from the NumPy version because PyTorch draws its own permutation, but the logic is the same: a torch.Generator with a fixed seed makes the shuffle reproducible, and iterating the loader again starts a new epoch with a new order. Without generator=, the shuffle draws from the global torch RNG, so anything else that consumes random numbers (dropout, initialisation of a new layer) changes your data order.

For data that is already a pair of tensors, TensorDataset(X, y) does the same as the class above without a transform. Shuffle the training loader only: validation and test order does not matter for the metrics, and a fixed order makes per-example error analysis easier.

collate_fn for variable-length sequences

The default collate calls torch.stack, which needs every item to have the same shape. Sequences (sentences, time series, molecules) do not. A custom collate_fn pads them to the longest in the batch and returns the lengths and a mask, so later layers can ignore the padding (the full story is in training sequence models).

python · try it yourself
import torch
from torch.utils.data import DataLoader
from torch.nn.utils.rnn import pad_sequence

torch.manual_seed(0)
seqs = [torch.randint(1, 10, (n,)) for n in (5, 2, 7, 3)]     # token ids, 0 is reserved for padding
labels = [1, 0, 1, 0]
data = list(zip(seqs, labels))

try:
    next(iter(DataLoader(data, batch_size=4)))
except RuntimeError as e:
    print("RuntimeError:", e)

def pad_collate(batch):
    xs, ys = zip(*batch)
    lengths = torch.tensor([len(s) for s in xs])
    padded = pad_sequence(xs, batch_first=True, padding_value=0)
    mask = torch.arange(padded.shape[1])[None, :] < lengths[:, None]
    return padded, lengths, mask, torch.tensor(ys)

padded, lengths, mask, yb = next(iter(DataLoader(data, batch_size=4, collate_fn=pad_collate)))
print("padded", tuple(padded.shape), "lengths", lengths.tolist())
for row, m in zip(padded.tolist(), mask.int().tolist()):
    print(row, m)
print("padding share", round(1 - mask.float().mean().item(), 3))
RuntimeError: stack expects each tensor to be equal size, but got [5] at entry 0 and [2] at entry 1
padded (4, 7) lengths [5, 2, 7, 3]
[9, 1, 3, 7, 8, 0, 0] [1, 1, 1, 1, 1, 0, 0]
[7, 8, 0, 0, 0, 0, 0] [1, 1, 0, 0, 0, 0, 0]
[2, 2, 1, 9, 3, 7, 4] [1, 1, 1, 1, 1, 1, 1]
[2, 3, 1, 0, 0, 0, 0] [1, 1, 1, 0, 0, 0, 0]
padding share 0.393

Of the 28 positions in the padded (4, 7) batch, 11 are padding (0.393). Padding is wasted computation, so sequence pipelines often sort or bucket examples by length before batching; the mask is what keeps the padding out of the loss and out of attention.

Worker processes and their seeds

With num_workers=k, the DataLoader starts k processes, each with a copy of the dataset, and they load batches in parallel while the main process trains. PyTorch seeds Python's random, torch and NumPy's legacy global RNG differently in each worker. It cannot reseed a random generator object that your dataset owns, such as a np.random.default_rng created in __init__: every worker receives an identical copy of it.

python · try it yourself
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, get_worker_info

class NoisyIndex(Dataset):
    """Returns (index, random noise drawn from a NumPy Generator stored in the dataset)."""
    def __init__(self, n):
        self.n = n
        self.rng = np.random.default_rng(0)
    def __len__(self):
        return self.n
    def __getitem__(self, i):
        return i, round(float(self.rng.random()), 4)

def show(loader):
    out = {}
    for idx, noise in loader:
        for i, v in zip(idx.tolist(), noise.tolist()):
            out[i] = round(v, 4)
    return [out[i] for i in range(8)]

ds = NoisyIndex(8)
print("0 workers:          ", show(DataLoader(ds, batch_size=2)))
print("2 workers, no init: ", show(DataLoader(ds, batch_size=2, num_workers=2)))

def worker_init_fn(worker_id):
    info = get_worker_info()                       # info.seed = base seed + worker id, set by PyTorch
    info.dataset.rng = np.random.default_rng(info.seed % 2**32)

g = torch.Generator().manual_seed(0)
a = show(DataLoader(ds, batch_size=2, num_workers=2, worker_init_fn=worker_init_fn, generator=g))
g = torch.Generator().manual_seed(0)
b = show(DataLoader(ds, batch_size=2, num_workers=2, worker_init_fn=worker_init_fn, generator=g))
print("2 workers, init_fn: ", a)
print("reproducible with a seeded generator:", a == b)
0 workers:           [0.637, 0.2698, 0.041, 0.0165, 0.8133, 0.9128, 0.6066, 0.7295]
2 workers, no init:  [0.5436, 0.9351, 0.5436, 0.9351, 0.8159, 0.0027, 0.8159, 0.0027]
2 workers, init_fn:  [0.8308, 0.6784, 0.647, 0.6341, 0.0608, 0.3052, 0.3309, 0.8182]
reproducible with a seeded generator: True

With two workers and no init function, worker 0 loads examples 0, 1, 4, 5 and worker 1 loads 2, 3, 6, 7, and both draw the same numbers: example 2 gets the "random" 0.5436 of example 0, and so on. With augmentation that means pairs of examples receive identical crops or noise. (The values also differ from the 0-worker line because the main process's generator had already advanced by 8 draws before the workers copied it.) The fix gives each worker its own generator from get_worker_info().seed, which PyTorch derives from the loader's base seed plus the worker id; with generator= seeded, the base seed and therefore every worker's stream is reproducible, as the last line shows.

How many workers? Start with the number of CPU cores available to you, divided among concurrent jobs, and measure: with tiny in-memory data such as Digits, workers only add start-up cost, so num_workers=0 is faster. persistent_workers=True keeps the workers alive between epochs, and pin_memory=True helps on CUDA machines (devices).

Samplers and streams

A sampler is any iterable of indices; shuffle=True is shorthand for a RandomSampler. Passing sampler= replaces it (and then shuffle must stay off). Two useful ones, plus an iterable dataset for data that cannot be indexed:

python · try it yourself
import torch
from torch.utils.data import (TensorDataset, DataLoader, WeightedRandomSampler,
                              SubsetRandomSampler, IterableDataset, get_worker_info)

y = torch.tensor([0] * 900 + [1] * 100)                   # 9 : 1 imbalance
X = torch.randn(1000, 4, generator=torch.Generator().manual_seed(0))
ds = TensorDataset(X, y)
counts = torch.bincount(y)
weights = (1.0 / counts.double())[y]                         # each example: 1 / size of its class
sampler = WeightedRandomSampler(weights, num_samples=len(y), replacement=True,
                                generator=torch.Generator().manual_seed(0))
idx = torch.tensor(list(sampler))
print("plain epoch class counts:   ", counts.tolist())
print("weighted epoch class counts:", torch.bincount(y[idx]).tolist())
minority = idx[y[idx] == 1]
print("minority draws", len(minority), "from", len(set(minority.tolist())), "distinct examples")

perm = torch.randperm(1000, generator=torch.Generator().manual_seed(0))
train_idx, val_idx = perm[:800].tolist(), perm[800:].tolist()
tr_loader = DataLoader(ds, batch_size=100, sampler=SubsetRandomSampler(train_idx, generator=torch.Generator().manual_seed(0)))
seen = sorted(i for b in DataLoader(range(1000), batch_size=100, sampler=SubsetRandomSampler(train_idx)) for i in b.tolist())
print("SubsetRandomSampler: batches", len(tr_loader), "| covers exactly the train indices:", seen == sorted(train_idx))

class Stream(IterableDataset):
    """An endless-looking stream, here 0..n-1, split between workers."""
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        info = get_worker_info()
        wid, nw = (0, 1) if info is None else (info.id, info.num_workers)
        for i in range(wid, self.n, nw):            # each worker takes every nw-th record
            yield torch.tensor([i, wid])

for nw in (0, 2):
    rows = torch.cat(list(DataLoader(Stream(10), batch_size=3, num_workers=nw)))
    print(f"num_workers={nw}: records", rows[:, 0].tolist(), "worker", rows[:, 1].tolist())
plain epoch class counts:    [900, 100]
weighted epoch class counts: [500, 500]
minority draws 500 from 99 distinct examples
SubsetRandomSampler: batches 8 | covers exactly the train indices: True
num_workers=0: records [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] worker [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
num_workers=2: records [0, 2, 4, 1, 3, 5, 6, 8, 7, 9] worker [0, 0, 0, 1, 1, 1, 0, 0, 1, 1]
  • WeightedRandomSampler draws indices with probability proportional to a weight. Weighting each example by one over its class size makes both classes equally likely: this epoch of 1000 draws holds 500 of each (exactly 500 by chance with this seed; expect about 500). Because it samples with replacement, the 500 minority draws reuse 99 distinct examples about five times each, which is oversampling with the same overfitting risk; class weights in the loss are the alternative (class imbalance). Measure on validation data with the real class balance.
  • SubsetRandomSampler shuffles a fixed list of indices, a way to split one dataset into training and validation without copying it. torch.utils.data.Subset(ds, idx) does the same as a dataset and combines with shuffle=True.
  • IterableDataset is for streams: files read line by line, a database cursor, generated data. It has __iter__ instead of __getitem__, and there is no sampler, so shuffling (with a buffer) and splitting the stream between workers are your job. Without the get_worker_info() split, two workers would each yield the whole stream and every record would appear twice. Note the order: workers deliver whole batches in turn, so records 0, 2, 4 come from worker 0 and 1, 3, 5 from worker 1.

Pitfalls

  • The same RNG in every worker for augmentation stored on the dataset. Seed it per worker in worker_init_fn.
  • Shuffling with the global RNG. Pass a seeded generator= so that the data order does not depend on unrelated random calls.
  • Shuffling the training data off. Batches of a sorted dataset contain one class each; training collapses (see debugging a network).
  • Heavy work in the main process. Decoding images or tokenising text in the loop instead of in __getitem__ defeats the workers.
  • float64 and int32 from NumPy. Convert in the dataset: images float32, class labels int64.
  • An IterableDataset without worker sharding. Every record is produced once per worker.
  • Using drop_last=True for validation or test. It silently skips examples; drop only in training.

Practice

  1. With 1077 training images, batch_size=64 and drop_last=True, how many optimiser steps does one epoch take, and how many images are never seen in that epoch? Are they the same images every epoch?
Answer

16 steps (1024 images) and 53 images skipped. With shuffling they are different images each epoch, so nothing is lost over many epochs; without shuffling the same 53 would never be used.

  1. Write a collate_fn for a dataset whose items are dicts {"tokens": LongTensor, "label": int} that returns a dict with "tokens" (padded with 0), "mask" and "label".
Answer
python
def collate(batch):
    toks = [b["tokens"] for b in batch]
    lengths = torch.tensor([len(t) for t in toks])
    padded = pad_sequence(toks, batch_first=True, padding_value=0)
    mask = torch.arange(padded.shape[1])[None, :] < lengths[:, None]
    return {"tokens": padded, "mask": mask, "label": torch.tensor([b["label"] for b in batch])}
  1. Your augmentation uses random.random() (Python's module) inside __getitem__. Do two workers produce the same values?
Answer

No: PyTorch seeds Python's random, torch and NumPy's legacy global RNG in each worker with the worker's own seed. The duplicated-stream problem applies to generator objects that the dataset itself holds, such as a np.random.default_rng created in __init__, which every worker copies. Reproducibility across runs still needs a seeded generator= on the DataLoader.

Test yourself

What does the default collate_fn do with a list of 32 items of shape (3, 32, 32)?

  1. Concatenates them into (96, 32, 32)
  2. Stacks them into (32, 3, 32, 32)
  3. Pads them to the longest item
  4. Returns the list unchanged

Why pass generator=torch.Generator().manual_seed(0) to a shuffling DataLoader?

  1. It makes loading faster
  2. The shuffle order becomes reproducible and independent of other uses of the global RNG
  3. It is required when num_workers > 0
  4. It disables reshuffling between epochs

A dataset creates self.rng = np.random.default_rng(0) and uses it for augmentation. With num_workers=4, what happens?

  1. Each worker gets a differently seeded generator automatically
  2. All four workers copy the same generator and produce the same random values
  3. NumPy generators cannot be used in workers
  4. Only worker 0 uses augmentation

What does WeightedRandomSampler with weights 1/class_count and replacement=True do on a 9:1 data set?

  1. Removes majority examples
  2. Draws both classes about equally often, repeating minority examples
  3. Changes the loss function
  4. Guarantees each example is seen once per epoch