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.
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:
- 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%. - 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.
- The queue absorbs variability, not lack of capacity.
prefetch_factordoes 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 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
If samples are fixed-shape arrays stored consecutively, sample starts at byte
where is file header size and array shape. Reading a sample requires a seek and a read of 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).
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 indices into full chunks and, if , one of ; drop_last decides whether the last is delivered. (2) A uniform permutation places each index in each of the positions with probability , and it is dropped if in the final . Permutations across epochs are independent, so probabilities multiply. (3) Sequential order always places indices in the incomplete chunk.
With and there are steps and : shuffling, each sample is missed in an epoch with probability , and in two consecutive epochs with probability . 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.
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 bydrop_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 with probability , and the draws are independent, so the probability of always avoiding it is . Since for , , hence . The sequence increases (by arithmetic-geometric mean applied to copies of and one 1) and, by expansion , converges to . By linearity of expectation, the expected fraction seen is , 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 times per epoch, and each of 15 class-A samples 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 , the batch is (imágenes, etiquetas) with shapes and . 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 (, 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 costs ( for per-token layers such as an MLP or convolution; for attention, whose cost grows with squared length), the fraction of epoch computation wasted on padding is
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 divided by the batch count, , with the maximum of independent lengths. For , . The maximum satisfies , hence has density on and
The ratio is .
∎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.
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:
- shuffle indices;
- split them into buckets of consecutive indices;
- sort each bucket by length and cut into batches;
- shuffle batches.
Each epoch remains different and each index appears exactly once, but lengths within a batch are similar. With and lognormal lengths, the cell below measures padding with falling from 60.5% to 6.1%: computation per useful token drops from times to , 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 . 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.
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.
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 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 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 processes do not each launch as many threads as the machine has cores.
How many workers are needed? Let be the time one worker takes to prepare a batch and the time GPU takes to consume it (copy plus compute).
Proof
Batch is prepared by worker , which receives it when the main process consumes batch (with prefetch_factor = 1 each worker has one task in flight and, since batch was ready at , the worker is free). Thus batch is ready at . The main process requests it at and receives it at the later time.
Let and . By induction, : true for by definition of , and if true through , then and . Conversely, iterating each maximum term separately, and . Dividing by , .
For the last claim, if the processes share cores and each batch takes , so becomes .
∎The recurrence is linear in max-plus algebra, and this is its simplest result: throughput is set by the slowest cycle, GPU ( per step) or workers ( every steps). With the opening numbers, ms and ms (15 compute and 3 copy), so , 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 and roughly , barely changing the decisive 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:
- If the main program is a
.pyfile, the child reimports it as module__mp_main__. Everything outsideif __name__ == "__main__":runs again in every worker; if that includes iterating aDataLoaderwith workers, the child tries to launch its own workers and Python stops it withRuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. - The parent serializes with
picklethe dataset,collate_fnandworker_init_fnand sends them.picklestores functions and classes by name (module and attribute), so the child must be able to import them. Alambdaor local function lacks an importable name and fails serialization. - 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 withAttributeError: Can't get attribute 'MiDataset' on <module '__main__'>, and the main process sees onlyRuntimeError: 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 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 elements, repeatedly deliver one at random and replace it with the next stream item.
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 positions, because stream element does not enter the buffer until have left. With 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 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 defaultnon_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:
- Loader alone: iterate the
DataLoaderwithout a model to get maximum data throughput in batches per second. - 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: , where is one worker’s batch time and 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.
| Symptom | Likely cause | What to try |
|---|---|---|
| high , few CPU cores busy | too few workers | increase num_workers to plus one or two |
| high , all cores at 100% | CPU saturated | cheaper transforms, precompute, move them to GPU |
| high , idle cores, disk saturated | disk reads | contiguous binary formats, large shards, SSD cache |
| spikes at epoch start | worker startup | persistent_workers=True, dataset cheap to serialize |
| small but irregular | variable-cost batches | higher prefetch_factor, one more worker |
| GPU bottleneck | leave 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
.npyfor fixed-shape arrays, or indexed formats like Arrow or Parquet. For LLM pretraining, the entire tokenized corpus is oneuint16array on disk (2 bytes per token if the vocabulary fits 65,536 entries), and a batch is windows of tokens at random positions in annp.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
IterableDatasetreading shards in order, with two-level shuffling andget_worker_infopartitioning, processes an arbitrarily large stream with constant memory: the algorithmic streaming model applied to data.
The professional version: torch.utils.data
| Component | What it does | When |
|---|---|---|
Dataset, IterableDataset | the two protocols | always; iterable for streams and shards |
DataLoader(..., batch_size, shuffle, drop_last) | default sampler, batch sampler and collate | common case |
RandomSampler(ds, replacement, num_samples, generator) | epoch permutation or draws with replacement | partial epochs, bootstrap |
WeightedRandomSampler(pesos, num_samples) | weighted draws, by default with replacement | imbalanced classes |
batch_sampler= | custom batches (buckets, token counts) | variable-length sequences |
default_collate, collate_fn= | combine samples into batches | custom collation for structures and padding |
torch.nn.utils.rnn.pad_sequence(seqs, batch_first=True, padding_value, padding_side) | pad a tensor list | inside collate |
num_workers, prefetch_factor, persistent_workers | parallel loading | if is appreciable |
pin_memory=True and .to(dev, non_blocking=True) | asynchronous copies | GPU training |
get_worker_info(), worker_init_fn | partitioning and setup per worker | iterables, 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.
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")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 , 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 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 and , predict , 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.
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))}")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 to 6. Treat this as an estimate: a worker’s 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.
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:])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).
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)")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 , because the worker prepares the next batch during GPU computation, and with 2, about . In a reference run those rows gave 134 and 25 ms, corresponding to and ms: worker depends on whether the system assigns a fast or slow core. With 4, waiting disappears (under 1 ms) and GPU reaches 99%, consistent with . 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.
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")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
batch_size=64 and drop_last=True, how many steps are in an epoch?num_workers for the GPU not to wait for data?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?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?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?mask with True on real tokens. Which calls use it correctly?More than one answer may be correct.
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, lengthsBucketBatchSampler(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 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 0Summary
Dataset specifies how to obtain a sample, sampler and batch sampler decide which form each batch, collate combines them, and workers produce batches in parallel so GPU need not wait. Throughput is set by the slowest stage, , 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. Withdrop_lastthere are steps; without it, . Replacement omits 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: 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__":, andpersistent_workers=Truehelps with a lightweight-to-serialize dataset. pin_memory=Truewithnon_blocking=Truefrees CPU during copying; sendinguint8and 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).