Module contents
Lesson 15 of 24Core 75 min

Dataset, DataLoader and the data pipeline

How data reach the GPU: map-style and iterable datasets, samplers, collation, variable-length batches, worker processes and pinned memory. Diagnose data bottlenecks and account for Windows spawn behavior.

After this lesson you can

  • Implement map-style and iterable datasets, including lazy disk reads with memory mapping.
  • Write collate functions for heterogeneous and variable-length batches with padding, masks and lengths.
  • Configure random, weighted and length-grouped samplers and understand shuffle and drop_last.
  • Tune num_workers, pin_memory, prefetch_factor and persistent_workers by measuring real Windows performance.
  • Diagnose and eliminate GPU waits for data.

Before you start

Motivation: GPU at 30% while the CPU decompresses images

You train a small convolutional network on 224 × 224 images on an RTX 4060. A training step with batches of 64 images (forward, loss, backward and optimizer) takes 15 ms on GPU. But each image is a JPEG on disk: it must be read, decompressed, cropped, flipped and normalized, all on CPU, say in 0.75 ms per image. In the most naive loop, the Python process prepares the whole batch (64 × 0.75 = 48 ms, plus about 4 ms to stack), passes it to GPU and starts over. nvidia-smi shows utilization around 30%, one CPU core is at 100% while another 23 wait, and an epoch takes over three times as long as it should.

The bottleneck is earlier: how data reach the GPU. PyTorch addresses it with two abstractions, Dataset and DataLoader, examined piece by piece in this lesson:

  • which protocol a dataset implements and how to read it from disk without loading it all;
  • who decides sample order, how samples are batched and what happens to the last batch;
  • how to combine variable-length sequences in a tensor without wasting half the computation on padding;
  • how work is distributed among worker processes, why Windows requires a particular coding pattern and how many workers are needed;
  • how to measure whether the GPU waits for data, the reason to tune the above.

At the end you will actually saturate the lab GPU with a disk-reading Dataset and document the configuration that works on this machine.

Intuition: a production line

Training is a producer-consumer system. Producers load and transform batches on CPU; the consumer is the GPU, executing one step per batch. A queue sits between them. The slowest stage sets overall throughput, and the GPU stays busy only if a batch is ready whenever the previous one finishes.

InteractivePipeline timeline
First 12 steps of an epoch. Numbers are batch indices.
mainGPU01234567891011120123456789ready batchesno queue: num_workers = 00100200300400500600ms
  • batch loading and collation
  • CPU → GPU copy
  • step compute
  • waiting (GPU idle or main process blocked)
Fraction of time the GPU computes, by num_workers
0%25%50%75%100%more workers than coresceiling C/(C + copy) = 82 %0123456789101112num_workers (dotted line: ⌈L/(C + copy)⌉ = 3)
CPU loading
0
0.75 ms
30 %
8
Batch and GPU
64
15 ms
Sample crossing PCIe (3×224×224)
DataLoader
2 (no effect)
GPU computing28 %
step (steady state)54 ms
data wait per step54 ms
throughput1191 samples/s
batch load in one process52 ms
workers needed3
batches in flight1 (37 MiB)
epoch of 50 000 samples42.0 s
Data-bound: the main process loads each batch itself (52 ms) while the GPU computes for 15 ms. Add workers: about 3 are needed.
Simulation of a real DataLoader: each worker loads whole batches round-robin, at most num_workers × prefetch_factor batches are in flight, and delivery is ordered. Copy bandwidths were measured on the lab machine. With num_workers = 0 the main process loads every batch and the GPU row has striped gaps. Increase workers one by one: gaps close until GPU becomes the bottleneck, then the lower curve flattens. Adjust per-sample cost, compute per step and variability, and observe the knee and effect of prefetch_factor.

Three things the figure shows and the rest of the lesson justifies:

  1. With num_workers = 0, one process prepares all batches. CUDA calls are asynchronous, so the main process already loads the next batch while the GPU computes the current one; even so, each batch takes about 55 ms to become ready and GPU computes 15 ms of each 55: below 30%.
  2. Beyond a certain worker count, adding more does not help. With 4 workers, each takes 52 ms per batch but together deliver one every 13 ms, faster than the GPU consumes them. The GPU step itself, including copy, sets the ceiling.
  3. The queue absorbs variability, not lack of capacity. prefetch_factor does not change average batches produced per second; it changes the buffer when one batch is slower than another.

Two dataset protocols

PyTorch does not require special inheritance: the object need only speak one of two Python data model protocols.

The difference is what information the loader has. With indexed access it knows nn and can request samples in any order: shuffle, distribute indices among processes, skip samples, start halfway. With an iterable it can only request “the next one.” In exchange, an iterable can represent unindexed things: a network data stream, a terabyte corpus split into sequentially read files, a generator synthesizing endless examples. This is PyTorch’s version of lazy generator pipelines.

In both cases the golden rule is the dataset stores how to obtain data, not the data. Its constructor stores paths, indices and metadata; __getitem__ reads the requested sample from disk, transforms and returns it. Memory then does not depend on dataset size, and the object is cheap to copy to other processes, exactly what happens with workers.

Lazy reading: the offset of row ii

If samples are fixed-shape arrays stored consecutively, sample ii starts at byte

offset(i)=h+i⋅s,s=itemsize⋅∏j≥1dj,\text{offset}(i) = h + i \cdot s, \qquad s = \text{itemsize} \cdot \prod_{j \ge 1} d_j,

where hh is file header size and (d0,d1,… )(d_0, d_1, \dots) array shape. Reading a sample requires a seek and a read of ss bytes. This is the same stride arithmetic as the ndarray memory model, on a file rather than RAM. np.memmap (or np.load(ruta, mmap_mode="r")) does this for you: it returns an ndarray-like object whose data live on disk, and the operating system brings only touched pages into memory.

The next cell implements both protocols in pure Python and a hand-written lazy .npy reader (the browser does not allow mmap, so seek is explicit here).

[ ]The two protocols and lazy readingBrowser
import itertools, os, pickle, tempfile
import numpy as np

class Cuadrados:
    """Acceso por índice: basta con __len__ y __getitem__."""
    def __init__(self, n):
        self.n = n
    def __len__(self):
        return self.n
    def __getitem__(self, i):
        if not 0 <= i < self.n:
            raise IndexError(i)
        return i, i * i

class Contador:
    """Iterable: solo __iter__. No tiene longitud ni acceso aleatorio."""
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        for i in range(self.n):
            yield i, i * i

ds = Cuadrados(5)
print("len:", len(ds), "  ds[3]:", ds[3], "  list(ds):", list(ds))   # list() usa __getitem__ hasta IndexError
print("los tres primeros de un flujo de 10^12:", list(itertools.islice(Contador(10**12), 3)))

# Un .npy con 2000 secuencias de 64 tokens uint16 (250 KiB) y un lector perezoso
ruta = os.path.join(tempfile.gettempdir(), "tokens_l15.npy")
np.save(ruta, np.random.default_rng(0).integers(0, 50_000, size=(2000, 64), dtype=np.uint16))

class FilasNPY:
    """Lee la fila i de un .npy sin cargar el fichero: offset = cabecera + i * bytes por fila."""
    def __init__(self, ruta):
        self.ruta = ruta
        with open(ruta, "rb") as f:
            version = np.lib.format.read_magic(f)
            leer = np.lib.format.read_array_header_1_0 if version == (1, 0) else np.lib.format.read_array_header_2_0
            self.forma, _, self.dtype = leer(f)
            self.cabecera = f.tell()
        self.bytes_fila = int(np.prod(self.forma[1:])) * self.dtype.itemsize
        self.leidos = 0
        self._f = None                     # el fichero se abre al primer acceso, en el proceso que lo use

    def __len__(self):
        return self.forma[0]

    def __getitem__(self, i):
        if self._f is None:
            self._f = open(self.ruta, "rb")
        self._f.seek(self.cabecera + i * self.bytes_fila)
        buf = self._f.read(self.bytes_fila)
        self.leidos += len(buf)
        return np.frombuffer(buf, dtype=self.dtype).reshape(self.forma[1:])

lector = FilasNPY(ruta)
completo = np.load(ruta)
print("\nforma:", lector.forma, "  cabecera:", lector.cabecera, "B   fila:", lector.bytes_fila, "B")
print("la fila 1234 coincide con la del array en memoria:", np.array_equal(lector[1234], completo[1234]))
lector.leidos = 0
_ = lector[0], lector[7], lector[1999]
print("bytes leídos para 3 filas:", lector.leidos, "de", os.path.getsize(ruta))

# pickle guarda la clase por su nombre y el objeto por su estado, __getstate__(): eso es lo que viaja
# a cada trabajador cuando spawn envía el Dataset
try:
    pickle.dumps(lector.__getstate__())
except TypeError as e:
    print("\npickle del estado con el fichero abierto ->", e)

def sin_fichero(self):                  # la solución: no serializar el descriptor
    estado = self.__dict__.copy()
    estado["_f"] = None
    return estado
FilasNPY.__getstate__ = sin_fichero
datos = pickle.dumps(lector.__getstate__())
copia = FilasNPY.__new__(FilasNPY)      # lo que hace pickle al otro lado: objeto vacío y estado
copia.__dict__.update(pickle.loads(datos))
print("con __getstate__:", len(datos), "B serializados; la copia lee bien:", np.array_equal(copia[5], completo[5]))

Three details matter more than they seem. First, list(ds) works without __iter__: if an object does not define it, Python iterates by calling __getitem__(0), __getitem__(1)… until IndexError. Thus __getitem__ without bounds checks causes infinite loops. Second, the file opens on first access, not in the constructor. Third, an object with an open file cannot be serialized with pickle, and serializing the dataset is exactly how PyTorch sends it to each worker process. __getstate__ decides what travels: paths and metadata here, not the descriptor. With np.memmap something worse than an error occurs: a memmap does serialize, but copies all its data. You will check this in the lab with a 108 MiB file.

From index to batch: sampler, batch_sampler and collate_fn

DataLoader is a composition of three independently replaceable pieces. With indexed access and automatic batching, its core is this loop:

for indices in batch_sampler:                       # 1. qué muestras forman el lote: p. ej. [17, 3, 42, ...]
    muestras = [dataset[i] for i in indices]        # 2. el Dataset trae cada una
    lote = collate_fn(muestras)                     # 3. se juntan en tensores
    if pin_memory:
        lote = pin(lote)                            # 4. copia a memoria fijada (más abajo)
    yield lote

Constructor options are shortcuts to construct these pieces, so some are mutually exclusive: shuffle=True with a custom sampler raises ValueError, and passing a batch_sampler rules out batch_size, shuffle, sampler and drop_last. Each time you write for lote in dl, DataLoader creates a new iterator traversing the sampler again: an epoch.

Proof

(1) The batch sampler cuts the nn indices into qq full chunks and, if r>0r > 0, one of rr; drop_last decides whether the last is delivered. (2) A uniform permutation places each index in each of the nn positions with probability 1/n1/n, and it is dropped if in the final rr. Permutations across epochs are independent, so probabilities multiply. (3) Sequential order always places indices qB,…,n−1qB, \dots, n - 1 in the incomplete chunk.

∎

With n=10 001n = 10\,001 and B=64B = 64 there are q=156q = 156 steps and r=17r = 17: shuffling, each sample is missed in an epoch with probability 0.17 %0.17\,\%, and in two consecutive epochs with probability 2.9×10−62.9 \times 10^{-6}. Without shuffling, the same 17 are never seen. Keeping the final incomplete batch has a cost too: a gradient estimated from 17 instead of 64 samples has nearly four times the variance, and a one-sample batch makes BatchNorm fail in training mode.

What the model sees each epoch

Order matters. Stochastic gradient descent assumes each batch represents the data; if data are stored sorted by class, date or length and not shuffled, early steps each epoch see only part of the distribution and the gradient is biased.

InteractiveWhat does the model see each epoch?
DataLoader(ds, batch_size=B) # SequentialSampler
epoch 1batch 0012345batch 167891011batch 2121314151617discarded1819epoch 2batch 0012345batch 167891011batch 2121314151617discarded1819epoch 3batch 0012345batch 167891011batch 2121314151617discarded1819
draw 60 of 60
Times the model sees each sample, per epoch
012345678910111213141516171819epoch 1epoch 2epoch 3
  • class A (indices 0 to 14)
  • class B (indices 15 to 19)
  • repeated in epoch / never seen
Sampler
Index order
6
Generator
0
steps per epoch3 (2 discarded)
epoch 3: distinct samples seen18 of 20
epoch 3: repeats0
epoch 3: class B among seen17 % (data: 25 %)
never seen in the 3 epochs2
With the sequential sampler each epoch is identical and batches inherit the file order: the first contain only class A, while B is concentrated at the end, where drop_last always discards the same samples. If data is ordered by class, date or length, each step’s gradient is biased.
Twenty samples stored by class: the first 15 are class A and the last 5 B. Each row is an epoch, each box a batch and each cell an index; press play to watch them fall. Below is how often the model sees each sample per epoch: red borders mark repeats and empty cells unseen samples. Compare sequential and random samplers, inspect replacement, see how weighted sampling balances classes by repeating, and enable ‘Reseed at the start of each epoch’ to see what happens to the generator.

The four samplers meet different needs:

  • Sequential: for evaluation, where order does not matter and reproducibility helps.
  • Random without replacement (shuffle=True): the training standard. Each epoch is a permutation, so every sample is seen exactly once (except those dropped by drop_last).
  • Random with replacement (RandomSampler(ds, replacement=True)): each index is drawn independently. Bootstrap sampling is useful for resampling and arbitrary-sized epochs, but leaves a surprisingly large fraction of data unseen.
  • Weighted (WeightedRandomSampler(pesos, num_samples)): draws with probability proportional to a per-sample weight, by default with replacement. Weights inverse to class frequency make classes equally likely.
Proof

Each draw avoids sample ii with probability 1−1/n1 - 1/n, and the nn draws are independent, so the probability of always avoiding it is (1−1/n)n(1 - 1/n)^n. Since log⁡(1−x)≤−x\log(1 - x) \le -x for x∈[0,1)x \in [0, 1), nlog⁡(1−1/n)≤−1n\log(1 - 1/n) \le -1, hence (1−1/n)n≤e−1(1 - 1/n)^n \le e^{-1}. The sequence increases (by arithmetic-geometric mean applied to nn copies of 1−1/n1 - 1/n and one 1) and, by expansion nlog⁡(1−1/n)=−1−12n+O(n−2)n\log(1 - 1/n) = -1 - \tfrac{1}{2n} + \bigO(n^{-2}), converges to e−1e^{-1}. By linearity of expectation, the expected fraction seen is 1n∑iP(i sale)=1−(1−1/n)n\frac{1}{n}\sum_i \Pr(i \text{ sale}) = 1 - (1 - 1/n)^n, where the Spanish label means “appears.”

∎

Weighted sampling has the same property, amplified: with two classes forcibly balanced, each of the interactive’s 5 class-B samples appears on average 20⋅12⋅15=220 \cdot \tfrac{1}{2} \cdot \tfrac{1}{5} = 2 times per epoch, and each of 15 class-A samples 2/32/3 of a time. The model repeatedly sees the same minority images, which can resemble overfitting them. Weighting the loss (CrossEntropyLoss(weight=...)) avoids repeating data; the better choice depends on the problem.

Finally, the generator. Without an explicit generator, RandomSampler draws a new seed from PyTorch’s global generator at each epoch’s start. Thus a single torch.manual_seed(0) before the epoch loop makes the whole epoch sequence reproducible, while one inside the loop makes all epochs identical. The latter is a common mistake when “setting the seed for reproducibility,” shown by the figure’s checkbox. The complete seeding strategy, including workers, is covered in the reproducibility lesson.

collate_fn: from a list of samples to a batch

Thus if each sample is (imagen, etiqueta) with image shape 3×224×2243 \times 224 \times 224, the batch is (imágenes, etiquetas) with shapes B×3×224×224B \times 3 \times 224 \times 224 and BB. Two less obvious consequences: a NumPy float64 array becomes a float64 tensor, conflicting with model float32 weights or, if the model also becomes float64, making a consumer GPU like the lab’s tens of times slower (the familiar dtype promotion, now hidden in the loader); and torch.stack requires all pieces to have the same shape. Different-length sequences fail with RuntimeError: stack expects each tensor to be equal size.

Variable-length sequences

Sentences, documents, time series of different durations, molecules with different atom counts: many samples have no fixed shape. To operate on them in a tensor, bring them to a common length.

Mask and lengths contain the same information (Mbt=1[t<ℓb]M_{bt} = \ind[t \lt \ell_b], lengths[:, None] > np.arange(T) in NumPy), but different layers require one or the other: attention uses masks, packed RNNs (pack_padded_sequence) use lengths. No layer automatically knows what is padding. If a loss or mean traverses the entire tensor, padding contaminates the result; see transformer padding masks.

The cost of padding

Padding costs computation: the model performs the same operations on padding as on a real token. If a sequence of length ℓ\ell costs ℓk\ell^k (k=1k = 1 for per-token layers such as an MLP or convolution; k=2k = 2 for attention, whose cost grows with squared length), the fraction of epoch computation wasted on padding is

ωk=1−∑lotes∑bℓbk∑lotesB⋅Tlotek.\omega_k = 1 - \frac{\sum_{\text{lotes}} \sum_{b} \ell_b^k}{\sum_{\text{lotes}} B \cdot T_{\text{lote}}^k}.

The Spanish labels in the formula denote batches and batch length. One long sequence makes the entire batch pay for its length. How much is lost with random batches?

Proof

By the law of large numbers applied to numerator and denominator of ωk\omega_k divided by the batch count, ωk→1−B E[ℓk]/(B E[Tk])\omega_k \to 1 - B\,\E[\ell^k] / (B\,\E[T^k]), with TT the maximum of BB independent lengths. For ℓ∼Unif⁡(0,L)\ell \sim \Unif(0, L), E[ℓk]=1L∫0Lxk ⁣dx=Lkk+1\E[\ell^k] = \frac{1}{L}\int_0^L x^k \dd x = \frac{L^k}{k + 1}. The maximum satisfies P(T≤x)=(x/L)B\Pr(T \le x) = (x/L)^B, hence has density BxB−1/LBB x^{B-1}/L^B on (0,L)(0, L) and

E[Tk]=∫0Lxk BxB−1LB ⁣dx=BB+kLk.\E[T^k] = \int_0^L x^k \, \frac{B x^{B-1}}{L^B} \dd x = \frac{B}{B + k} L^k.

The ratio is E[ℓk]/E[Tk]=B+k(k+1)B\E[\ell^k]/\E[T^k] = \frac{B + k}{(k + 1)B}.

∎

With batches of 64 and attention, two thirds of computation goes to padding. Real lengths are not uniform but long-tailed (many short sentences and a few very long ones), making this worse: a batch maximum is almost always set by the tail.

InteractiveWasted padding
token position (0 to 128)ℓ690113932134424673583118251412152839T = max ℓ = 73
  • real token (mask True)
  • padding (mask False)
Padding in each batch of the epoch (64 batches, in delivery order)
0%50%100%epoch: 60 %first batchlast batch
Data and batches
Lengths
Batch formation
16
View
Cost of a sequence of length ℓ
0 of 63
batch shape16 × 73
padding in this batch57 %
waste in the epoch60 %
total compute per useful compute×2.47
mean length / mean batch T29.2 / 72.2
Random sampling: each batch is padded to its longest sequence, and one long sequence makes them all pay its length. Switch to “Bucketing”.
A sequence batch drawn row by row: blue is real tokens; stripes are padding to the longest. Each row is also a mask row. Below is padding for all batches in a 1024-sequence epoch. With random batches and lognormal lengths, over half the computation is padding; switch to ‘Bucketing’ and browse batches. Try attention cost, uniform lengths (the theoretical prediction appears among readings), and global ordering, which nearly eliminates padding at a price.

Grouping by length

The solution is batches of similarly sized sequences. Sorting the whole dataset by length minimizes padding but destroys randomness: batches are always the same and, if delivered in order, the model sees all short sentences first, then all long ones. Bucketing is the standard compromise:

  1. shuffle indices;
  2. split them into buckets of m⋅Bm \cdot B consecutive indices;
  3. sort each bucket by length and cut into mm batches;
  4. shuffle batches.

Each epoch remains different and each index appears exactly once, but lengths within a batch are similar. With m=50m = 50 and lognormal lengths, the cell below measures padding with B=16B = 16 falling from 60.5% to 6.1%: computation per useful token drops from 1/(1−0.605)≈2.51/(1 - 0.605) \approx 2.5 times to 1.071.07, nearly two and a half times less per epoch for the same model. The price is a batch-length correlation SGD does not expect (long-sentence batches have differently sized losses and gradients); in practice it is harmless with moderate mm. With variable batch size, another option fixes tokens per batch rather than sequences; LLM pretraining often goes further, concatenating documents without padding and using a document mask to prevent cross-document attention (sequence packing).

Implementation from scratch

All of the above fits in forty lines of Python. The next cell implements a loader with PyTorch’s semantics (sampler, batch sampler, shuffle, drop_last and collation with padding, mask and lengths) and checks it for three epochs.

[ ]A minimal DataLoaderBrowser
import random
import numpy as np

class SamplerSecuencial:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        return iter(range(self.n))
    def __len__(self):
        return self.n

class SamplerAleatorio:
    """Una permutación nueva en cada época, sacada de un generador que avanza."""
    def __init__(self, n, generador):
        self.n, self.g = n, generador
    def __iter__(self):
        idx = list(range(self.n))
        self.g.shuffle(idx)
        return iter(idx)
    def __len__(self):
        return self.n

class BatchSampler:
    def __init__(self, sampler, batch_size, drop_last):
        self.sampler, self.B, self.drop_last = sampler, batch_size, drop_last
    def __iter__(self):
        lote = []
        for i in self.sampler:
            lote.append(i)
            if len(lote) == self.B:
                yield lote
                lote = []
        if lote and not self.drop_last:
            yield lote
    def __len__(self):
        n = len(self.sampler)
        return n // self.B if self.drop_last else -(-n // self.B)

def collate_pad(muestras, pad=0):
    """[(secuencia, etiqueta), ...] -> x (B, T) con relleno, mask (B, T), lengths (B,), y (B,)."""
    seqs, ys = zip(*muestras)
    lengths = np.array([len(s) for s in seqs], dtype=np.int64)
    T = int(lengths.max())
    x = np.full((len(seqs), T), pad, dtype=np.int64)
    for b, s in enumerate(seqs):
        x[b, :len(s)] = s
    mask = np.arange(T) < lengths[:, None]               # True en los tokens reales
    return {"x": x, "mask": mask, "lengths": lengths, "y": np.array(ys)}

class MiniLoader:
    def __init__(self, dataset, batch_size=1, shuffle=False, drop_last=False, collate_fn=collate_pad, semilla=0):
        sampler = SamplerAleatorio(len(dataset), random.Random(semilla)) if shuffle else SamplerSecuencial(len(dataset))
        self.dataset, self.collate_fn = dataset, collate_fn
        self.batch_sampler = BatchSampler(sampler, batch_size, drop_last)
    def __iter__(self):
        for indices in self.batch_sampler:                # 1. el sampler decide qué índices
            muestras = [self.dataset[i] for i in indices]  # 2. el Dataset trae cada muestra
            yield self.collate_fn(muestras)              # 3. collate las junta en un lote
    def __len__(self):
        return len(self.batch_sampler)

class Frases:
    """Dataset de acceso por índice con secuencias de longitud variable."""
    def __init__(self, n, semilla=0):
        g = np.random.default_rng(semilla)
        self.lens = np.clip(g.lognormal(3.0, 0.6, size=n).astype(int), 1, 200)
        self.y = g.integers(0, 2, size=n)
    def __len__(self):
        return len(self.lens)
    def __getitem__(self, i):
        return list(range(1, self.lens[i] + 1)), int(self.y[i])   # tokens 1..l; el 0 es el relleno

lote = next(iter(MiniLoader(Frases(10), batch_size=4)))
print("longitudes:", lote["lengths"], "  x:", lote["x"].shape, "  mask.sum(1):", lote["mask"].sum(1))
print("máscara, columnas 14 a 28:\n", lote["mask"][:, 14:].astype(int))

# semántica de shuffle y drop_last durante tres épocas
ds = Frases(103)
for drop_last in (False, True):
    dl = MiniLoader(ds, batch_size=10, shuffle=True, drop_last=drop_last, semilla=1)
    print(f"\ndrop_last={drop_last}: len(dl) = {len(dl)}")
    for e in range(3):
        idx = [i for lote in dl.batch_sampler for i in lote]
        print(f"  época {e}: {len(idx)} índices, {len(set(idx))} distintos, empieza por {idx[:5]}")

With 103 samples and batches of 10, without drop_last there are 11 steps and the last has 3 samples; with drop_last there are 10 and each epoch omits 3 different samples. The generator advances each epoch, so permutations change, and the same seed repeats the full sequence. Now padding waste: uniform-length theory and buckets versus random batches on a long-tailed corpus.

[ ]Padding: theory, buckets and global orderBrowser
import numpy as np

def desperdicio(lotes, lens, k=1):
    """lotes: (num_lotes, B) de índices. Fracción del cómputo en relleno si una secuencia de longitud l cuesta l**k."""
    L = lens[lotes].astype(float)
    return 1 - (L ** k).sum() / (L.shape[1] * (L.max(axis=1) ** k).sum())

def lotes_aleatorios(n, B, g):
    return g.permutation(n).reshape(-1, B)

def lotes_por_cubos(lens, B, cubo, g):
    """Baraja, ordena por longitud dentro de cada cubo de cubo*B índices, trocea en lotes y baraja los lotes."""
    p = g.permutation(len(lens))
    partes = [p[s:s + cubo * B] for s in range(0, len(p), cubo * B)]
    lotes = np.concatenate([q[np.argsort(lens[q], kind="stable")] for q in partes]).reshape(-1, B)
    return lotes[g.permutation(len(lotes))]

g = np.random.default_rng(0)
uni = g.uniform(0, 1, size=196_608)                # longitudes continuas U(0, 1): la escala no importa
print("longitudes uniformes, lotes aleatorios: simulación frente a teoría")
for B in (4, 16, 64):
    lotes = lotes_aleatorios(len(uni), B, g)
    for k in (1, 2):
        print(f"  B = {B:2d}, coste l^{k}: {desperdicio(lotes, uni, k):.4f}   teoría 1 - (B+k)/((k+1)B) = {1 - (B + k) / ((k + 1) * B):.4f}")

lens = np.clip(np.round(np.exp(g.normal(3.2, 0.6, size=49_152))), 1, 512).astype(np.int64)   # como frases de un corpus
print(f"\nlongitudes lognormales: media {lens.mean():.1f}, mediana {np.median(lens):.0f}, máximo {lens.max()}")
for B in (16, 64):
    a = lotes_aleatorios(len(lens), B, g)
    c = lotes_por_cubos(lens, B, 50, g)
    s = np.argsort(lens, kind="stable").reshape(-1, B)
    for k in (1, 2):
        print(f"  B = {B}, coste l^{k}: aleatorio {desperdicio(a, lens, k):.1%}   por cubos {desperdicio(c, lens, k):.1%}   orden global {desperdicio(s, lens, k):.1%}")
print("\npor cubos, cada índice exactamente una vez:", np.array_equal(np.sort(c.ravel()), np.arange(len(lens))))

The simulation reproduces the formula within one thousandth or less. In the lognormal corpus, with B=64B = 64 and attention, random batches waste 89% of computation; buckets reduce it to 32% and global order to 3%. The difference between buckets and global ordering lies in tail batches: a 3200-sequence bucket contains few long sequences of very different lengths, and quadratic cost makes those differences matter greatly. Larger buckets approach global ordering at the cost of randomness.

Parallelism: worker processes

With num_workers = 0, the previous section’s loop runs in the main process, which also launches GPU kernels. With num_workers = W > 0, PyTorch starts WW Python processes and distributes work among them.

They are processes rather than threads because of the GIL: loading and transforms often use Python code (or libraries that do not release the GIL throughout), and threads would execute one at a time. Each worker calls torch.set_num_threads(1) at startup so WW processes do not each launch as many threads as the machine has cores.

How many workers are needed? Let LL be the time one worker takes to prepare a batch and GG the time GPU takes to consume it (copy plus compute).

Proof

Batch kk is prepared by worker k mod Wk \bmod W, which receives it when the main process consumes batch k−Wk - W (with prefetch_factor = 1 each worker has one task in flight and, since batch k−Wk - W was ready at Ok−WO_{k-W}, the worker is free). Thus batch kk is ready at Ok−W+LO_{k-W} + L. The main process requests it at Ok−1+GO_{k-1} + G and receives it at the later time.

Let τ=max⁡(G,L/W)\tau = \max(G, L/W) and a=max⁡0≤j<W(Oj−jτ)a = \max_{0 \le j \lt W}(O_j - j\tau). By induction, Ok≤a+kτO_k \le a + k\tau: true for k<Wk \lt W by definition of aa, and if true through k−1k - 1, then Ok−1+G≤a+(k−1)τ+τO_{k-1} + G \le a + (k-1)\tau + \tau and Ok−W+L≤a+(k−W)τ+WτO_{k-W} + L \le a + (k - W)\tau + W\tau. Conversely, iterating each maximum term separately, Ok≥O0+kGO_k \ge O_0 + kG and Ok≥Ok mod W+⌊k/W⌋L≥⌊k/W⌋LO_k \ge O_{k \bmod W} + \lfloor k/W \rfloor L \ge \lfloor k/W \rfloor L. Dividing by kk, lim inf⁡Ok/k≥max⁡(G,L/W)=τ≥lim sup⁡Ok/k\liminf O_k/k \ge \max(G, L/W) = \tau \ge \limsup O_k/k.

For the last claim, if W>PW > P the WW processes share PP cores and each batch takes L W/PL\,W/P, so L/WL/W becomes L/PL/P.

∎

The recurrence is linear in max-plus algebra, and this is its simplest result: throughput is set by the slowest cycle, GPU (GG per step) or workers (LL every WW steps). With the opening numbers, L≈52L \approx 52 ms and G≈18G \approx 18 ms (15 compute and 3 copy), so W∗=⌈2.85⌉=3W^\ast = \lceil 2.85 \rceil = 3, as in the initial figure with zero variability. Variable times require one or two more workers and prefetch_factor above 1: one worker’s slow batches are offset by another’s fast ones only with a queue. The theorem also says what does not help. Doubling batch size doubles LL and roughly GG, barely changing the decisive L/GL/G ratio. More workers than cores do not help either.

Windows, spawn and why Dataset must live in a module

On Linux workers are created by default with fork: an instant copy of the parent process, already holding everything defined so far. Windows has no fork; its only method is spawn, starting an empty Python interpreter. Three things happen so that interpreter can run the worker:

  1. If the main program is a .py file, the child reimports it as module __mp_main__. Everything outside if __name__ == "__main__": runs again in every worker; if that includes iterating a DataLoader with workers, the child tries to launch its own workers and Python stops it with RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase.
  2. The parent serializes with pickle the dataset, collate_fn and worker_init_fn and sends them. pickle stores functions and classes by name (module and attribute), so the child must be able to import them. A lambda or local function lacks an importable name and fails serialization.
  3. In a notebook, the main module is not a file: classes defined in a cell live in __main__, and the new interpreter cannot reconstruct them. The worker dies with AttributeError: Can't get attribute 'MiDataset' on <module '__main__'>, and the main process sees only RuntimeError: DataLoader worker exited unexpectedly.

The fix is always the same: Dataset, collate and any function sent to workers belong in an importable module, a datos.py file alongside the notebook (in Jupyter, a cell with %%writefile datos.py), imported in the notebook with from datos import MiDataset. Scripts also guard their entry point with if __name__ == "__main__":. The lab reproduces all three failures and the fix.

A fourth, less-known effect also follows from spawn. On Windows the parent writes the serialized dataset to a pipe, and the child does not start reading until it imports the main module, taking seconds with PyTorch. If the serialized object does not fit the pipe buffer, the parent’s write blocks until then, and workers that should start in parallel start one after another. On the lab machine, iterator creation with 4 workers rises from 0.05 s to over 10 s merely by storing 4096 labels as a 32 KiB array in the dataset. Another reason to store paths rather than data and use persistent_workers=True, paying startup once instead of once per epoch.

IterableDataset with multiple workers

With indexed access, the main process distributes indices and each sample loads once. An iterable has no indices to distribute: each worker receives its dataset copy and runs its own __iter__ from the start. Unless the iterable accounts for this, each sample appears WW times per epoch. Have __iter__ query torch.utils.data.get_worker_info(), which inside a worker returns its id and total num_workers, and have each traverse only its portion, usually a subset of files:

from torch.utils.data import IterableDataset, get_worker_info

class Fragmentos(IterableDataset):
    def __init__(self, rutas):
        self.rutas = rutas
    def __iter__(self):
        info = get_worker_info()
        mias = self.rutas if info is None else self.rutas[info.id::info.num_workers]
        for ruta in mias:
            yield from leer_ejemplos(ruta)

The next cell simulates distribution in pure Python (here “workers” run one after another, but the logic is the same) and a shuffle buffer, a way to shuffle a stream that does not fit in memory: keep a buffer of SS elements, repeatedly deliver one at random and replace it with the next stream item.

[ ]Worker sharding and buffer shufflingBrowser
import random
from collections import Counter

FRAGMENTOS = [f"shard-{s:03d}" for s in range(8)]          # 8 ficheros de 1000 ejemplos cada uno

def leer(fragmento):
    s = int(fragmento[-3:])
    for j in range(1000):
        yield s * 1000 + j                                  # el ejemplo número s*1000 + j del corpus

class Flujo:
    """Un IterableDataset de fragmentos. info = (id del trabajador, número de trabajadores) o None."""
    def __init__(self, fragmentos, repartir):
        self.fragmentos, self.repartir = fragmentos, repartir
    def iterar(self, info):
        mios = self.fragmentos
        if self.repartir and info is not None:
            wid, nw = info
            mios = self.fragmentos[wid::nw]                 # cada trabajador, sus fragmentos
        for f in mios:
            yield from leer(f)

def cargar(ds, num_workers):
    """Lo que entrega un DataLoader: cada trabajador ejecuta su propia copia de __iter__."""
    if num_workers == 0:
        return list(ds.iterar(None))
    salida = []
    for w in range(num_workers):
        salida += list(ds.iterar((w, num_workers)))
    return salida

for repartir in (False, True):
    vistos = cargar(Flujo(FRAGMENTOS, repartir), num_workers=4)
    veces = Counter(Counter(vistos).values())
    print(f"repartir={repartir}: {len(vistos)} ejemplos entregados, {len(set(vistos))} distintos, veces por ejemplo: {dict(veces)}")

def barajar_con_buffer(flujo, tam, g):
    """Barajado aproximado con memoria acotada: se entrega un elemento al azar del buffer y se repone."""
    buf = []
    for x in flujo:
        if len(buf) < tam:
            buf.append(x)
            continue
        j = g.randrange(tam)
        yield buf[j]
        buf[j] = x
    g.shuffle(buf)
    yield from buf

def corpus():
    for f in FRAGMENTOS:
        yield from leer(f)

g = random.Random(0)
for tam in (10, 1000, 8000):
    salida = list(barajar_con_buffer(corpus(), tam, g))
    desp = sorted(abs(pos - x) for pos, x in enumerate(salida))
    print(f"buffer {tam:5d}: desplazamiento mediano {desp[len(desp) // 2]:5d}, máximo {desp[-1]:5d}; "
          f"los 10 primeros salen de entre los {max(salida[:10]) + 1} primeros del flujo")

Without sharding, 4 workers deliver 32,000 examples from 8000 distinct ones, each exactly 4 times: the model trains four epochs for each one you think you run. Since each worker makes batches from its own stream and the loader delivers round-robin, each batch arrives four times in succession, once per worker. The buffer shows streaming shuffle’s limit: no element can move forward more than SS positions, because stream element tt does not enter the buffer until t−St - S have left. With S=10S = 10 order barely changes. Large datasets therefore shuffle at two levels: shard order each epoch and a buffer of thousands of examples within.

pin_memory and non_blocking

Copying a batch to GPU is not an ordinary memcpy. The GPU’s DMA engine reads RAM directly over PCIe and needs pinned (page-locked) memory: pages the operating system promises not to move or page to disk. Ordinary process memory is pageable, so copying from it forces the driver to use an intermediate pinned buffer: an extra CPU copy. On the lab machine, a batch of 64 3×224×2243 \times 224 \times 224 float32 images (36.75 MiB) takes 4.7 ms from pageable memory (8.2 GB/s) and 3.2 ms from pinned memory (12.1 GB/s, 77% of this GPU’s theoretical 15.75 GB/s PCIe 4.0 x8 link).

More important than bandwidth is synchronization, connecting to lesson 12’s device placement:

  • x.to("cuda") (with default non_blocking=False) waits for the copy to finish. Because the copy uses the same stream as kernels, it also waits for all queued GPU work: the entire previous step. CPU stalls and cannot prepare the next step.
  • x.to("cuda", non_blocking=True) from pinned memory queues the copy and returns immediately. CPU continues (requesting the next batch, launching kernels) and GPU performs the copy in turn.

That is why pin_memory=True and non_blocking=True go together: without pinned memory, non_blocking cannot truly be asynchronous; without non_blocking, pinned memory gains only bandwidth. Two nuances. Pinning costs time: the loader’s pin_memory thread copies each batch to a pinned buffer (1–3 ms for those 36.75 MiB in the lab), in parallel with everything else. Asynchronous copying on the default stream does not overlap GPU computation: it frees the CPU, not the bus. Overlapping copy and compute requires another stream, as in the next lesson’s asynchronous CUDA execution and stream overlap.

One way to reduce copying is to send images as uint8 and convert and normalize on GPU. That is 4 times fewer PCIe bytes (try it in the opening figure), and conversion is an elementwise kernel taking microseconds.

Diagnosis: is the GPU waiting for data?

The preceding tuning is unnecessary if training is not data-limited, and visual guesses are easily wrong. The measurement that matters is simple.

The subtlety is compute. CUDA operations are asynchronous, so the step’s Python code returns well before GPU finishes, and actual GPU time appears at synchronization (a loss.item(), a CPU copy, or next step’s next if the main process blocks there). For diagnosis, force synchronization at step end, knowing this removes any CPU-GPU overlap:

import time, torch

it = iter(loader)
for paso in range(50):
    t0 = time.perf_counter()
    x, y = next(it)                                     # espera de datos
    t1 = time.perf_counter()
    x, y = x.to(dev, non_blocking=True), y.to(dev, non_blocking=True)
    perdida = criterio(modelo(x), y)
    opt.zero_grad(set_to_none=True); perdida.backward(); opt.step()
    torch.cuda.synchronize()                            # solo al diagnosticar
    t2 = time.perf_counter()
    espera.append(t1 - t0); computo.append(t2 - t1)
# descarta los primeros pasos (arranque de trabajadores, autotuning, caché del asignador)

Two control measurements complete diagnosis and bound potential gains:

  1. Loader alone: iterate the DataLoader without a model to get maximum data throughput in batches per second.
  2. Model alone: repeat the step with a fixed batch already on GPU to get maximum compute throughput.

If the first is lower than the second, training is data-limited, and the throughput theorem says roughly how many workers are needed: ⌈L/G⌉\lceil L/G \rceil, where LL is one worker’s batch time and GG step time. If higher, data are not the problem and the model needs acceleration (mixed precision, torch.compile, better kernels), covered next. The detailed tool is the PyTorch profiler, whose traces show GPU gaps like the opening figure. nvidia-smi is a clue, not proof: its “utilization” is the fraction of time any kernel is active, and a tiny kernel counts like one saturating the GPU.

SymptomLikely causeWhat to try
high twt_w, few CPU cores busytoo few workersincrease num_workers to ⌈L/G⌉\lceil L/G \rceil plus one or two
high twt_w, all cores at 100%CPU saturatedcheaper transforms, precompute, move them to GPU
high twt_w, idle cores, disk saturateddisk readscontiguous binary formats, large shards, SSD cache
twt_w spikes at epoch startworker startuppersistent_workers=True, dataset cheap to serialize
small but irregular twt_wvariable-cost batcheshigher prefetch_factor, one more worker
tw≈0t_w \approx 0GPU bottleneckleave data pipeline and optimize model

Data that do not fit in RAM

A 2 TB dataset is streamed through rather than loaded. Three ideas make it possible, all returning to the rule that a dataset stores how to obtain data:

  • Contiguous binary formats. Millions of small files (one JPEG per image) are slow to open and list, especially on Windows. A large file with consecutive samples and an offset index works much better: a memory-mapped .npy for fixed-shape arrays, or indexed formats like Arrow or Parquet. For LLM pretraining, the entire tokenized corpus is one uint16 array on disk (2 bytes per token if the vocabulary fits 65,536 entries), and a batch is BB windows of T+1T + 1 tokens at random positions in an np.memmap: a Dataset per sample is unnecessary.
  • Shards. Split the corpus into files of hundreds of MB, distribute among workers (and with multiple GPUs among processes, distributed data loading), shuffle as units and read sequentially, where disks perform best.
  • Streaming. An IterableDataset reading shards in order, with two-level shuffling and get_worker_info partitioning, processes an arbitrarily large stream with constant memory: the algorithmic streaming model applied to data.

The professional version: torch.utils.data

ComponentWhat it doesWhen
Dataset, IterableDatasetthe two protocolsalways; iterable for streams and shards
DataLoader(..., batch_size, shuffle, drop_last)default sampler, batch sampler and collatecommon case
RandomSampler(ds, replacement, num_samples, generator)epoch permutation or draws with replacementpartial epochs, bootstrap
WeightedRandomSampler(pesos, num_samples)weighted draws, by default with replacementimbalanced classes
batch_sampler=custom batches (buckets, token counts)variable-length sequences
default_collate, collate_fn=combine samples into batchescustom collation for structures and padding
torch.nn.utils.rnn.pad_sequence(seqs, batch_first=True, padding_value, padding_side)pad a tensor listinside collate
num_workers, prefetch_factor, persistent_workersparallel loadingif twt_w is appreciable
pin_memory=True and .to(dev, non_blocking=True)asynchronous copiesGPU training
get_worker_info(), worker_init_fnpartitioning and setup per workeriterables, per-process resources

The following cells run in the local lab with PyTorch. The first reproduces with the library what you built by hand: steps per epoch, default collate and its limits, padding with a mask, and the attention convention error.

[ ]torch.utils.data versus what you already knowLocal GPU
import pickle, time
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, RandomSampler, WeightedRandomSampler, default_collate

# 1. pasos por época
print("pasos con 10001 muestras y lotes de 64:", len(DataLoader(range(10_001), batch_size=64, drop_last=True)),
      "con drop_last,", len(DataLoader(range(10_001), batch_size=64)), "sin él")
torch.manual_seed(0)
dl = DataLoader(range(10), batch_size=4, shuffle=True)
print("dos épocas con una semilla:", [b.tolist() for b in dl], [b.tolist() for b in dl])
torch.manual_seed(0)
print("misma semilla, otra vez:   ", [b.tolist() for b in dl])

# 2. default_collate: estructura recursiva, y float64 de NumPy que sigue siendo float64
lote = default_collate([(np.array([1.0, 2.0]), 3, {"id": "a"}), (np.array([4.0, 5.0]), 6, {"id": "b"})])
print("\ndefault_collate:", lote, " dtype:", lote[0].dtype)
try:
    default_collate([torch.ones(2), torch.ones(3)])
except RuntimeError as e:
    print("longitudes distintas ->", e)

# 3. relleno, máscara y longitudes con pad_sequence
seqs = [torch.tensor([5, 6, 7, 8]), torch.tensor([9]), torch.tensor([1, 2])]
x = pad_sequence(seqs, batch_first=True, padding_value=0)
lengths = torch.tensor([len(s) for s in seqs])
mask = torch.arange(x.shape[1]) < lengths[:, None]
print("\nx =", x.tolist(), "\nmask =", mask.int().tolist())

# 4. la misma máscara (True = token real) en dos APIs con convenciones opuestas
torch.manual_seed(0)
h = pad_sequence([torch.randn(5, 8), torch.randn(3, 8)], batch_first=True)    # (2, 5, 8)
m = torch.arange(5) < torch.tensor([5, 3])[:, None]
mha = torch.nn.MultiheadAttention(8, 2, batch_first=True).eval()
with torch.no_grad():
    bien, _ = mha(h, h, h, key_padding_mask=~m)          # MHA: True = ignorar
    mal, _ = mha(h, h, h, key_padding_mask=m)
    q = h[:, None]
    sdpa_bien = F.scaled_dot_product_attention(q, q, q, attn_mask=m[:, None, None, :])    # SDPA: True = participar
    sdpa_mal = F.scaled_dot_product_attention(q, q, q, attn_mask=~m[:, None, None, :])
print("\nMHA, primer token:  bien", bien[:, 0, :3].numpy().round(3).tolist(), "  mal", mal[:, 0, :3].numpy().round(3).tolist())
print("SDPA, primer token: bien", sdpa_bien[:, 0, 0, :3].numpy().round(3).tolist(), "  mal", sdpa_mal[:, 0, 0, :3].numpy().round(3).tolist())

# 5. con reemplazo y ponderado: qué fracción de los datos se ve en una época
n = 50_000
idx = torch.tensor(list(RandomSampler(range(n), replacement=True, num_samples=n, generator=torch.Generator().manual_seed(0))))
print(f"\ncon reemplazo: se ven {idx.unique().numel() / n:.3f} de las muestras (1 - 1/e = {1 - np.exp(-1):.3f})")
y = (torch.arange(n) >= 45_000).long()                   # clase 1: el 10 %
w = 1.0 / torch.bincount(y)[y].double()
idx = torch.tensor(list(WeightedRandomSampler(w, n, generator=torch.Generator().manual_seed(0))))
print(f"ponderado: clase 1 en el {y[idx].float().mean():.1%} de las extracciones")
for c, tam in ((0, 45_000), (1, 5_000)):
    sel = idx[y[idx] == c]
    print(f"  clase {c}: se ven {sel.unique().numel()} de sus {tam} muestras, {sel.numel() / tam:.2f} veces cada una en media")

# 6. la lista de tensores pequeños frente a un tensor
filas = [torch.zeros(4) for _ in range(20_000)]
t = time.perf_counter(); s1 = pickle.dumps(filas); t1 = time.perf_counter() - t
t = time.perf_counter(); s2 = pickle.dumps(torch.zeros(20_000, 4)); t2 = time.perf_counter() - t
print(f"\npickle de 20000 tensores de 4 floats: {t1 * 1e3:.0f} ms, {len(s1) / 1e6:.1f} MB;  un tensor 20000x4: {t2 * 1e3:.1f} ms, {len(s2) / 1e6:.2f} MB")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The weighted example makes it clear: the minority class rises from 10% of data to half the draws, and each of its 5000 samples appears about five times per epoch. The other side is the majority class: with 0.56 draws per sample on average, over half its 45,000 samples are unseen in the whole epoch (expected fraction e−0.56≈0.57e^{-0.56} \approx 0.57, the replacement theorem’s calculation). The attention cell shows both convention-error symptoms: nan on the unpadded sequence and silent zeros on the other.

Lab: saturating the RTX 4060

Now the real case: a Dataset reads 4096 3×96×963 \times 96 \times 96 uint8 images from disk with memory mapping, crops, flips and applies a Gaussian filter (a controlled-cost stand-in for actual decoding and augmentation, covered in image augmentation), and a small convolutional network. The goal: measure LL and GG, predict W∗W^\ast, verify it and document the configuration that works on this machine.

The first cell writes the importable module (a notebook’s %%writefile cell) and data, and measures both times with num_workers = 0. Notice three dataset choices: open memmaps on first access, use __getstate__ to prevent them traveling to workers, and use an index-derived augmentation generator so results do not depend on which worker processes the sample.

[ ]Lab 1: the data module and L and G timesLocal GPU
import pickle, sys, time, tempfile, textwrap
from pathlib import Path
import numpy as np
import torch
from torch import nn

DIR = Path(tempfile.gettempdir()) / "atlas_l15"
DIR.mkdir(exist_ok=True)
(DIR / "datos_l15.py").write_text(textwrap.dedent('''
    import numpy as np
    import torch
    from scipy import ndimage
    from torch.utils.data import Dataset

    class ImagenesEnDisco(Dataset):
        """Imágenes uint8 de un .npy en disco, leídas por índice con memoria mapeada."""

        def __init__(self, ruta_x, ruta_y, recorte=80, trabajo=3):
            self.ruta_x, self.ruta_y = str(ruta_x), str(ruta_y)
            self.recorte, self.trabajo = recorte, trabajo
            self.n = int(np.load(self.ruta_y, mmap_mode="r").shape[0])
            self._x = self._y = None          # se abren en cada proceso, la primera vez que hacen falta

        def __len__(self):
            return self.n

        def _abrir(self):
            if self._x is None:
                self._x = np.load(self.ruta_x, mmap_mode="r")
                self._y = np.load(self.ruta_y, mmap_mode="r")

        def __getstate__(self):               # lo que viaja a cada trabajador: rutas, no datos
            estado = self.__dict__.copy()
            estado["_x"] = estado["_y"] = None
            return estado

        def __getitem__(self, i):
            self._abrir()
            img = self._x[i].astype(np.float32) / 255.0          # lee solo los bytes de la muestra i
            g = np.random.default_rng(i)                        # aumentación determinista por índice
            f, c = g.integers(0, img.shape[1] - self.recorte + 1, size=2)
            img = img[:, f:f + self.recorte, c:c + self.recorte]
            if g.random() < 0.5:
                img = img[:, :, ::-1]
            for _ in range(self.trabajo):                       # coste de CPU: decodificar, aumentar...
                img = ndimage.gaussian_filter(img, sigma=(0, 1.0, 1.0))
            img = (img - 0.5) / 0.25
            return torch.from_numpy(np.ascontiguousarray(img)), int(self._y[i])

    def modelo():
        from torch import nn
        return nn.Sequential(
            nn.Conv2d(3, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1),
            nn.Flatten(), nn.Linear(128, 10))
''').lstrip(), encoding="utf-8")

N = 4096
rx, ry = DIR / "imagenes.npy", DIR / "etiquetas.npy"
if not rx.exists():                                     # 108 MiB, se escriben una sola vez
    x = np.lib.format.open_memmap(rx, mode="w+", dtype=np.uint8, shape=(N, 3, 96, 96))
    g = np.random.default_rng(0)
    for k in range(0, N, 512):
        x[k:k + 512] = g.integers(0, 256, size=(512, 3, 96, 96), dtype=np.uint8)
    x.flush(); del x
    np.save(ry, np.arange(N) % 10)

if str(DIR) not in sys.path:
    sys.path.insert(0, str(DIR))
import datos_l15
from datos_l15 import ImagenesEnDisco

ds = ImagenesEnDisco(rx, ry)
x0, y0 = ds[0]
print("una muestra:", tuple(x0.shape), x0.dtype, " etiqueta", y0, "   en disco:", round(rx.stat().st_size / 2**20), "MiB")
print("Dataset serializado:", len(pickle.dumps(ds)), "bytes")
mm = np.load(rx, mmap_mode="r")
print("un memmap serializado:", round(len(pickle.dumps(mm)) / 2**20), "MiB (copia todos los datos)")

t = time.perf_counter()
for i in np.random.default_rng(1).permutation(N)[:256]:
    ds[int(i)]
c = (time.perf_counter() - t) / 256
L = 128 * c
print(f"\ncarga por muestra: {c * 1e3:.2f} ms  ->  L (lote de 128, un proceso) = {L * 1e3:.0f} ms")

dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = datos_l15.modelo().to(dev)
opt = torch.optim.SGD(net.parameters(), lr=0.01)
xb, yb = torch.randn(128, 3, 80, 80), torch.randint(0, 10, (128,))
xp, yp = xb.pin_memory() if dev.type == "cuda" else xb, yb
def paso(x, y):
    x, y = x.to(dev, non_blocking=True), y.to(dev, non_blocking=True)
    perdida = nn.functional.cross_entropy(net(x), y)
    opt.zero_grad(set_to_none=True); perdida.backward(); opt.step()
for _ in range(10):
    paso(xp, yp)
if dev.type == "cuda": torch.cuda.synchronize()
t = time.perf_counter()
for _ in range(30):
    paso(xp, yp)
if dev.type == "cuda": torch.cuda.synchronize()
G = (time.perf_counter() - t) / 30
print(f"G (copia y paso en {dev}) = {G * 1e3:.1f} ms   ->  predicción: W* = ceil(L/G) = {int(np.ceil(L / G))}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On the lab machine, each sample costs 0.5–1 ms depending on the run (the processor mixes fast and slow cores and frequency depends on temperature), and a step about 25–30 ms, predicting W∗=3W^\ast = 3 to 6. Treat this as an estimate: a worker’s LL includes batch stacking and depends on core assignment, and the sweep table lets you infer it. The serialized dataset occupies hundreds of bytes, while a memmap of the same data serializes by copying its 108 MiB: if opened in the constructor, each worker would receive a complete copy.

The second cell reproduces spawn failures. To imitate a notebook it launches an interpreter with python -c, where, as in Jupyter, the main module is not a file.

[ ]Lab 2: spawn, notebooks and importable modulesLocal GPU
import subprocess, sys, tempfile
from pathlib import Path

DIR = Path(tempfile.gettempdir()) / "atlas_l15"

casos = {
    "Dataset definido en el notebook": """
import torch
from torch.utils.data import Dataset, DataLoader
class MiDataset(Dataset):
    def __len__(self): return 8
    def __getitem__(self, i): return i
print(next(iter(DataLoader(MiDataset(), batch_size=4, num_workers=2))))
""",
    "collate_fn con lambda": """
from torch.utils.data import DataLoader
from datos_l15 import ImagenesEnDisco
ds = ImagenesEnDisco("imagenes.npy", "etiquetas.npy")
print(next(iter(DataLoader(ds, batch_size=4, num_workers=2, collate_fn=lambda b: b)))[0][1])
""",
    "Dataset importado de un módulo": """
from torch.utils.data import DataLoader
from datos_l15 import ImagenesEnDisco
ds = ImagenesEnDisco("imagenes.npy", "etiquetas.npy")
x, y = next(iter(DataLoader(ds, batch_size=4, num_workers=2)))
print("lote", tuple(x.shape), "etiquetas", y.tolist())
""",
}
for nombre, codigo in casos.items():
    r = subprocess.run([sys.executable, "-c", codigo], cwd=DIR, capture_output=True, text=True, encoding="utf-8", timeout=180)
    errores = [l.strip() for l in r.stderr.splitlines() if "Error:" in l]
    print(f"{nombre}:\n   ", r.stdout.strip() if r.returncode == 0 else "  |  ".join(dict.fromkeys(errores)) or r.stderr[-300:])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The first case shows the typical pair of errors: worker AttributeError, the cause, and main-process RuntimeError, the only one visible in a notebook if the worker error does not reach the console. The second fails before startup when serializing the lambda. The third works, exactly what you would do in a notebook: module in a file and an import.

The third cell is the main experiment. It writes a script with if __name__ == "__main__": guard and runs it in a separate process for two reasons: real training (python train.py) and clean processes per configuration without kernel-state contamination. For each configuration it measures iterator creation, first batch, and median wait and compute per step. Finally it repeats one configuration with the “heavy” dataset (4096 labels stored as an array in the object).

[ ]Lab 3: num_workers and pin_memory sweepLocal GPU
import json, subprocess, sys, tempfile, textwrap
from pathlib import Path

DIR = Path(tempfile.gettempdir()) / "atlas_l15"
(DIR / "medir.py").write_text(textwrap.dedent('''
    import json, sys, time
    import numpy as np, torch
    from torch import nn
    from torch.utils.data import DataLoader
    from datos_l15 import ImagenesEnDisco, modelo

    def medir(ds, W, pin, pasos=24, B=128):
        dev = torch.device("cuda")
        torch.manual_seed(0)
        net = modelo().to(dev); opt = torch.optim.SGD(net.parameters(), lr=0.01)
        t0 = time.perf_counter()
        dl = DataLoader(ds, batch_size=B, shuffle=True, drop_last=True, num_workers=W,
                        pin_memory=pin, persistent_workers=W > 0)
        it = iter(dl)
        t_iter = time.perf_counter() - t0
        next(it)
        t_primero = time.perf_counter() - t0
        espera, computo = [], []
        for _ in range(pasos):
            a = time.perf_counter()
            x, y = next(it)                                   # espera de datos
            b = time.perf_counter()
            x, y = x.to(dev, non_blocking=pin), y.to(dev, non_blocking=pin)
            perdida = nn.functional.cross_entropy(net(x), y)
            opt.zero_grad(set_to_none=True); perdida.backward(); opt.step()
            torch.cuda.synchronize()                          # solo para medir
            c = time.perf_counter()
            espera.append(b - a); computo.append(c - b)
        e, k = float(np.median(espera[4:])), float(np.median(computo[4:]))
        return dict(W=W, pin=pin, iter=t_iter, primero=t_primero, espera=e, computo=k)

    if __name__ == "__main__":                                # imprescindible con spawn
        modo, rx, ry = sys.argv[1:4]
        ds = ImagenesEnDisco(rx, ry)
        if modo == "barrido":
            for W, pin in [(0, False), (0, True), (1, True), (2, True), (4, True), (6, True), (8, True), (6, False)]:
                print(json.dumps(medir(ds, W, pin)), flush=True)
        else:                                                 # el mismo Dataset con 4096 etiquetas en memoria
            ds.etiquetas = np.arange(len(ds), dtype=np.int64)
            print(json.dumps(medir(ds, 4, True, pasos=6)), flush=True)
''').lstrip(), encoding="utf-8")

def lanzar(modo):
    r = subprocess.run([sys.executable, "medir.py", modo, "imagenes.npy", "etiquetas.npy"],
                       cwd=DIR, capture_output=True, text=True, encoding="utf-8", timeout=900)
    if r.returncode != 0:
        raise RuntimeError(r.stderr[-1500:])
    return [json.loads(l) for l in r.stdout.splitlines() if l.startswith("{")]

filas = lanzar("barrido") + lanzar("pesado")
print(" W  pin    crear iter  primer lote  espera/paso  cómputo/paso  GPU calculando  muestras/s")
for m in filas:
    paso = m["espera"] + m["computo"]
    print(f"{m['W']:2d}  {str(m['pin']):5s}  {m['iter']:8.2f} s  {m['primero']:8.2f} s  {m['espera'] * 1e3:8.1f} ms"
          f"  {m['computo'] * 1e3:9.1f} ms  {m['computo'] / paso:12.0%}  {128 / paso:10.0f}")
print("\n(la última fila: el mismo Dataset con un array de 32 KiB dentro)")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lab runs show: with num_workers = 0, wait per step ranges from about 100 to 180 ms depending on run, versus about 25 ms compute, and GPU computes 13–20% of the time; with 1 worker wait is about L−GL - G, because the worker prepares the next batch during GPU computation, and with 2, about L/2−GL/2 - G. In a reference run those rows gave 134 and 25 ms, corresponding to L≈160L \approx 160 and L≈100L \approx 100 ms: worker LL depends on whether the system assigns a fast or slow core. With 4, waiting disappears (under 1 ms) and GPU reaches 99%, consistent with ⌈L/G⌉=⌈100/25⌉=4\lceil L/G \rceil = \lceil 100/25 \rceil = 4. From 4 to 8 only startup and memory change: the throughput theorem’s knee. First batch takes 4–8 s at any worker count, the cost of starting interpreters importing PyTorch and SciPy in parallel, and the heavy dataset row takes over 10 s just to create the iterator. Exact numbers vary between runs (laptop thermal management and antivirus), but the table’s shape does not.

The last cell measures copying itself: pageable versus pinned memory, synchronous versus asynchronous.

[ ]Lab 4: pageable versus pinned memoryLocal GPU
import time
import torch

if torch.cuda.is_available():
    dev = torch.device("cuda")
    x = torch.empty(64 * 3 * 224 * 224)                   # un lote de 64 imágenes float32: 36.75 MiB
    casos = {"paginable": x, "fijada": x.pin_memory()}
    y = torch.empty_like(x, device=dev)
    for nombre, src in casos.items():
        for nb in (False, True):
            for _ in range(3):
                y.copy_(src, non_blocking=nb)
            torch.cuda.synchronize()
            t = time.perf_counter()
            for _ in range(20):
                y.copy_(src, non_blocking=nb)
            vuelta = time.perf_counter() - t                  # lo que tarda la CPU en encolar las 20 copias
            torch.cuda.synchronize()
            total = (time.perf_counter() - t) / 20
            print(f"{nombre:9s} non_blocking={str(nb):5s}: {total * 1e3:5.2f} ms por copia ({x.numel() * 4 / total / 1e9:4.1f} GB/s);"
                  f"  la CPU queda libre tras {vuelta * 1e3:6.2f} ms")
    t = time.perf_counter(); x.pin_memory(); primera = time.perf_counter() - t   # reserva memoria fijada nueva
    t = time.perf_counter()
    for _ in range(10):
        x.pin_memory()                                     # reutiliza bloques de la caché de memoria fijada
    print(f"\nfijar el lote (lo que hace el hilo de pin_memory): {(time.perf_counter() - t) / 10 * 1e3:.1f} ms;"
          f" la primera vez, reservando, {primera * 1e3:.1f} ms")
else:
    print("sin GPU: esta celda no tiene nada que medir")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

From pinned memory with non_blocking=True, CPU is free in microseconds even though the copy takes the same time: that time lets the main process request the next batch and launch step kernels. With pageable memory, non_blocking changes little: CPU remains blocked during copying. The last line also shows why PyTorch caches pinned-memory blocks: allocating them is a driver call an order of magnitude more expensive than pinning a batch into an already allocated block.

With these measurements, the documented configuration for this machine (i9-14900HX with 24 cores, RTX 4060 Laptop, Windows) is:

# datos.py: el Dataset, la collate y worker_init_fn, nunca en el notebook
loader = DataLoader(
    ds, batch_size=128, shuffle=True, drop_last=True,
    num_workers=6,             # ceil(L/G) más uno o dos de margen; medir con el barrido
    pin_memory=True,           # y .to(dev, non_blocking=True) en el bucle
    persistent_workers=True,   # el arranque con spawn cuesta segundos: pagarlo una vez
    prefetch_factor=2,         # subir solo si la espera es irregular
)

Common mistakes

Exercises

NumericSteps per epoch
A training set has 10,001 samples. With batch_size=64 and drop_last=True, how many steps are in an epoch?
NumericWhat replacement leaves out
An epoch consists of n=50 000n = 50\,000 draws with replacement from 50,000 samples. What expected fraction of samples is unseen throughout the epoch? Answer between 0 and 1.
NumericHow many workers?
Loading and transforming an image costs 1.5 ms on one core, batches have 128 images, and a GPU step including copy takes 40 ms. With constant times and spare cores, what is the smallest num_workers for the GPU not to wait for data?
NumericPadding with quadratic cost
A batch has four sequences of lengths 12, 3, 7 and 2, padded to the longest. If a sequence of length ℓ\ell costs ℓ2\ell^2 (attention), what fraction of batch computation is wasted on padding? Answer between 0 and 1.
QuizThe notebook that cannot start workers
In a Windows Jupyter notebook you define class MiDataset(Dataset) in a cell and create DataLoader(MiDataset(), batch_size=32, num_workers=4). Iterating gives RuntimeError: DataLoader worker (pid(s) ...) exited unexpectedly. What is the cause and correct fix?
Quiz40 ms waiting, 15 ms computing
You instrument the loop (synchronizing at each step end) and measure median 40 ms waiting in next(iterador) and 15 ms compute per step with num_workers=2. CPU has idle cores. What do you try first and measure to confirm?
QuizAn IterableDataset with four workers
An IterableDataset reads 100 example files in order. With num_workers=0 an epoch has 1,000,000 examples; with num_workers=4 the loop processes 4,000,000 per epoch and validation loss worsens sooner. What happens?
QuizOne mask, two conventions
Your collate returns mask with True on real tokens. Which calls use it correctly?

More than one answer may be correct.

CodeCollation with padding, mask and lengths
Implement collate_pad(lote, pad=0). It receives a nonempty list of integer sequences (lists or 1D NumPy arrays of different lengths, possibly empty) and returns (x, mask, lengths): x is an int64 array of shape (B, T) with T the maximum length (0 if all are empty) and right padding with pad; mask is a same-shaped bool array with True on real tokens; lengths is an int64 array of shape (B,). Do not modify input sequences.
import numpy as np

def collate_pad(lote, pad=0):
  """Lista de B secuencias de enteros -> (x (B, T) int64, mask (B, T) bool, lengths (B,) int64)."""
  B = len(lote)
  # tu código: longitudes, T, relleno y máscara
  x = np.zeros((B, 1), dtype=np.int64)
  mask = np.ones((B, 1), dtype=bool)
  lengths = np.ones(B, dtype=np.int64)
  return x, mask, lengths
Shift+Enter to run
CodeA BucketBatchSampler
Implement class BucketBatchSampler(lengths, batch_size, bucket_size, drop_last=False, seed=0), a batch sampler grouping indices of similar length. Each epoch (each __iter__ call): shuffle indices 0,…,n−10, \dots, n-1 with a random.Random(seed) created in the constructor (advancing between epochs), split into buckets of bucket_size * batch_size consecutive indices, sort each bucket by length, cut into batch_size batches and shuffle the list of all batches. With drop_last=False each index must appear exactly once per epoch; with drop_last=True incomplete batches are discarded. __len__ must return the number of batches in an epoch.
import random

class BucketBatchSampler:
  def __init__(self, lengths, batch_size, bucket_size, drop_last=False, seed=0):
      self.lengths = list(lengths)
      self.B, self.m, self.drop_last = batch_size, bucket_size, drop_last
      self.g = random.Random(seed)

  def __iter__(self):
      n = len(self.lengths)
      # tu código: barajar, cubos, ordenar por longitud, trocear, barajar los lotes
      for s in range(0, n, self.B):
          yield list(range(s, min(s + self.B, n)))

  def __len__(self):
      return 0
Shift+Enter to run

Summary

Key idea
A data pipeline is a producer-consumer chain: the Dataset specifies how to obtain a sample, sampler and batch sampler decide which form each batch, collate combines them, and WW workers produce batches in parallel so GPU need not wait. Throughput is set by the slowest stage, max⁡(G,L/W)\max(G, L/W), identifiable only by measuring data wait per step.
  • A map-style dataset has __len__ and __getitem__; an iterable has __iter__. Both should store paths and metadata, not data: read lazily (memmap, seek) and open resources in the process using them.
  • DataLoader = sampler + batch sampler + collate. With drop_last there are ⌊n/B⌋\lfloor n/B \rfloor steps; without it, ⌈n/B⌉\lceil n/B \rceil. Replacement omits e−1≈37 %e^{-1} \approx 37\,\% of samples per epoch, and weighted sampling balances classes by repetition.
  • Variable-length sequences are combined with padding, mask and lengths. Random-batch padding can cost half of computation (two thirds for attention); length buckets reduce it substantially while retaining shuffling. Check each layer’s mask convention.
  • Workers are processes: ⌈L/G⌉\lceil L/G \rceil are needed; more do not help and cost RAM and startup. On Windows (spawn), Dataset and collate must live in an importable module, scripts need if __name__ == "__main__":, and persistent_workers=True helps with a lightweight-to-serialize dataset.
  • pin_memory=True with non_blocking=True frees CPU during copying; sending uint8 and normalizing on GPU divides PCIe bytes by 4.
  • For datasets larger than RAM: contiguous binary formats, shards partitioned among workers, and two-level shuffling (shards and buffer).