Debugging numerical code and training runs
Training can fail silently or produce NaN hours later. Combine classical debugging with tracing the first NaN or Inf, sanity checks, gradient and activation instrumentation, and bisection to isolate the cause.
After this lesson you can
- Use breakpoint(), pdb, post-mortem debugging and conditional breakpoints in scripts and notebooks.
- Locate the first operation producing NaN or Inf with np.errstate, torch.autograd.detect_anomaly and hooks.
- Apply training sanity checks: expected initial loss, overfitting a batch, zero input and batch-example independence.
- Instrument training with per-layer gradient norms, update-to-weight ratio and activation statistics.
- Isolate failures by bisecting data, model and configuration to a minimal reproducible case.
Before you start
Motivation: training that works but is wrong
Ordinary code fails noisily: an exception, a traceback, a line number. Numerical code and, above all, training fail in two worse ways.
- Silently. Loss falls, accuracy rises and everything seems fine, but the model is worse than it should be. Labels shifted by one position, an extra softmax or a forgotten
model.eval()cause no error: they cost accuracy points, or a month believing the idea does not work. Karpathy summarizes it in his recipe for training networks: a misconfigured training run almost never complains, it just works a little worse. - Late. Three hours in, a
nanappears in the log. By the time you see it, NaN has contaminated all weights and the step producing it was lost thousands of steps ago. Reproducing it costs another three hours.
Both have the same remedy: do not debug on the full training run. A debugging cycle is worth the time it takes to give an answer, and the difference between a hypothesis checked in three seconds and one checked in three hours is the difference between solving the problem today and not solving it. This lesson gathers tools to shorten that cycle:
- Classic debugging, inspecting program state at the exact failure point:
breakpoint(),pdb, post mortem and conditional breakpoints. - Tracing nonfinite values back to the first operation producing them.
- Sanity checks that in seconds show the pipeline is broken (or give confidence it is not) before spending a single GPU hour.
- Per-layer instrumentation, showing symptoms before they reach the loss.
- Bisection: halve data, model and configuration until a minimal reproducible case remains.
Everything builds on the training loop, backward semantics and module hooks you already know.
Interactive debugging: breakpoint(), pdb and post mortem
print is the most widely used debugging tool and one of the worst for numerical code: you must decide beforehand what to print, each new question requires rerunning, and an entire printed tensor is unreadable. A debugger stops the program and lets you ask any questions you want about the real state at that point: shapes, dtypes, devices, values, the call stack that led there.
breakpoint() and the commands that matter
Since Python 3.7, breakpoint() on any line stops the program and opens pdb. It calls sys.breakpointhook(), which checks environment variable PYTHONBREAKPOINT: with PYTHONBREAKPOINT=0 all calls are ignored (useful for leaving a point in code without interference), and PYTHONBREAKPOINT=IPython.core.debugger.set_trace opens IPython’s debugger, with colors and autocomplete. Once inside, a dozen commands cover almost everything:
| command | what it does |
|---|---|
p expr, pp expr | evaluate and print an expression (pp, formatted) |
n, s, c | next line without entering calls, entering them, continue to next breakpoint |
r, unt | until the current function returns; until a line after the current one (leave a loop) |
w, u, d | call stack; move up and down it to inspect the caller’s frame |
l, ll | code around current line; entire function |
b fichero:línea, cond | breakpoint, optionally conditional |
tbreak, cl, condition n cond | temporary breakpoint, clear breakpoints, change breakpoint n’s condition |
display expr | reprint expr each time execution stops if it changed |
interact | open an interpreter with current frame variables |
!sentencia | execute a Python statement (for example an assignment pdb would confuse with a command) |
Two save the most time in numerical code. u lets you move from the low-level function where the error occurs (a matrix multiplication with incompatible shapes) to your calling code’s frame, where meaningful variables live. And interact opens a full interpreter in that frame: recalculate with a different shape, try a fix and see if it gives the expected result, without rerunning anything.
Post mortem: examining the program after failure
The second is most valuable because it does not require knowing beforehand where to look. Variants you will use:
- In a script,
python -m pdb -c continue entrenar.py --argsruns the program normally and, if it ends with an uncaught exception, opens the debugger in the frame where it was raised. - In a notebook, after a failed cell, the magic
%debugopens the debugger on the last exception, and%pdb ondoes so automatically on every failure. In a normal Python session, the equivalent isimport pdb; pdb.pm(). - In code,
pdb.post_mortem(e.__traceback__)inside anexceptopens the debugger on that exception while still handling it.
The next cell does this with a real preprocessing script written in its own file. Since a cell has no keyboard, we pass pdb the commands you would type, and output is exactly what you would see in a terminal.
import io, os, sys, pdb, importlib
# un script de preprocesado con un fallo, en su propio fichero, como en un proyecto real
with open("prep.py", "w", encoding="utf-8") as f:
f.write('''\
def estandarizar(filas):
salida = []
for i, fila in enumerate(filas):
media = sum(fila) / len(fila)
var = sum((v - media) ** 2 for v in fila) / len(fila)
salida.append([(v - media) / var ** 0.5 for v in fila])
return salida
''')
sys.path.insert(0, os.getcwd())
importlib.invalidate_caches()
import prep
importlib.reload(prep)
datos = [[1.0, 2.0, 3.0], [0.5, 1.5, 4.0], [4.0, 4.0, 4.0], [2.0, 0.0, 1.0]]
def sesion(comandos, arrancar):
"""Ejecuta pdb con los comandos dados como si los teclearas y devuelve lo que habría mostrado."""
salida = io.StringIO()
dbg = pdb.Pdb(stdin=io.StringIO(comandos), stdout=salida)
try:
arrancar(dbg)
except Exception:
pass
return salida.getvalue()
# 1) post mortem: el programa ya ha fallado y examinamos el marco donde murió
try:
prep.estandarizar(datos)
except ZeroDivisionError as e:
tb = e.__traceback__
print("excepción:", repr(e))
def pm(dbg):
dbg.reset()
dbg.interaction(None, tb)
print(sesion("p i, fila\np media, var\nq\n", pm))
# 2) punto de ruptura condicional: parar solo cuando la varianza sea nula, antes de dividir
def condicional(dbg):
dbg.set_break(prep.__file__, 6, cond="var == 0")
dbg.runcall(prep.estandarizar, datos)
print(sesion("c\np i, fila, var\nq\n", condicional))The first session answers in two commands what would have taken two runs with print: failure is in row 2, which is constant, and its variance is exactly 0. In the second, the conditional breakpoint stops the program immediately before division, in the only iteration that matters, even if the loop had a million rows.
Conditional breakpoints and their cost
A pdb conditional breakpoint (b entrenar.py:57, not math.isfinite(loss)) has a drawback: to know whether to stop, the debugger must monitor execution line by line, and its condition is evaluated in Python each time the line is reached. The alternative is to write the condition in the code itself:
if not math.isfinite(loss.item()):
breakpoint()
When the condition is false, it costs the same as any if. The difference is large:
import io, os, sys, time, pdb, importlib
with open("bucle.py", "w", encoding="utf-8") as f:
f.write('''\
def paso(x):
y = 0.0
for k in range(20):
y += (x * k) % 7
return y
def bucle(n=20_000):
for i in range(n):
r = paso(i * 0.5)
if r != r:
breakpoint()
''')
sys.path.insert(0, os.getcwd())
importlib.invalidate_caches()
import bucle
importlib.reload(bucle)
def medir(f):
t0 = time.perf_counter()
f()
return time.perf_counter() - t0
t_base = medir(bucle.bucle) # la condición r != r (cierta solo si r es NaN) en el código
def bajo_pdb():
dbg = pdb.Pdb(stdin=io.StringIO("c\n"), stdout=io.StringIO())
dbg.set_break(bucle.__file__, 10, cond="r != r") # la misma condición, evaluada por pdb
dbg.runcall(bucle.bucle)
t_pdb = medir(bajo_pdb)
print(f"condición en el código: {t_base:.3f} s")
print(f"condición en pdb: {t_pdb:.3f} s ({t_pdb / t_base:.0f}×)")In the browser it comes out about ten times slower, and in CPython 3.13 on a laptop, about thirty. In a training loop, where almost all time is spent outside Python, the relative penalty is smaller, but the rule is the same: debugger conditional breakpoints are for code executed few times; for monitoring a hot loop, put the condition in code.
Two details of the cell. r != r is the cheapest way to ask whether a float is NaN, because NaN is the only value unequal to itself. And a pdb breakpoint condition that raises an exception (for example because the variable does not yet exist on that line) is treated as true: the debugger stops. A common mistake is placing a breakpoint one line before the variable is defined.
The editor debugger, notebooks and processes other than yours
Graphical debuggers (VS Code’s, which uses debugpy, or PyCharm’s) do the same as pdb with a better interface: variable inspection, conditional breakpoints and logpoints (which print without stopping), and in VS Code, “Debug Cell” to debug a notebook cell. Two settings matter in ML. By default they stop only in your code ("justMyCode": true); to enter PyTorch or a library, disable it. And an exception caught by a library is invisible unless you enable breaking on caught exceptions.
The most puzzling failures happen outside the main process:
- DataLoader processes. With
num_workers > 0, yourDatasetcode runs in separate processes, and abreakpoint()there has no terminal. To debug loading,num_workers=0: everything returns to the main process. - CUDA errors. Kernels launch asynchronously, and an error like
device-side assert triggered(typical of an out-of-range label incross_entropyor an out-of-range index in anEmbedding) is reported on a later operation. WithCUDA_LAUNCH_BLOCKING=1each launch waits for the previous one and the traceback points to the culprit. Simpler still: reproduce on CPU, where the offending operation immediately raises anIndexError(withcross_entropy, even showing the out-of-range label in the message). - Hung or dying processes. A blocked DataLoader or
all_reducethat never returns throws nothing.python -X faulthandlerdumps the Python stack of all threads if the process dies from a signal (a segmentation fault in a C extension, for example). For hangs,faulthandler.dump_traceback_later(600)sets a timer dumping it after ten minutes; if called again at each step’s start, the timer resets and fires only when a step takes more than ten minutes. Andpy-spy dump --pid PIDdumps it from outside, without stopping or modifying the process (the sampling profiler from lesson 17).
Hunting NaN and Inf
A NaN is not an error: it is a value. IEEE 754 defines which operations produce it, and almost all others propagate it.
import warnings
import numpy as np
warnings.simplefilter("ignore") # aquí queremos ver los valores, no los avisos
f32 = np.float32
casos = {
"exp(89) en float32": np.exp(f32(89)),
"exp(12) en float16": np.exp(np.float16(12)),
"exp(-104) en float32": np.exp(f32(-104)),
"1 / 0": f32(1) / f32(0),
"0 / 0": f32(0) / f32(0),
"inf - inf": np.inf - np.inf,
"0 * inf": 0.0 * np.inf,
"log(0)": np.log(f32(0)),
"log(-1)": np.log(f32(-1)),
"sqrt(-1)": np.sqrt(f32(-1)),
}
for k, v in casos.items():
print(f"{k:22s} -> {v}")
nan = float("nan")
print("\nNaN se propaga... salvo cuando no:")
print("nan + 1 =", nan + 1, " nan * 0 =", nan * 0, " nan == nan:", nan == nan)
print("max(nan, 1) =", max(nan, 1.0), " max(1, nan) =", max(1.0, nan))
print("np.maximum(nan, 1) =", np.maximum(nan, 1.0), " np.fmax(nan, 1) =", np.fmax(nan, 1.0))
print("np.argmax([1, nan, 3]) =", np.argmax([1.0, nan, 3.0]), " np.nanargmax =", np.nanargmax([1.0, nan, 3.0]))
print("np.clip(nan, -1, 1) =", np.clip(nan, -1, 1), " np.where(False, nan, 0) =", np.where(False, nan, 0.0))The table reveals the three usual sources in a network. Overflow produces Inf: overflows in float32 from , and in float16 from , because the float16 maximum is 65504. Underflow produces exact 0: is already 0 in float32, and a 0 where a positive probability was expected becomes when taking the logarithm. And indeterminate forms produce NaN: , , , square root or logarithm of a negative number. Inf rarely lasts: once subtracted from itself (during normalization) or multiplied by 0 (in backward), it becomes NaN.
Propagation has misleading exceptions. Python’s max depends on argument order, because it compares with > and every comparison with NaN is false. np.argmax treats NaN as the maximum and returns its index, so a class prediction calculated with argmax on NaN logits gives no error: it gives the class containing the first NaN. And where discards a NaN from the unchosen branch in forward but, as we will see, not in backward.
One NaN contaminates an entire step
The important word is “first”. Because of propagation, once a tensor has a NaN, everything depending on it does too, and in a training step everything depends on everything. The interactive shows this with four real failures hidden in a small network.
Three things the figure teaches and worth retaining:
- Forward contaminates the entire backward. If a forward tensor is NaN, the gradient of everything upstream is too, because the chain rule multiplies by derivatives evaluated at NaN values. And one batch row suffices: sums over examples, so a single example with NaN makes all weight gradients NaN.
- One step erases the trail. The optimizer converts NaN gradients into NaN weights, and in the next step the first layer produces NaN with any input. If you search for the origin at step , or any later step, you will always find the first layer. Capture the exact step when the first nonfinite value appears: save that batch and model and optimizer state before taking the step, what lesson 21 calls exact resumption.
- Clean forward does not guarantee clean backward. With
torch.where(h > 0, torch.sqrt(h), 0), forward is flawless: the branch with the square root of negatives is calculated (and is NaN), butwherediscards it. In backward,wheresends gradient 0 to that branch, and the square-root derivative multiplies it by , which is NaN: . Loss at step is finite and weights at step are not.
The probe hunt answers the practical question of how expensive finding the origin is. If each check requires rerunning until failure, bisection is optimal: probe the middle of the candidates and keep the half containing the origin. With 25 positions, 5 probes suffice. But hooks let you probe all positions in a single run, so the cost lies in reproducing failure, not probe count. Bisection again becomes essential when each test is expensive and cannot be parallelized: a code version, configuration subset, data segment. We will see it at the end of the lesson.
np.errstate: turn the first NaN into an exception
In NumPy, the first nonfinite value can become an exception. np.errstate controls NumPy’s response to each class of floating-point event (divide, over, under, invalid): ignore it, warn or raise FloatingPointError at the exact operation producing it. Underflow is almost always harmless and left on ignore.
import numpy as np
import traceback
rng = np.random.default_rng(0)
def capa_norm(h):
mu = h.mean(axis=1, keepdims=True)
var = h.var(axis=1, keepdims=True)
return (h - mu) / np.sqrt(var) # sin epsilon
def softmax(z):
e = np.exp(z - z.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
def forward(X, W1, W2, y):
h = np.maximum(capa_norm(X @ W1), 0.0)
p = softmax(h @ W2)
return -np.log(p[np.arange(len(y)), y]).mean()
X = rng.normal(size=(8, 5)).astype(np.float32)
X[5] = 0.0 # una fila de relleno
W1 = rng.normal(size=(5, 16)).astype(np.float32)
W2 = rng.normal(size=(16, 4)).astype(np.float32)
y = rng.integers(0, 4, size=8)
with np.errstate(all="ignore"):
print("pérdida:", forward(X, W1, W2, y)) # nan, sin pista de dónde
with np.errstate(divide="raise", over="raise", invalid="raise", under="ignore"):
try:
forward(X, W1, W2, y)
except FloatingPointError as e:
marco = traceback.extract_tb(e.__traceback__)[-1]
print(f"FloatingPointError: {e}")
print(f" en {marco.name}(), línea {marco.lineno}")npm run lab and open the connection link.The exception points to division in capa_norm: the padding row, multiplied by , gives a zero vector, its variance is 0 and normalization calculates . With a traceback, the rest is %debug and u. This cell runs in the local lab because it does not work in the browser: NumPy is compiled to WebAssembly, which does not expose the processor’s floating-point exception flags, and np.errstate cannot know anything went wrong.
torch.autograd.detect_anomaly
PyTorch has no forward equivalent of errstate. It offers torch.autograd.detect_anomaly() (or set_detect_anomaly(True)), which does two things: during forward, save the Python stack of every operation creating a graph node; during backward, check each backward function’s output and, if it contains NaN, raise an error with the function name and forward stack that created it.
import time, warnings
import torch
def where_con_raiz():
x = torch.tensor([-1.0, 4.0], requires_grad=True)
return torch.where(x > 0, torch.sqrt(x), torch.zeros_like(x)).sum()
def log_de_softmax_nulo():
z = torch.tensor([[0.0, 110.0]], requires_grad=True)
p = torch.softmax(z, dim=-1) # p[0, 0] = exp(-110) = 0 en float32
return -torch.log(p)[0, 0]
def log_de_cero():
p = torch.tensor([0.0, 1.0], requires_grad=True)
return -torch.log(p).sum()
for f in (where_con_raiz, log_de_softmax_nulo, log_de_cero):
with warnings.catch_warnings(record=True) as avisos, torch.autograd.detect_anomaly():
warnings.simplefilter("always")
try:
loss = f()
loss.backward()
print(f"{f.__name__:20s} pérdida = {loss.item()}: backward sin error")
except RuntimeError as e:
print(f"{f.__name__:20s} RuntimeError: {str(e).splitlines()[0]}")
# detect_anomaly emite como aviso la pila del forward de la operación culpable
pila = [str(a.message) for a in avisos if "Traceback of forward" in str(a.message)]
lineas = pila[-1].splitlines()
k = max(i for i, l in enumerate(lineas) if l.strip().startswith("File "))
print(" " * 21 + "su forward:", lineas[k].strip().split(", ", 1)[1])
def coste(dev, anomalia, n=30):
torch.manual_seed(0)
capas = [torch.nn.Sequential(torch.nn.Linear(512, 512), torch.nn.ReLU()) for _ in range(8)]
m = torch.nn.Sequential(*capas, torch.nn.Linear(512, 10)).to(dev)
opt = torch.optim.SGD(m.parameters(), lr=1e-3)
X = torch.randn(256, 512, device=dev)
Y = torch.randint(0, 10, (256,), device=dev)
def paso():
opt.zero_grad()
torch.nn.functional.cross_entropy(m(X), Y).backward()
opt.step()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
with torch.autograd.set_detect_anomaly(anomalia):
for _ in range(5):
paso()
if dev == "cuda":
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(n):
paso()
if dev == "cuda":
torch.cuda.synchronize()
return (time.perf_counter() - t0) / n * 1e3
print()
for dev in ["cpu"] + (["cuda"] if torch.cuda.is_available() else []):
a, b = coste(dev, False), coste(dev, True)
print(f"{dev:4s}: paso normal {a:6.2f} ms, con detect_anomaly {b:6.2f} ms ({b / a:.1f}×)")npm run lab and open the connection link.The output shows its three limits. First, it only looks at backward and only searches for NaN: log_de_cero produces loss and gradient , and detect_anomaly says nothing. Second, it names the first backward function producing a NaN, which need not be the origin: in zero softmax, NaN is born in SoftmaxBackward0 when multiplying , but the problem is the logarithm, which should be log_softmax. Third, it is expensive: it multiplies step time severalfold on CPU and by ten or more on GPU, because it saves a Python stack per operation and synchronizes on every check. This is a tool for the reduced case, never to leave enabled during normal training.
Hooks checking isfinite layer by layer
The most flexible tool is one you build with hooks: a forward hook on each module checking torch.isfinite on its output, a backward hook checking gradients with respect to inputs, and a hook on each parameter for its gradient. On first failure, log module, phase, input and output statistics and the line of your code from which the module was called. This is the lesson’s first lab.
import os, time, traceback, warnings
from collections import OrderedDict
import torch
import torch.nn as nn
warnings.filterwarnings("ignore", message="Full backward hook is firing")
_TORCH = os.path.dirname(torch.__file__) # para quitar de la pila los marcos internos
def _tensores(obj):
if torch.is_tensor(obj):
return [obj] if obj.is_floating_point() else []
if isinstance(obj, (tuple, list)):
return [t for o in obj for t in _tensores(o)]
return []
def _resumen(ts):
out = []
for t in ts:
t = t.detach()
fin = t[torch.isfinite(t)]
out.append(dict(forma=tuple(t.shape), nan=int(torch.isnan(t).sum()), inf=int(torch.isinf(t).sum()),
min=round(fin.min().item(), 3) if fin.numel() else None,
max=round(fin.max().item(), 3) if fin.numel() else None))
return out
class DetectorNoFinitos:
"""Hooks que registran el primer valor no finito: módulo, fase, estadísticas y pila del forward."""
def __init__(self, modelo, pilas=True):
self.informe, self.pilas, self._pila_fwd, self._h = None, pilas, {}, []
for nombre, m in modelo.named_modules():
if nombre: # la raíz repetiría lo que dicen sus hijos
self._h.append(m.register_forward_hook(self._fwd(nombre)))
self._h.append(m.register_full_backward_hook(self._bwd(nombre)))
for nombre, p in modelo.named_parameters():
self._h.append(p.register_hook(self._grad_param(nombre)))
def _fallo(self, **info):
if self.informe is None: # solo el primero: el resto es contagio
self.informe = info
def _fwd(self, nombre):
def hook(mod, args, out):
if self.pilas: # dónde se llamó a este módulo en el forward
pila = traceback.extract_stack(limit=12)[:-1] # sin este hook
self._pila_fwd[nombre] = [f for f in pila if not f.filename.startswith(_TORCH)]
outs = _tensores(out)
if self.informe is None and not all(bool(torch.isfinite(t).all()) for t in outs):
self._fallo(modulo=nombre, fase="forward", entrada=_resumen(_tensores(args)),
salida=_resumen(outs), pila=self._pila_fwd.get(nombre))
return hook
def _bwd(self, nombre):
def hook(mod, grad_input, grad_output):
gi = _tensores([g for g in grad_input if g is not None])
if self.informe is None and not all(bool(torch.isfinite(t).all()) for t in gi):
self._fallo(modulo=nombre, fase="backward",
entrada=_resumen(_tensores([g for g in grad_output if g is not None])),
salida=_resumen(gi), pila=self._pila_fwd.get(nombre))
return hook
def _grad_param(self, nombre):
def hook(g):
if self.informe is None and not bool(torch.isfinite(g).all()):
self._fallo(modulo=nombre, fase="gradiente de parámetro", entrada=[], salida=_resumen([g]), pila=None)
return hook
def quitar(self):
for h in self._h:
h.remove()
# tres fallos de la figura del NaN, escritos como módulos
class LNSinEps(nn.Module):
def forward(self, h):
mu = h.mean(-1, keepdim=True)
var = h.var(-1, keepdim=True, unbiased=False)
return (h - mu) / var.sqrt() # 0/0 si la fila es constante
class RaizPositiva(nn.Module):
def forward(self, h):
return torch.where(h > 0, h.sqrt(), torch.zeros_like(h))
class LogProbs(nn.Module):
def forward(self, z):
return torch.log(torch.softmax(z, dim=-1)) # -inf si una probabilidad se anula
def red(act):
torch.manual_seed(0)
return nn.Sequential(OrderedDict(lin1=nn.Linear(8, 16), ln=LNSinEps(), act=act,
lin2=nn.Linear(16, 4), logp=LogProbs()))
def casos():
x = torch.randn(6, 8)
y = torch.randint(0, 4, (6,))
m = red(nn.ReLU())
x[2] = 0.0 # una fila de relleno...
m.lin1.bias.data[:] = 0.0 # ...sale de lin1 como un vector constante
yield "varianza nula", m, x, y
m = red(nn.ReLU())
m.lin2.weight.data *= 300.0 # logits a cientos de unidades de distancia
yield "probabilidad nula", m, x, y
yield "raíz en where", red(RaizPositiva()), x, y
for nombre, m, x, y in casos():
det = DetectorNoFinitos(m)
loss = nn.functional.nll_loss(m(x), y)
loss.backward()
det.quitar()
r = det.informe
print(f"{nombre}: pérdida = {loss.item():.4g}")
print(f" detector: {r['fase']} de '{r['modulo']}'")
print(f" entrada {r['entrada'][:1]}")
print(f" salida {r['salida'][:1]}")
if r["pila"]:
f = r["pila"][-1]
print(f" llamado desde la línea {f.lineno}, en {f.name}()")
m.zero_grad(set_to_none=True)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
with torch.autograd.detect_anomaly():
try:
nn.functional.nll_loss(m(x), y).backward()
print(" detect_anomaly: no dice nada")
except RuntimeError as e:
print(" detect_anomaly:", str(e).split("'")[1])
# coste: hooks en todos los módulos del MLP de 8 capas de 512 frente a detect_anomaly
def coste(dev, modo, n=30):
torch.manual_seed(0)
capas = [nn.Sequential(nn.Linear(512, 512), nn.ReLU()) for _ in range(8)]
m = nn.Sequential(*capas, nn.Linear(512, 10)).to(dev)
opt = torch.optim.SGD(m.parameters(), lr=1e-3)
X = torch.randn(256, 512, device=dev)
Y = torch.randint(0, 10, (256,), device=dev)
det = DetectorNoFinitos(m, pilas=False) if modo == "hooks" else None
def paso():
opt.zero_grad()
nn.functional.cross_entropy(m(X), Y).backward()
opt.step()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
with torch.autograd.set_detect_anomaly(modo == "anomaly"):
for _ in range(5):
paso()
if dev == "cuda":
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(n):
paso()
if dev == "cuda":
torch.cuda.synchronize()
if det:
det.quitar()
return (time.perf_counter() - t0) / n * 1e3
print()
for dev in ["cpu"] + (["cuda"] if torch.cuda.is_available() else []):
t = {modo: coste(dev, modo) for modo in ("nada", "hooks", "anomaly")}
print(f"{dev:4s}: sin nada {t['nada']:6.2f} ms | hooks {t['hooks']:6.2f} ms ({t['hooks'] / t['nada']:.1f}×)"
f" | detect_anomaly {t['anomaly']:6.2f} ms ({t['anomaly'] / t['nada']:.1f}×)")npm run lab and open the connection link.In precision the custom detector wins in the first two cases. With zero variance, it points to ln forward and shows input (finite) and output (16 NaNs, an entire row); detect_anomaly blames LogBackward0, three modules later, because it is the first backward function multiplying by a NaN value. With zero probability, the detector sees in logp forward, and detect_anomaly also points to LogBackward0, but indirectly: with logits hundreds of units apart, probabilities of classes other than the label also vanish, and there the log backward multiplies a zero gradient by . If only the label’s probability were zero, log would give gradient , which is not NaN, and the first NaN would appear in SoftmaxBackward0, as in the previous cell. For the square root inside where, born in backward, both agree. In cost, both multiply step time severalfold: the detector because each bool(torch.isfinite(t).all()) copies a Boolean to CPU and synchronizes with GPU in every module. A production version would accumulate flags on GPU and check them once per step.
Two limitations of module hooks. They see only module boundaries: a torch.log inside a forward is invisible, and the detector blames the containing module (here logp). And full backward hooks do not support modules modifying input in place, such as nn.ReLU(inplace=True): PyTorch raises an error, and inplace must be disabled during debugging.
Mixed-precision anomalies
With autocast and GradScaler in float16, nonfinite values have two origins worth distinguishing. Some are expected: GradScaler multiplies loss by a factor starting at ; if a scaled gradient overflows, scaler.step skips the step and scaler.update halves the factor; every 2000 consecutive steps without overflow doubles it. Seeing Inf gradients in the first steps, or occasionally, is the mechanism working. A detector should look at gradients after scaler.unscale_(opt) and log skipped steps, not raise an error for them. Others are real: forward activations exceeding 65504, such as large attention logits or unnormalized input. The warning sign is a scaling factor falling continuously step after step, or consecutive skipped steps: the forward is overflowing rather than just the scaled gradient. In bfloat16, with the same exponent range as float32, overflow is rare and problems involve precision: 8 mantissa bits, between two and three decimal digits, enough for a variance computed as to be negative and its square root NaN.
Sanity checks
Most training pipeline bugs can be detected in seconds, before real training, with tests whose correct result is known beforehand.
Initial loss
The first check costs one forward pass. If initial logits are small, softmax is nearly uniform and cross-entropy (the cross-entropy between label and prediction) is . For , ; for , . This can be made precise.
Proof
Write and , so . Then
The bound follows from Jensen: the logarithm of a mean of exponentials is at least the mean of exponents, , and because all have mean 0 and is independent of them. For the expansion, , because the linear term vanishes, and . The cubic term has zero expectation by normal symmetry, and subsequent ones are order . This leaves , and the sum of squared deviations from the sample mean of normals has expectation .
∎Practical reading: initial loss measures logit scale. If near , initialization is reasonable. If far above, initial logits are large, due to unnormalized input or a badly scaled final layer, and training will spend its first steps undoing it: Karpathy’s hockey-stick curve, and the reason to initialize the output layer carefully. A particular initialization deviates from expectation by a term of order , because is not exactly 0 in one network, but with that is a few hundredths.
And where should loss fall in the first steps? A model that has not learned anything from input can at least learn each class frequency with the final layer’s bias.
Proof
Grouping examples by class, . The first term is entropy and the second is KL divergence, which is nonnegative and zero only if by Gibbs’ inequality. With , the left side is .
∎This gives two reference lines for reading any classification training curve. Staying at means learning nothing, not even bias: weights are not updating. Staying at means learning only class frequencies: output does not depend on input. With balanced classes the two lines coincide and the second check loses diagnostic power; with imbalanced classes, as in this lesson’s examples, and are distinct plateaus with different causes.
Overfit one batch
The second check is most useful: take a small batch, 8 to 32 examples, and train only on it until loss is practically 0. A network with reasonable capacity memorizes 32 examples with any labels, so if it cannot, there is a bug in model, loss or optimizer: gradients not arriving, parameters not updating, a loss with an artificial floor. Do it in eval mode (without dropout, which prevents complete memorization) and with a generous learning rate.
What it does not detect is equally important. Labels misaligned with inputs can also be memorized, because memorization does not need a meaningful relationship. Passing this check says the model can learn; it does not say the data teaches what you think.
Zero input, example independence and inspecting data
Three more checks cover what the previous one misses.
- Zero input. Train the same number of steps with real input and input replaced by zeros. With zeros, the model can only learn class frequencies and validation loss should stay at . If real input gives the same, the model is not using input.
- Independence between batch examples. Except with batch normalization in
trainmode, output of example should not depend on input of example . Check with a gradient: backpropagate example 0’s output and look at the gradient with respect to all input; it must be exactly zero in the other examples’ rows. This detects the most treacherous shape bug: aviewreinterpreting memory across the batch dimension (view semantics from lesson 12), which changes no shapes and thus gives no error. - Inspect data immediately before the model. Not data on disk: what comes out of the DataLoader after all transformations, on the line before
model(x). Mean and standard deviation of each feature, class histogram of several batches, a few decoded examples (a drawn image, detokenized text) alongside their labels. This detects misaligned labels, duplicated normalization and augmentations destroying the signal.
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
K, D = 10, 20
PRIOR = np.array([0.3, 0.2, 0.12, 0.1, 0.08, 0.06, 0.05, 0.04, 0.03, 0.02])
def datos(seed=0, n_tr=3000, n_va=1000):
"""Los datos de la consulta de síntomas: 10 gaussianas en R^20 con probabilidades desiguales."""
g = np.random.default_rng(seed)
medias = g.normal(0, 1.0, (K, D))
def muestra(n):
y = g.choice(K, n, p=PRIOR)
return (medias[y] + g.normal(0, 1.6, (n, D))).astype(np.float32), y
(xtr, ytr), (xva, yva) = muestra(n_tr), muestra(n_va)
mu, sd = xtr.mean(0), xtr.std(0)
return [torch.tensor(a) for a in ((xtr - mu) / sd, ytr, (xva - mu) / sd, yva)]
Xtr, Ytr, Xva, Yva = datos()
H = -(PRIOR * np.log(PRIOR)).sum()
def mlp(p=0.3):
return nn.Sequential(nn.Linear(D, 256), nn.ReLU(), nn.Dropout(p),
nn.Linear(256, 256), nn.ReLU(), nn.Dropout(p), nn.Linear(256, K))
torch.manual_seed(1)
modelo = mlp()
# 1) pérdida inicial
modelo.eval()
with torch.no_grad():
z = modelo(Xtr)
l0 = F.cross_entropy(z, Ytr).item()
print(f"pérdida inicial {l0:.3f} log K = {math.log(K):.3f} H(Y) = {H:.3f} std de los logits = {z.std():.3f}")
# 2) sobreajustar un lote
def sobreajustar(modelo, x, y, pasos=300, lr=1e-3):
opt = torch.optim.Adam(modelo.parameters(), lr=lr)
modelo.eval() # sin dropout: queremos ver si PUEDE memorizar
for _ in range(pasos):
opt.zero_grad()
loss = F.cross_entropy(modelo(x), y)
loss.backward()
opt.step()
return loss.item()
torch.manual_seed(1)
print(f"sobreajustar 32 ejemplos: pérdida final {sobreajustar(mlp(), Xtr[:32], Ytr[:32]):.2e}")
torch.manual_seed(1)
print(f" ...con etiquetas al azar: {sobreajustar(mlp(), Xtr[:32], torch.randint(0, K, (32,))):.2e}")
# 3) entrada a cero frente a entrada real
def entrenar(x, y, xv, pasos=400, B=60):
torch.manual_seed(1)
m = mlp()
opt = torch.optim.Adam(m.parameters(), lr=1e-3)
g = torch.Generator().manual_seed(0)
for _ in range(pasos):
i = torch.randint(0, len(x), (B,), generator=g)
opt.zero_grad()
F.cross_entropy(m(x[i]), y[i]).backward()
opt.step()
m.eval()
with torch.no_grad():
return F.cross_entropy(m(xv), Yva).item()
print(f"validación con la entrada real {entrenar(Xtr, Ytr, Xva):.3f}, "
f"con la entrada a cero {entrenar(torch.zeros_like(Xtr), Ytr, torch.zeros_like(Xva)):.3f}")
# 4) independencia entre ejemplos del lote
def fuga_entre_ejemplos(modelo, x, i=0):
"""Máximo de |d salida_i / d x_j| para j != i. Debe ser 0 si el modelo trata cada ejemplo por separado."""
modelo.eval() # BatchNorm en modo train mezcla ejemplos legítimamente
x = x.clone().requires_grad_(True)
modelo(x)[i].sum().backward()
g = x.grad.abs().flatten(1).sum(1)
g[i] = 0
return g.max().item()
class Grupos(nn.Module):
"""Procesa las 20 características como 2 grupos de 10 con una capa compartida."""
def __init__(self, bug=False):
super().__init__()
self.bug, self.grupo, self.cabeza = bug, nn.Linear(10, 32), nn.Linear(64, K)
def forward(self, x):
B = x.shape[0]
g = x.view(2, B, 10).transpose(0, 1) if self.bug else x.view(B, 2, 10)
return self.cabeza(torch.relu(self.grupo(g)).reshape(B, 64))
torch.manual_seed(0)
print(f"fuga entre ejemplos: MLP {fuga_entre_ejemplos(mlp(), Xtr[:8]):.1e}, "
f"Grupos {fuga_entre_ejemplos(Grupos(), Xtr[:8]):.1e}, Grupos con el bug {fuga_entre_ejemplos(Grupos(bug=True), Xtr[:8]):.1e}")npm run lab and open the connection link.Numbers confirm theory: initial loss versus , with logit standard deviation ; 32 examples memorized to loss below , also with random labels; with zero input validation stays at , practically , versus with real input. And the grouped model with x.view(2, B, 10) has exactly the same shapes as the correct one, but example 0’s output depends on the others: view does not permute data, it reinterprets memory, and the first half of the 8-example buffer contains features of examples 0 to 3, not the first group of each example.
Common silent bugs
Each of these bugs produces training that works. Knowing its quantitative signature helps recognize it on a curve.
Broadcasting in loss. With pred of shape and y of shape , ((pred - y) ** 2).mean() calculates a matrix by the broadcasting rules, without error. What is minimized then is
because averaging over cancels the cross term. Loss does not depend on which label each example has: it pushes all predictions toward batch mean , and its minimum is variance of . The model learns to predict a constant and loss falls to a reasonable value. The classification equivalent is indexing with logp[:, y] instead of logp[torch.arange(B), y]: each example trains against all batch labels, and loss stalls at .
Softmax applied twice. F.cross_entropy expects logits and applies log_softmax internally. If given probabilities , it calculates , and since is in the simplex this quantity has a floor: its derivative with respect to is and with respect to any other is positive, so moving mass from any class to always reduces it, and the minimum is at :
For , : loss cannot fall below that even if the model is always correct, and because the outer softmax barely changes when moves, gradients are tiny.
A view mixing examples. The previous cell’s example. Its shapes are correct, so only the independence check or a test against a reference implementation detects it.
Forgotten eval. Validating without model.eval() leaves dropout active and batch normalization using and updating validation-batch statistics. Validation becomes noisy, worse and nondeterministic: evaluating twice in a row gives different numbers. Forgetting model.train() on return is the symmetric bug, training without dropout.
Misaligned labels. Shuffling and separately, sorting files and labels by different criteria or an off-by-one shift during reading. The model can only memorize: training falls slowly below and validation does not fall below .
The following interactive gathers eight real curves: a PyTorch MLP trained on a synthetic 10-class problem with unequal probabilities, seven times with a different planted bug and once without one but with a curve that looks buggy. For each, choose the most likely cause and the fastest confirming test.
Validation below training is the most instructive case, because it is not a bug: the two losses are measured under different conditions (with dropout and averaged over epoch steps, versus eval mode at the end). The first step of any diagnosis is comparing comparable quantities.
Lab: ten planted bugs
The second lab makes the clinic systematic. The next cell is a minimal “repository” with data, model, loss, loop and evaluation, where any of ten silent bugs can be enabled. Below is a battery of nine checks, each a few lines and seconds of execution. The final table says which checks fail for each bug: the aim is for each bug to have at least one and for the healthy repository to pass them all.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
# Un «repositorio» mínimo: datos, modelo, pérdida, bucle y evaluación. Cada bug se activa por su nombre.
# Usa datos(), K y D de la celda anterior.
BUGS = {
"etiquetas_desalineadas": "y desplazada una posición respecto a x",
"softmax_doble": "softmax antes de cross_entropy",
"eval_olvidado": "evaluate() sin model.eval()",
"broadcasting_perdida": "-logp[:, y].mean() en vez de -logp[arange(B), y].mean()",
"scheduler_por_lote": "StepLR pensado por épocas, llamado en cada lote",
"aumentacion_en_validacion": "el ruido de aumentación también en validación",
"sin_zero_grad": "falta opt.zero_grad()",
"sin_barajar": "datos ordenados por clase y sin barajar",
"sin_normalizar": "entrada sin estandarizar",
"view_mezcla_lote": "x.view(2, B, 10) en vez de x.view(B, 2, 10)",
}
class Modelo(nn.Module):
def __init__(self, mezcla=False):
super().__init__()
self.mezcla = mezcla
self.grupo = nn.Linear(10, 64)
self.red = nn.Sequential(nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, 128), nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, K))
def forward(self, x):
B = x.shape[0]
g = x.view(2, B, 10).transpose(0, 1) if self.mezcla else x.view(B, 2, 10)
return self.red(self.grupo(g).reshape(B, 128))
class Repo:
def __init__(self, bugs=(), seed=0, B=60):
self.b, self.B = set(bugs), B
X, Y, Xv, Yv = datos() # ya estandarizados
if "sin_normalizar" in self.b:
X, Xv = X * 25 + 40, Xv * 25 + 40
if "etiquetas_desalineadas" in self.b:
Y = torch.roll(Y, 1)
if "sin_barajar" in self.b:
o = torch.argsort(Y, stable=True)
X, Y = X[o], Y[o]
self.X, self.Y, self.Xv, self.Yv = X, Y, Xv, Yv
torch.manual_seed(seed)
self.model = Modelo(mezcla="view_mezcla_lote" in self.b)
self.opt = torch.optim.Adam(self.model.parameters(), lr=1e-3)
self.sched = torch.optim.lr_scheduler.StepLR(self.opt, step_size=4, gamma=0.5)
self.g = torch.Generator().manual_seed(seed)
def lotes(self): # el DataLoader de una época
n = len(self.X)
idx = torch.arange(n) if "sin_barajar" in self.b else torch.randperm(n, generator=self.g)
for s in range(0, n - self.B + 1, self.B):
i = idx[s:s + self.B]
yield self.X[i] + 0.05 * torch.randn(self.B, D, generator=self.g), self.Y[i]
def perdida(self, out, y):
if "softmax_doble" in self.b:
out = F.softmax(out, dim=-1)
if "broadcasting_perdida" in self.b:
return -F.log_softmax(out, dim=-1)[:, y].mean()
return F.cross_entropy(out, y)
def paso(self, x, y):
self.model.train()
if "sin_zero_grad" not in self.b:
self.opt.zero_grad()
loss = self.perdida(self.model(x), y)
loss.backward()
self.opt.step()
if "scheduler_por_lote" in self.b:
self.sched.step()
return loss.item()
def fin_de_epoca(self):
if "scheduler_por_lote" not in self.b:
self.sched.step()
def evaluar(self):
if "eval_olvidado" not in self.b:
self.model.eval()
xv = self.Xv
if "aumentacion_en_validacion" in self.b:
xv = xv + 0.05 * torch.randn(xv.shape)
with torch.no_grad():
l = self.perdida(self.model(xv), self.Yv).item()
self.model.train()
return l
# ---------- la batería de comprobaciones: cada una recibe un Repo recién creado ----------
def perdida_inicial(r):
x, y = next(r.lotes())
r.model.eval()
with torch.no_grad():
l = r.perdida(r.model(x), y).item()
return abs(l - math.log(K)) < 0.25
def sobreajustar_lote(r):
x, y = next(r.lotes())
for _ in range(300):
r.paso(x[:32], y[:32])
r.model.eval()
with torch.no_grad():
return r.perdida(r.model(x[:32]), y[:32]).item() < 0.05
def entrada_a_cero(r, pasos=150):
def val(r, cero):
for k, (x, y) in enumerate(r.lotes()):
if k == pasos:
break
r.paso(torch.zeros_like(x) if cero else x, y)
if cero:
r.Xv = torch.zeros_like(r.Xv)
return r.evaluar()
return val(r, False) < val(Repo(r.b), True) - 0.3
def independencia_lote(r):
x, _ = next(r.lotes())
r.model.eval()
x = x[:8].clone().requires_grad_(True)
r.model(x)[0].sum().backward()
return x.grad[1:].abs().max().item() == 0.0
def mirar_lote(r):
x, y = next(r.lotes())
# centroides de clase estimados en VALIDACIÓN: ¿cuadran las etiquetas del lote de entrenamiento?
C = torch.stack([r.Xv[r.Yv == k].mean(0) for k in range(K)])
acierto = (torch.cdist(x, C).argmin(1) == y).float().mean().item()
return len(y.unique()) >= 5 and abs(x.mean().item()) < 0.5 and 0.5 < x.std().item() < 2 and acierto > 0.4
def evaluacion_determinista(r):
return r.evaluar() == r.evaluar()
def lr_constante_en_la_epoca(r):
lrs = set()
for x, y in r.lotes():
r.paso(x, y)
lrs.add(r.opt.param_groups[0]["lr"])
return len(lrs) == 1
def gradiente_se_vacia(r):
x, y = next(r.lotes())
for g in r.opt.param_groups:
g["lr"] = 0.0 # pasos que no mueven nada
torch.manual_seed(0) # la misma máscara de dropout en los dos pasos
r.paso(x, y)
g1 = r.model.red[-1].weight.grad.clone()
torch.manual_seed(0)
r.paso(x, y)
return torch.allclose(r.model.red[-1].weight.grad, g1)
def perdida_de_prediccion_perfecta(r):
_, y = next(r.lotes())
return r.perdida(20.0 * F.one_hot(y, K).float(), y).item() < 1e-3
CHECKS = [perdida_inicial, sobreajustar_lote, entrada_a_cero, independencia_lote, mirar_lote,
evaluacion_determinista, lr_constante_en_la_epoca, gradiente_se_vacia, perdida_de_prediccion_perfecta]
print(" " * 26 + " ".join(f"{i + 1:>2d}" for i in range(len(CHECKS))))
for bug in ["(ninguno)"] + list(BUGS):
bugs = () if bug == "(ninguno)" else (bug,)
fila = ["·" if c(Repo(bugs)) else "✗" for c in CHECKS]
print(f"{bug:26s}" + " ".join(f"{f:>2s}" for f in fila))
print()
for i, c in enumerate(CHECKS):
print(f"{i + 1:2d} = {c.__name__}")npm run lab and open the connection link.The table has several lessons. No check detects all bugs, and several detect only one: evaluacion_determinista alone sees forgotten eval and validation augmentation, and gradiente_se_vacia alone sees missing zero_grad. With Adam, that bug even passes single-batch overfitting because Adam normalizes step size and accumulated gradients keep pointing approximately in the right direction. Misaligned labels also pass overfitting, as predicted, and fail zero input and batch inspection. The lab exercise is the converse: for each bug, write the smallest test detecting it, as a test_* function you can leave in the project’s battery with tools from the numerical testing lesson.
Instrumentation: see symptoms before loss
Loss is one number summarizing millions of parameters. By the time it reflects a problem, the problem has been there for a while. Instrumentation records what happens inside, layer by layer.
Each reading has a precise interpretation.
Update ratio measures what fraction of weights each step rewrites. For SGD without momentum, and : the learning rate in units of the weights themselves, the scale that matters. CS231n notes propose as reference: far below, weights barely move in thousands of steps; far above, every ten or hundred steps they are entirely rewritten and training becomes unstable. This is not a theorem, but a useful dashboard scale. With Adam, the ratio depends mostly on lr because the optimizer normalizes each coordinate: on the first step, and , so is the gradient sign apart from denominator , and each weight with non-negligible gradient moves . For a matrix with He initialization, and , so : with , sixteen times lr.
Per-layer gradient norms reveal vanishing and explosion. In a network without normalization or residual connections, activation and gradient scales are multiplied by a similar factor at each layer. If the weights of a ReLU layer with inputs have variance and preactivation is symmetric with mean 0, and the next preactivation’s variance is . Standard deviation is multiplied by per layer: He initialization chooses so that factor is 1. With and , the factor is and five layers reduce the signal by a factor of : gradients vanish. With , the factor is 4 and output is a thousand times larger than input.
Dead units are ReLUs whose preactivation is negative for all data. Their gradient is 0, so incoming weights stop receiving signal and do not recover: the layer has lost that capacity forever. Too high an lr produces them en masse, because a large step can send a unit’s bias far below zero; a negative initial bias also does. They are the subject of dead ReLU neurons in the networks module.
With lr 0.2, the ratio exceeds in the first few dozen steps and dead ReLU fraction grows while loss is still falling: the dashboard warns at step 0 and loss keeps improving until step 170; it then shoots up and ends near , with almost all deep-layer ReLUs dead and final accuracy near random guessing, one third. With lr 0.01 all readings are in place and final accuracy is 99%. With tiny initialization, the activation profile at step 0 falls from each hidden layer to the next by a factor between 0.03 and 0.05, the predicted above, and loss does not move from .
The next cell performs the same experiment in PyTorch with a reusable instrumentation class. Three design decisions make it cheap: measure every cada steps rather than all, save activations with hooks instead of touching the model, and gather all readings from a step into one tensor copied to CPU once, because every .item() is a GPU synchronization.
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class Instrumentos:
"""Normas de gradiente, ratio ‖ΔW‖/‖W‖ y estadísticas de activación por capa, cada `cada` pasos."""
def __init__(self, modelo, cada=1):
self.cada, self.t, self.log = cada, 0, []
self.pesos = [(n, p) for n, p in modelo.named_parameters() if p.ndim >= 2]
self.act = {}
self._h = [m.register_forward_hook(self._hook(n)) for n, m in modelo.named_modules() if isinstance(m, nn.ReLU)]
def _hook(self, nombre):
def hook(mod, args, out):
if self.t % self.cada == 0:
with torch.no_grad(): # fracción de unidades a cero en TODO el lote, y desviación típica
self.act[nombre] = ((out > 0).sum(0) == 0).float().mean(), out.std()
return hook
def antes_del_paso(self): # llamar tras backward() y antes de opt.step()
self._medir = self.t % self.cada == 0
if self._medir:
self._prev = [p.detach().clone() for _, p in self.pesos]
self._g = torch.stack([p.grad.norm() for _, p in self.pesos])
def despues_del_paso(self, loss):
if self._medir:
with torch.no_grad():
d = torch.stack([(p - q).norm() / q.norm() for (_, p), q in zip(self.pesos, self._prev)])
muertas = torch.stack([v[0] for v in self.act.values()])
std = torch.stack([v[1] for v in self.act.values()])
# una sola copia a la CPU por paso medido: es lo único que sincroniza con la GPU
fila = torch.cat([loss.detach().reshape(1), self._g, d, muertas, std]).cpu().numpy()
self.log.append((self.t, fila))
self.t += 1
def quitar(self):
for h in self._h:
h.remove()
def espiral(n=100, K=3, seed=0):
g = np.random.default_rng(seed)
X, y = [], []
for k in range(K):
r = np.linspace(0, 1, n)
t = k * 4 + np.linspace(0, 4, n) + g.normal(0, 0.2, n)
X.append(np.c_[r * np.sin(t), r * np.cos(t)])
y += [k] * n
return torch.tensor(np.vstack(X), dtype=torch.float32), torch.tensor(y)
def experimento(lr, pasos=400, B=64, seed=2):
torch.manual_seed(seed)
capas = []
for a, b in zip([2, 32, 32, 32, 32], [32] * 5):
capas += [nn.Linear(a, b), nn.ReLU()]
modelo = nn.Sequential(*capas, nn.Linear(32, 3))
for m in modelo:
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
nn.init.zeros_(m.bias)
opt = torch.optim.SGD(modelo.parameters(), lr=lr, momentum=0.9)
X, y = espiral()
ins = Instrumentos(modelo)
g = torch.Generator().manual_seed(seed)
for _ in range(pasos):
i = torch.randint(0, len(X), (B,), generator=g)
opt.zero_grad()
loss = F.cross_entropy(modelo(X[i]), y[i])
loss.backward()
ins.antes_del_paso()
opt.step()
ins.despues_del_paso(loss)
ins.quitar()
with torch.no_grad():
acc = (modelo(X).argmax(1) == y).float().mean().item()
return np.array([f for _, f in ins.log]), acc
L = 6 # capas con pesos
for lr in (0.01, 0.2):
log, acc = experimento(lr)
perdida, gnorm, ratio, muertas = log[:, 0], log[:, 1:1 + L], log[:, 1 + L:1 + 2 * L], log[:, 1 + 2 * L:1 + 2 * L + 5]
ema = np.copy(perdida)
for t in range(1, len(ema)):
ema[t] = 0.9 * ema[t - 1] + 0.1 * perdida[t]
malos = np.flatnonzero(~np.isfinite(perdida))
nan_en = f", pérdida NaN desde el paso {malos[0]}" if len(malos) else ""
print(f"lr = {lr}: exactitud final {acc:.2f}, mejor pérdida suavizada en el paso {np.nanargmin(ema)}{nan_en}")
for t in (0, 10, 50, 100, 200, 399):
print(f" paso {t:3d} pérdida {perdida[t]:.3f} ratio máx {ratio[t].max():.1e} "
f"‖∇W1‖/‖∇W6‖ {gnorm[t, 0] / gnorm[t, -1]:.1e} muertas (peor capa) {muertas[t].max():.0%}")
# Adam en su primer paso mueve cada peso exactamente lr (m/√v = signo del gradiente)
torch.manual_seed(0)
capa = nn.Linear(512, 512)
nn.init.kaiming_normal_(capa.weight, nonlinearity="relu")
opt = torch.optim.Adam(capa.parameters(), lr=1e-3)
w0 = capa.weight.detach().clone()
capa(torch.randn(64, 512)).pow(2).mean().backward()
opt.step()
print(f"\nAdam, primer paso: ratio {((capa.weight - w0).norm() / w0.norm()).item():.4f} "
f"predicción lr·√(d/2) = {1e-3 * math.sqrt(512 / 2):.4f}")npm run lab and open the connection link.In PyTorch, with another seed and float32, lr 0.2 ends worse than in the browser: loss becomes NaN around step 90. The ratio, in contrast, exceeded from step 0, and best smoothed loss was reached at step 29. That is instrumentation’s value: the warning arrives dozens of steps before NaN, and in real training, hours before. The last line confirms the first-step Adam calculation to four decimal places.
Bisection: toward a minimal reproducible case
When the preceding checks are insufficient, the most general method remains: reduce the problem. A failure appearing three hours in, with the full model, all data and forty configuration options, is almost impossible to debug. The same failure with one batch, two layers and one option can be solved in minutes.
Axes of reduction:
- Steps. Save a checkpoint every steps and, on the first nonfinite value, the batch and random-generator state. Rerunning from the last checkpoint reproduces failure in steps instead of hours if training is deterministic: lesson 20’s seeds are a bisection requirement.
- Data. If failure depends on a batch, train only with that batch; if on an example, find it by halves.
- Model. Remove blocks, reduce width, replace a layer with identity.
- Configuration and code. A working configuration and a broken one differ by a set of changes; yesterday’s version and today’s by a list of commits, which
git bisectsearches automatically (you will see git bisect in lesson 23).
When failure is monotone along an ordered sequence (layers in forward order, steps, commits), search is binary and its cost optimal.
Proof
For the upper bound, the invariant is that the first bad item lies in , initially . Evaluating midpoint leaves if is bad (by monotonicity, the first is not after ) and otherwise. Each evaluation reduces an interval of candidates to at most , so after evaluations at most remain, which is 1 once . The lower bound is the final guided exercise.
∎Bisection needs monotonicity. When failure depends on a combination of elements, such as two configuration options that only together make training diverge, splitting in half may leave both halves without failure. Zeller and Hildebrandt’s (2002) ddmin algorithm generalizes bisection to this case: test chunks and their complements, and if neither preserves failure, split more finely. Its result is 1-minimal: removing any further element makes failure disappear. When one element alone is the cause, it behaves like binary search.
The final method in the box is layer-by-layer comparison with a reference. If you have an implementation known correct (a paper’s original, a library’s, a slow obvious one you wrote), load the same weights into both, pass the same input and compare intermediate activations in order with tolerance, as in reference implementation testing. The first divergent layer is the culprit. Comparing only output is insufficient, as the cell shows.
import math
import numpy as np
# 1) Bisección sobre una secuencia ordenada (capas, pasos, commits): el primer «malo»
def primer_malo(n, es_malo):
"""Menor i en [0, n) con es_malo(i), sabiendo que es_malo es monótona y es_malo(n - 1) es cierto."""
lo, hi, pruebas = 0, n - 1, 0
while lo < hi:
mid = (lo + hi) // 2
pruebas += 1
if es_malo(mid):
hi = mid
else:
lo = mid + 1
return lo, pruebas
n = 25
peor = max(primer_malo(n, lambda i, o=o: i >= o)[1] for o in range(n))
print(f"{n} posiciones: como mucho {peor} pruebas; ceil(log2 {n}) = {math.ceil(math.log2(n))}")
# 2) ddmin (Zeller y Hildebrandt, 2002) sobre la diferencia entre una configuración que funciona y otra que no
def ddmin(cambios, falla):
"""Subconjunto 1-mínimo de `cambios` con el que falla(subconjunto) sigue siendo cierto."""
pruebas = 0
def f(c):
nonlocal pruebas
pruebas += 1
return falla(c)
c, k = list(cambios), 2
while len(c) >= 2:
trozos = [c[i * len(c) // k:(i + 1) * len(c) // k] for i in range(k)]
for t in trozos: # ¿falla con un solo trozo?
if f(t):
c, k = t, 2
break
else:
for t in trozos: # ¿falla quitando un trozo?
resto = [x for x in c if x not in t]
if f(resto):
c, k = resto, max(k - 1, 2)
break
else:
if k >= len(c):
break
k = min(2 * k, len(c)) # partir más fino
return c, pruebas
buena = {"lr": 3e-4, "warmup": 2000, "amp": False, "batch": 64, "clip": 1.0, "wd": 0.1,
"eps": 1e-8, "init": "normal", "ln_eps": 1e-5, "seq": 512, "compile": False, "seed": 0}
mala = dict(buena, lr=1e-3, warmup=200, amp=True, batch=128, clip=None, wd=0.05, eps=1e-6,
init="xavier", seq=1024, compile=True, seed=1)
diff = [k for k in buena if buena[k] != mala[k]]
def falla(subconjunto):
"""Ejecución simulada: aplica a la configuración buena solo esos cambios. Diverge si hay AMP y no hay recorte."""
cfg = dict(buena, **{k: mala[k] for k in subconjunto})
return cfg["amp"] and cfg["clip"] is None
causa, pruebas = ddmin(diff, falla)
print(f"\n{len(diff)} cambios entre las dos configuraciones: {diff}")
print(f"ddmin: causa mínima {causa} en {pruebas} ejecuciones (probar todos los subconjuntos: {2 ** len(diff)})")
# 3) Comparar capa a capa con una implementación de referencia
rng = np.random.default_rng(0)
x = rng.normal(size=(4, 16))
pesos = [rng.normal(size=(16, 16)) / 4 for _ in range(4)]
def layer_norm(h, sesgada=True, eps=1e-5):
var = h.var(-1, keepdims=True, ddof=0 if sesgada else 1)
return (h - h.mean(-1, keepdims=True)) / np.sqrt(var + eps)
def capas(x, version):
"""Devuelve todas las activaciones intermedias, en orden."""
acts, h = [], x
for i, W in enumerate(pesos):
h = h @ W
acts.append(("lineal", i, h))
h = layer_norm(h, sesgada=(version == "referencia" or i != 2)) # el port usa ddof=1 en la capa 2
acts.append(("norm", i, h))
h = np.maximum(h, 0)
acts.append(("relu", i, h))
return acts
ref, port = capas(x, "referencia"), capas(x, "port")
print("\nprimera divergencia entre la referencia y el port:")
for (nombre, i, a), (_, _, b) in zip(ref, port):
err = np.abs(a - b).max()
if not np.allclose(a, b, rtol=1e-6, atol=1e-9):
print(f" {nombre} {i}: error máximo {err:.2e} <- aquí")
break
print(f" {nombre} {i}: error máximo {err:.2e}")
print(f" y a la salida: {np.abs(ref[-1][2] - port[-1][2]).max():.2e}")Two results deserve comment. ddmin isolates the two changes jointly causing failure in 16 runs versus 2048 combinations of 11 changes: no simple bisection could have done it because failure requires both at once. And the port with unbiased variance (ddof=1) in one LayerNorm diverges in that layer (all outputs multiplied by , 3% less, with maximum error 0.08), but at output the difference is : the next normalization is scale-invariant and erases almost all error. A test comparing output alone with rtol=1e-5 would accept the port, and the error would reappear as soon as someone removed the next normalization.
The debugging notebook
The final tool is not code. A difficult bug is solved by a sequence of experiments, and without a record that sequence gets repeated, forgotten or misinterpreted. The minimal format is a table with one row per experiment, writing its first three columns before execution:
| hypothesis | test | prediction | result | next step |
|---|---|---|---|---|
| batch at step 41 200 brings a NaN | torch.isfinite(x).all() on saved batch | false | true: batch is clean | search model |
| something overflows in float16 | repeat step from checkpoint in float32 | finite | finite | find what overflows |
| it is attention | hook detector on the float16 step | b7.atn | first Inf in output of b7.atn | inspect logits |
| attention logits above 65504 | maximum before scaling | more than | scale before product |
Writing the prediction before the result separates an experiment from exploration: if prediction fails, the hypothesis falls, and that is information. Three rules complete it: one change at a time, because two simultaneous changes do not say which worked; every bug found becomes a test that would have detected it, to prevent recurrence; and the cheapest hypothesis to check goes first, not the most likely, if the cost difference is large. Lesson 23’s lab notebook, the lab notebook, applies this habit at project scale.
Common mistakes
Exercises
F.cross_entropy, which applies log_softmax again. What is the lowest loss it can reach on one example, even if it predicts the correct class with probability 1?y = torch.where(x > 0, torch.sqrt(x), 0.0) gives a correct forward, but x.grad is NaN where . Which changes truly fix it? There may be several.More than one answer may be correct.
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) before opt.step() with Adam. What happens?Step 1 of 4. How do you represent the strategy?
sanity_check_overfit(model, batch, steps=300, tol=1e-2, lr=1e-2). It receives a classifier and a batch (x, y), and trains a copy of the model (using copy.deepcopy to leave the original untouched) with Adam and F.cross_entropy for steps steps on that batch, in eval mode so dropout does not prevent memorization. If final loss is below tol, return that loss as a float. Otherwise raise AssertionError with a message including the word “pérdida”, the final loss reached, step count and initial loss. Also raise AssertionError if the model has no trainable parameters. The original model must remain intact, weights and mode.import torch
import torch.nn.functional as F
def sanity_check_overfit(model, batch, steps=300, tol=1e-2, lr=1e-2):
"""Comprueba que una copia del modelo memoriza el lote (x, y). Devuelve la pérdida final o lanza AssertionError."""
passfirst_nonfinite_layer(model, inputs), which executes model(inputs) without gradients with a forward hook on each submodule (all those in named_modules() except the root) and returns the name, as it appears in named_modules(), of the first module, in order of forward completion, whose output contains any NaN or Inf. If all is finite, return None. Hooks must always be removed on completion, including if forward raises an exception.import torch
def first_nonfinite_layer(model, inputs):
"""Nombre (como en named_modules) de la primera capa cuyo forward produce un valor no finito, o None."""
return NoneSummary
breakpoint(),python -m pdb -c continue,%debugandpdb.post_mortemopen the debugger on real state at the point of failure. pdb conditional breakpoints are expensive in hot loops: put the condition in code.- Nonfinite values arise from overflow, underflow followed by a logarithm or indeterminate forms, and propagate throughout a step: a NaN in forward makes all upstream gradients NaN, and one optimizer step spreads it to all weights. Capture the first failing step.
np.errstateconverts the first floating-point event to an exception;detect_anomalyonly looks at backward, only NaN, and names the first function making NaN, which is not always the origin; a hook detector sees forward and backward module by module.- Initial loss should be near ; remaining at means learning nothing, and remaining at means learning class frequencies only. Overfitting a batch tests whether the model can learn, not whether data is correct.
- Per-layer gradient norms, update-to-weight ratio (reference ) and dead ReLU fraction warn of excessive lr or poor initialization before loss does.
- Bisection finds the first bad element of a monotone sequence in tests, which is optimal; ddmin extends the idea to failures depending on combinations; layer-by-layer comparison with a reference finds the first divergence hidden by the output.