nn.Module, optimizers and the training loop
The anatomy of PyTorch training code: nn.Module as a tree of parameters, buffers and submodules with its state_dict; torch.optim parameter groups, state and schedulers; and the canonical training and evaluation loop.
After this lesson you can
- Write custom modules that register parameters, buffers and submodules correctly and traverse them with named_parameters and named_modules.
- Explain what a state_dict contains and load it while handling missing or unexpected keys.
- Configure optimizers with parameter groups and learning-rate schedulers.
- Write the canonical training and evaluation loop with train(), eval(), validation and metrics.
- Use forward and backward hooks to inspect activations and gradients without changing the model.
Before you start
Motivation: one skeleton for all models
This loop trains almost any PyTorch network:
model = Net().to(device)
opt = torch.optim.AdamW(param_groups(model, weight_decay=0.1), lr=3e-4)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: warmup_cosine(s, W, T))
for epoch in range(epochs):
model.train()
for x, y in train_loader:
x, y = x.to(device), y.to(device)
loss = loss_fn(model(x), y)
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
opt.step()
sched.step()
val = evaluate(model, val_loader) # model.eval() + torch.inference_mode()
The neural-network block’s MLP, the GPT you will write from scratch and AlphaZero’s value and policy network all train with these same fifteen lines. Net, data and loss change; the skeleton does not. It is worth understanding the machinery beneath each line, especially failures with an unpleasant property: they raise no exception. The code runs, loss falls and the model performs worse than it should without warning. Four real examples:
- You store network blocks in a Python list. The optimizer cannot see them and only the head trains, but loss still falls because the head learns something on its own.
- You validate without
model.eval(). Metrics are noisy and, with batch normalization, validation itself modifies the model you will save. - The learning-rate schedule was designed per step but called per epoch. With 1000 steps per epoch, a 2000-step warmup takes two million.
- You replace the model head after creating the optimizer. The new head receives gradients but is never updated.
This lesson takes the skeleton apart: nn.Module as a tree of parameters, buffers and submodules; state_dict as its snapshot; the torch.optim API with parameter groups, state and schedulers; the canonical training and evaluation loop; and hooks to inspect a model without changing its code. Optimization algorithms themselves, from stochastic momentum to AdamW, are covered in the optimization module; here we master their shared machinery.
Inside nn.Module
How these registries are filled explains the opening failures. No register method needs calling: writing self.fc = nn.Linear(16, 16) inside __init__ suffices. This works because nn.Module overrides __setattr__, the special method to which Python translates every attribute assignment under the Python data model. Simplified, it does this:
def __setattr__(self, name, value):
if isinstance(value, nn.Parameter):
self._parameters[name] = value # parámetro
elif isinstance(value, nn.Module):
self._modules[name] = value # submódulo
elif name in self._buffers:
self._buffers[name] = value # reasignar un buffer existente lo actualiza
else:
object.__setattr__(self, name, value) # cualquier otra cosa: atributo normal
Conversely, nn.Module.__getattr__ looks up names in the three registries. Python calls __getattr__ only when normal lookup in the object’s __dict__ fails, and parameters are not in __dict__: they are in _parameters. Thus self.fc returns the submodule even though it was never stored as an ordinary attribute.
Almost all nn.Module behavior follows from these ten lines:
- Registration depends on the value’s type at assignment. An
nn.Parameterornn.Moduleis registered; an ordinary tensor, list, dictionary or tuple of modules is stored as a Python attribute and invisible to everything else. Thusself.layers = [nn.Linear(64, 64)]hides the layer: the assigned object is alist, not aModule. This also explainscannot assign module before Module.__init__() callif you forgetsuper().__init__(): registries do not yet exist. - Order is assignment order. Registries are ordered dictionaries, and traversals visit them in that order.
- Buffers are declared explicitly with
self.register_buffer("mask", tensor, persistent=True). Once registered,self.mask = otro_tensorupdates the buffer instead of creating an attribute, asBatchNormupdates its statistics.
Traversals build on the tree. named_modules() visits in preorder: the module itself first, named "", then each submodule with its path. named_parameters() and named_buffers() traverse those modules and each module’s own tensors, so a module’s tensors precede its children’s. children() gives only direct children, and parameters() is named_parameters() without names. All these traversals deduplicate by identity: the same Parameter, buffer or submodule reachable by two paths appears once, at the first. This is exactly what weight tying between a language model’s embedding table and output layer needs: one tensor, two uses, one accumulated gradient and one update.
Operations affecting the whole model traverse this tree:
model.to(device)traverses the tree and converts or moves every parameter and buffer, persistent or not. Unliketensor.to(device), which returns a new tensor,module.tomodifies the module in place and returns it for convenience. Tensors stored as ordinary attributes do not move: a leading source of device placement errors in custom code.model.train(mode=True)setstraining = modeon all modules in the tree, andmodel.eval()ismodel.train(False). It does nothing else: only modules whoseforwardchecksself.training, such asDropoutandBatchNorm, change behavior. In particulareval()has nothing to do with autograd: it still records the graph unless insidetorch.no_grad()ortorch.inference_mode(), the tools for cutting the graph.model.apply(fn)callsfnon every submodule in postorder, mainly to initialize weights.
Finally, model(x) differs from model.forward(x). nn.Module.__call__ executes registered hooks before and after forward, while calling forward directly skips them. We return to this at the end.
__init__; the table shows every module and tensor in the tree, with a column per mechanism traversing it: parameters(), the optimizer created from them, state_dict() and .to(). Changed code lines are highlighted. Start by storing blocks in a Python list. Then register the same block twice, change how scale is registered and finally replace the head after creating the optimizer. Observe which readings change and which do not.What you should have seen:
- A Python list hides an entire tree branch. With
blocksin a list, the blocks’ 608 parameters disappear from all four columns at once..to("cuda")leaves them on CPU, so GPU forward fails withExpected all tensors to be on the same device. On CPU everything runs without warning. - Sharing a block duplicates only keys. With
nn.ModuleList([b, b]),parameters()falls from 836 to 532 because it countsbonce, and the optimizer updates it once per step with summed gradients from both uses. Thestate_dictkeeps all 18 keys:blocks.0.fc.weightandblocks.1.fc.weightpoint to the same storage. - Parameters, buffers and ordinary tensors differ by who sees them. A parameter appears in all columns. A persistent buffer appears in
state_dictand travels with.to(), but the optimizer does not touch it. A nonpersistent one only travels with.to(), and an ordinary tensor appears in none. - The optimizer stores references, not names. After replacing the head,
parameters()andstate_dictsee the new one, but the optimizer still points to the old tensors. The optimizer section explains why.
Containers: Sequential, ModuleList and ModuleDict
To store a variable number of submodules, PyTorch provides three containers that are themselves modules and register their contents under names "0", "1", … or their keys:
| container | what it is | forward | used for |
|---|---|---|---|
nn.Sequential(*mods) | ordered list | chains modules: one’s output is the next one’s input | unbranched stacks; seq[1:] returns another Sequential |
nn.ModuleList(mods) | list | none: you write the loop in the parent’s forward | transformer layers, blocks with residual connections |
nn.ModuleDict(dict) | dictionary with str keys | none | task-specific heads, branches selected by name |
For individual tensors there are nn.ParameterList and nn.ParameterDict; to register a module with a computed name, use self.add_module(nombre, m) or equivalently setattr(self, nombre, m), which goes through __setattr__.
The practical rule is short: if an attribute contains modules or parameters, its type must be a PyTorch container. A Python list, tuple or dictionary always fails silently in the same way: gradients are computed because autograd works with any requires_grad=True tensor involved in the loss, but the optimizer never applies them. If hidden layers are in a list, loss still falls because the head fits random features, producing an unintended linear model over fixed random features. Detect this quickly by comparing sum(p.numel() for p in model.parameters()) with the expected count.
state_dict: a snapshot of the model
Three properties of a module’s state_dict to remember:
- Keys are tree paths and order follows traversals: each module’s own tensors before its children’s. Shared parameters appear once per path, without deduplication. Nonpersistent buffers do not appear.
- Values are not copies. They are graph-detached tensors (
requires_grad=False) sharing storage with parameters. If you domejor = model.state_dict()and keep training,mejorchanges with eachopt.step(). An in-memory snapshot requires{k: v.clone() for k, v in model.state_dict().items()}orcopy.deepcopy. - It contains no code. Only names and tensors: to use it, first build a model with the same structure. Saving with
torch.saveand reading withtorch.load(..., weights_only=True)is also the safe way to serialize models.
model.load_state_dict(sd, strict=True) compares sd keys with the model’s. With default strict=True, missing or extra keys cause a RuntimeError listing them. With strict=False there is no error and the function returns a named tuple, _IncompatibleKeys(missing_keys, unexpected_keys). In either case a key with the wrong shape is always an error. Loading copies values into existing tensors with param.copy_(valor), without replacing them, so anything holding parameter references, including the optimizer, remains valid afterward. assign=True does the opposite: replaces tensors with dictionary tensors, useful to materialize a model created on meta without allocating memory twice, but requiring the optimizer to be created afterward.
Two legitimate uses of partial loading are reusing part of a model and renaming keys. The pattern is always the same: transform the dictionary with comprehensions, load and check.
sd = torch.load("preentrenado.pt", map_location="cpu", weights_only=True)
sd = {k.removeprefix("_orig_mod."): v for k, v in sd.items()} # renombrar
sd = {k: v for k, v in sd.items() if not k.startswith("head.")} # todo menos la cabeza
res = model.load_state_dict(sd, strict=False)
assert set(res.missing_keys) == {"head.weight", "head.bias"} and not res.unexpected_keys
This is the first fine-tuning step: load a trained model’s body and keep a new task head. With LoRA the problem reverses: adapter keys are absent from the base model, and deciding what to load, freeze and train with the optimizer is the whole method.
A toy Module from scratch
All this machinery fits in about a hundred lines of pure Python. The first cell implements MiniModule over NumPy arrays: registration with __setattr__ and __getattr__, deduplicated traversals, hierarchical-key state_dict, loading with strict, and modes.
import numpy as np
from collections import OrderedDict
class Parameter:
"""Un array entrenable: datos y gradiente (lo que en PyTorch es nn.Parameter)."""
def __init__(self, data):
self.data = np.array(data, dtype=np.float64)
self.grad = None
def __repr__(self):
return f"Parameter{self.data.shape}"
class MiniModule:
def __init__(self):
# object.__setattr__ salta nuestro __setattr__: es la infraestructura del registro
object.__setattr__(self, "_parameters", OrderedDict())
object.__setattr__(self, "_buffers", OrderedDict())
object.__setattr__(self, "_non_persistent", set())
object.__setattr__(self, "_modules", OrderedDict())
object.__setattr__(self, "training", True)
def __setattr__(self, name, value):
if "_parameters" not in self.__dict__:
raise AttributeError("llama a super().__init__() antes de asignar atributos")
if isinstance(value, Parameter):
self._remove(name)
self._parameters[name] = value
elif isinstance(value, MiniModule):
self._remove(name)
self._modules[name] = value
elif name in self._buffers: # reasignar un buffer lo actualiza
self._buffers[name] = np.asarray(value, dtype=np.float64)
else: # cualquier otra cosa: atributo normal, invisible
self._remove(name)
object.__setattr__(self, name, value)
def _remove(self, name):
for d in (self._parameters, self._buffers, self._modules, self.__dict__):
d.pop(name, None)
def __getattr__(self, name): # solo se llama si la búsqueda normal falla
for store in ("_parameters", "_buffers", "_modules"):
d = self.__dict__.get(store, {})
if name in d:
return d[name]
raise AttributeError(f"{type(self).__name__} no tiene el atributo {name!r}")
def register_buffer(self, name, value, persistent=True):
self._remove(name)
self._buffers[name] = np.asarray(value, dtype=np.float64)
if not persistent:
self._non_persistent.add(name)
# --- recorrer el árbol: preorden, con rutas separadas por puntos ---
def named_modules(self, prefix="", memo=None):
memo = set() if memo is None else memo
if id(self) in memo: # un submódulo compartido se visita una vez
return
memo.add(id(self))
yield prefix, self
for name, m in self._modules.items():
yield from m.named_modules(f"{prefix}.{name}" if prefix else name, memo)
def named_parameters(self):
seen = set()
for mod_name, m in self.named_modules():
for name, p in m._parameters.items():
if id(p) not in seen: # parámetros compartidos: una sola vez
seen.add(id(p))
yield (f"{mod_name}.{name}" if mod_name else name), p
def parameters(self):
return [p for _, p in self.named_parameters()]
# --- estado ---
def state_dict(self, prefix=""):
sd = OrderedDict()
for name, p in self._parameters.items():
sd[prefix + name] = p.data # sin copiar: comparte memoria, como en PyTorch
for name, b in self._buffers.items():
if name not in self._non_persistent:
sd[prefix + name] = b
for name, m in self._modules.items():
sd.update(m.state_dict(prefix + name + "."))
return sd
def load_state_dict(self, sd, strict=True):
own = self.state_dict()
missing = [k for k in own if k not in sd]
unexpected = [k for k in sd if k not in own]
if strict and (missing or unexpected):
raise KeyError(f"faltan {missing}, sobran {unexpected}")
for k, v in sd.items():
if k in own:
if own[k].shape != np.shape(v):
raise ValueError(f"forma incompatible en {k}: {own[k].shape} frente a {np.shape(v)}")
own[k][...] = v # copia en el sitio: las referencias siguen valiendo
return missing, unexpected
# --- modos ---
def train(self, mode=True):
for _, m in self.named_modules():
object.__setattr__(m, "training", mode)
return self
def eval(self):
return self.train(False)
def __call__(self, *args):
return self.forward(*args)Notice two details. __init__ uses object.__setattr__ to create the registries themselves, because our __setattr__ needs them to work. And load_state_dict writes in place with own[k][...] = v, like PyTorch’s param.copy_. Now three concrete modules and an MLP that can store hidden layers in a Sequential or a Python list:
class Linear(MiniModule):
def __init__(self, d_in, d_out, rng):
super().__init__()
self.weight = Parameter(rng.normal(0, d_in ** -0.5, (d_out, d_in)))
self.bias = Parameter(np.zeros(d_out))
def forward(self, x):
return x @ self.weight.data.T + self.bias.data
class Dropout(MiniModule):
def __init__(self, p, rng):
super().__init__()
self.p, self.rng = p, rng # un número y un generador: atributos normales
def forward(self, x):
if not self.training or self.p == 0:
return x
keep = self.rng.random(x.shape) >= self.p
return x * keep / (1 - self.p) # dropout invertido
class Sequential(MiniModule):
def __init__(self, *mods):
super().__init__()
for i, m in enumerate(mods):
setattr(self, str(i), m) # pasa por __setattr__: queda registrado
def forward(self, x):
for m in self._modules.values():
x = np.maximum(m(x), 0)
return x
class MLP(MiniModule):
def __init__(self, rng, use_list=False):
super().__init__()
layers = [Linear(4, 8, rng), Linear(8, 8, rng)]
self.hidden = layers if use_list else Sequential(*layers)
self.drop = Dropout(0.5, rng)
self.head = Linear(8, 2, rng)
self.register_buffer("steps", np.zeros(()))
self.register_buffer("cache", np.zeros(4), persistent=False)
def forward(self, x):
if isinstance(self.hidden, list):
for layer in self.hidden:
x = np.maximum(layer(x), 0)
else:
x = self.hidden(x)
return self.head(self.drop(x))
rng = np.random.default_rng(0)
for use_list in (False, True):
m = MLP(rng, use_list)
n = sum(p.data.size for p in m.parameters())
print(f"use_list={use_list}: {n} parámetros, claves {list(m.state_dict())}")
print()
m = MLP(rng)
for name, mod in m.named_modules():
print(f"{name or '(raíz)':10s} {type(mod).__name__:10s} training={mod.training}")
x = rng.normal(size=(3, 4))
print("train(): ¿dos pasadas iguales?", np.allclose(m(x), m(x)))
m.eval()
print("eval(): ¿dos pasadas iguales?", np.allclose(m(x), m(x)), "| drop.training =", m.drop.training)With the list, the model goes from 130 parameters to 18, those of the head, and state_dict loses the hidden layers’ four keys even though forward still uses them. The steps buffer appears first because it is a root-owned tensor, while nonpersistent cache does not appear. And eval() reaches Dropout through the tree: the MLP knows nothing of dropout, only propagates the flag.
The last cell loads weights from one model into another: first only the body, then a prefixed dictionary like that of a compiled model.
src, dst = MLP(np.random.default_rng(1)), MLP(np.random.default_rng(2))
w_ref = dst.head.weight.data # una referencia, como la que guarda un optimizador
sd = src.state_dict()
print("¿state_dict comparte memoria con el modelo?", sd["head.weight"] is src.head.weight.data)
# 1. Cargar solo el cuerpo, como al reutilizar un backbone con otra cabeza
body = {k: v for k, v in sd.items() if not k.startswith("head.")}
missing, unexpected = dst.load_state_dict(body, strict=False)
print("faltan:", missing, "| sobran:", unexpected)
assert set(missing) == {"head.weight", "head.bias"} and not unexpected
# 2. Claves con un prefijo ajeno (el que añade torch.compile): strict=False no se queja de nada
wrapped = {"_orig_mod." + k: v for k, v in sd.items()}
missing, unexpected = dst.load_state_dict(wrapped, strict=False)
print(f"con prefijo: faltan {len(missing)} y sobran {len(unexpected)}: no se ha cargado nada")
fixed = {k.removeprefix("_orig_mod."): v for k, v in wrapped.items()}
dst.load_state_dict(fixed) # strict=True: si algo no encaja, error
print("¿pesos iguales tras renombrar?", np.array_equal(dst.head.weight.data, src.head.weight.data))
print("¿la referencia antigua sigue siendo el peso del modelo?", w_ref is dst.head.weight.data)The last line shows why PyTorch loads by copying: anything holding a weight reference, such as the optimizer, still points to the weight used by the model.
torch.optim: groups, state and step
The constructor accepts an iterable of tensors or dictionaries. torch.optim.SGD(model.parameters(), lr=0.1) has one group; with
opt = torch.optim.AdamW([
{"params": matrices, "weight_decay": 0.1},
{"params": sesgos_y_normas, "weight_decay": 0.0},
{"params": model.head.parameters(), "lr": 1e-3}, # este grupo usa otro lr
], lr=3e-4, betas=(0.9, 0.95))
there are three, the first two inheriting lr=3e-4. The constructor consumes the iterable and stores tensor references in each group’s list. The fact that model.parameters() is a generator does not mean the optimizer reevaluates it each step: it traverses it once at construction. Hence the replaced-head failure: model.head = nn.Linear(...) registers new module tensors, but optimizer lists retain the old ones. If you really must add parameters later, opt.add_param_group({"params": ...}) does so explicitly.
State is indexed by tensors themselves rather than names, because the optimizer does not know names. Its state_dict translates tensors to integers by position in groups: {"state": {0: {"momentum_buffer": ...}, 1: ...}, "param_groups": [{"lr": 0.1, ..., "params": [0, 1, ...]}]}. To restore an optimizer, create it with parameters in the same order. If the model’s layers are constructed in another order, load_state_dict loads silently and one layer’s momentum buffer ends up associated with another; mismatched shapes fail at the next step, matching shapes never fail. Revisit this in complete checkpoints.
zero_grad and step
Recall backward semantics: gradients accumulate in .grad. Clear them before each backward; accumulating gradients across microbatches simply means not clearing them. Since PyTorch 2.0, zero_grad sets .grad = None instead of filling with zeros. This saves memory and a write, and changes an edge case: a parameter with no gradient, because it did not participate in the loss or is frozen, is skipped by step, while one with zero gradient is still updated. With momentum or weight decay, updating with zero gradient moves the parameter: the momentum buffer keeps pushing and decay keeps shrinking. For example, if you freeze a layer after creating an SGD optimizer with momentum and use zero_grad(set_to_none=False), the layer keeps moving each step, progressively less, as its momentum buffer decays like ; with the default it stays still from the first step.
PyTorch’s SGD-with-momentum rule, with gradient , weight decay , momentum and dampening (dampening, zero by default), is
The torch.optim.SGD documentation notes a subtle difference from Sutskever et al. (2013), where learning rate multiplies the gradient inside velocity: and . With constant trajectories agree; with a schedule they do not. You will prove this in the exercises. In AdamW, weight decay is not added to the gradient but applied separately, , before Adam’s step: decoupled weight decay. Why it differs from an penalty is studied in weight decay versus L2 regularization.
Groups without weight decay
The most common use of groups is excluding biases, normalization parameters and, depending on the author, embeddings from weight decay. This is an empirical convention rather than a theorem, with reasonable arguments. Weight decay was intended to limit the scale of feature-mixing matrices. A bias or normalization gain comprises few parameters per layer and barely affects model capacity, and shrinking LayerNorm gain , whose natural value is 1, toward zero pushes network outputs to zero without useful regularization. Weights followed by normalization also do not change the function when rescaled, due to normalization scale invariance, so decay there acts more like effective learning-rate control than regularization.
Two rules are widespread. BERT excludes by name parameters containing LayerNorm or bias. minGPT decays only Linear weights, excluding biases, LayerNorm and Embedding, while nanoGPT uses dimensionality: decay every tensor with two or more dimensions, including embeddings, but not one-dimensional tensors. The dimension rule does not depend on names, which vary by model. You will write your own version in the exercises.
An optimizer using the torch.optim API
The torch.optim.Optimizer base class handles administration: it builds groups with defaults, creates self.state and saves and loads its state_dict. A subclass only needs step. This one implements SGD with momentum and weight decay using the same operations in the same order as PyTorch’s reference implementation, checked for a hundred steps.
import copy
import torch
import torch.nn as nn
class MiSGD(torch.optim.Optimizer):
def __init__(self, params, lr=1e-3, momentum=0.0, weight_decay=0.0):
super().__init__(params, dict(lr=lr, momentum=momentum, weight_decay=weight_decay))
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None: # algunos optimizadores reevalúan la pérdida (LBFGS)
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
for p in group["params"]:
if p.grad is None: # sin gradiente (congelado o fuera de la pérdida): se salta
continue
d = p.grad
if group["weight_decay"] != 0:
d = d.add(p, alpha=group["weight_decay"])
if group["momentum"] != 0:
state = self.state[p] # estado perezoso, indexado por el propio tensor
if "momentum_buffer" not in state:
state["momentum_buffer"] = d.clone()
else:
state["momentum_buffer"].mul_(group["momentum"]).add_(d)
d = state["momentum_buffer"]
p.add_(d, alpha=-group["lr"])
return loss
for device in ["cpu"] + (["cuda"] if torch.cuda.is_available() else []):
torch.manual_seed(0)
a = nn.Sequential(nn.Linear(10, 32), nn.Tanh(), nn.Linear(32, 1)).to(device)
b = copy.deepcopy(a)
opt_a = MiSGD(a.parameters(), lr=0.05, momentum=0.9, weight_decay=1e-2)
opt_b = torch.optim.SGD(b.parameters(), lr=0.05, momentum=0.9, weight_decay=1e-2)
X, y = torch.randn(64, 10, device=device), torch.randn(64, 1, device=device)
for _ in range(100):
for model, opt in ((a, opt_a), (b, opt_b)):
opt.zero_grad()
((model(X) - y) ** 2).mean().backward()
opt.step()
iguales = all(torch.equal(p, q) for p, q in zip(a.parameters(), b.parameters()))
print(f"{device}: ¿idénticos bit a bit tras 100 pasos? {iguales}")
sd = opt_a.state_dict()
print("claves del estado:", list(sd["state"]), "| params del grupo:", sd["param_groups"][0]["params"])
print("estado del parámetro 0:", list(sd["state"][0]))npm run lab and open the connection link.torch.equal requires exact, not approximate equality. Bitwise equality is possible because both implementations perform the same floating-point operations in the same order; replacing d.add(p, alpha=wd) with d + wd * p can already change the last bit because it rounds the product before addition. The last line shows the optimizer state_dict format: tensors became integers 0 to 3.
Schedulers: learning rate as a function of step
A scheduler does not optimize: each call to its step() method rewrites each optimizer group’s "lr" according to a rule. PyTorch learning-rate schedulers share a mechanism:
- On construction they save each group’s lr as
initial_lrand apply the value at time 0. WithLambdaLR, receiving a counter function , group lr becomesinitial_lr. (We call it , not as the class name suggests, because denotes weight decay.) - They keep a counter,
last_epoch, starting at 0 and incrementing with eachscheduler.step(). Despite its name, it counts calls, not epochs: called every optimizer step, it counts steps. - After each call,
LambdaLRsets each group’s lr to itsinitial_lrtimes ; others use their corresponding rule.get_last_lr()returns it.
The correct loop order is opt.step() followed by scheduler.step(). Reversing it triggers PyTorch’s Detected call of lr_scheduler.step() before optimizer.step() warning and loses the schedule’s first value. Because the factor multiplies each group’s lr, one scheduler moves all groups in parallel and preserves ratios; LambdaLR also accepts a list of functions, one per group.
The most used transformer training schedule is linear warmup plus cosine decay. With counter , warmup steps , total and final fraction of peak ,
and for . The cosine comes from SGDR (Loshchilov and Hutter, 2017), which combined it with restarts; warmup avoids large initial steps when Adam’s second-moment estimates are not yet reliable and the network is far from a stable region. With Hugging Face’s transformers convention , the first step uses lr 0; other implementations use . Their properties and why they work are covered in learning-rate schedules. PyTorch components express nearly the same without lambdas; LinearLR requires a positive start_factor, hence rather than 0:
warm = torch.optim.lr_scheduler.LinearLR(opt, start_factor=1e-3, end_factor=1.0, total_iters=W)
cos = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=T - W, eta_min=r * 3e-4)
sched = torch.optim.lr_scheduler.SequentialLR(opt, schedulers=[warm, cos], milestones=[W])
SequentialLR delegates to the first scheduler until milestone and the second thereafter. Note CosineAnnealingLR’s eta_min is an absolute lr, while the lambda’s is relative to each group: with different group lrs, the lambda preserves ratios at the end too. Two schedulers outside this pattern are ReduceLROnPlateau, receiving a metric via sched.step(val_loss) once per evaluation, and OneCycleLR, requiring total steps at construction.
LambdaLR, expressed in optimizer steps. The plot shows each group's lr at each step; the table shows what each accumulates over training: lr sum and contraction from AdamW's decoupled weight decay. Change the call to ‘per epoch’ and read the warning. Try the step schedule too. Then give biases weight decay and see how much they shrink.What you should have seen:
- The epoch mistake multiplies warmup duration by steps per epoch. With and 100 steps per epoch, warmup intended to end at step 100 would end at 10,000, while training lasts 1000: lr never exceeds 9% of peak. With the step schedule milestones never arrive. There is no error or warning because both calls are legal: the scheduler does not know the units used for .
- Groups move in parallel. The scheduler multiplies each group’s base lr by the same factor, preserving their ratios throughout training.
- Decoupled weight decay depends on the schedule. Each step multiplies group parameters by , so total contraction is , with relative error of order , negligible at these values. The table confirms it: the lr sum matters. Changing the schedule, lengthening training or making the epoch mistake changes how much the same regularizes. This underlies AdamW’s timescale.
One practical detail: LambdaLR’s state_dict saves the counter and base lrs but not the function, which cannot be serialized if it is a lambda. To resume training, rebuild the scheduler with the same function and load its state_dict.
The canonical training and evaluation loop
Each piece has a reason:
model.train()at the start of each epoch, not just once at program start, because the previous epoch’s evaluation left it inevalmode.- Clear gradients anywhere before
backward. Putting this immediately beforebackwardrather than at step end leaves.gradavailable for inspection afterstep. clip_grad_norm_betweenbackwardandstep. It rescales all gradients together so their joint norm does not exceedmax_norm, returning the norm before clipping: a cheap instability signal worth logging. Gradient clipping is covered in the neural-network block.scheduler.step()afteropt.step(), in the inner loop if counts steps.- No
loss.item()each step..item()copies a GPU number to CPU and forces a wait for queued GPU work; accumulatingloss.detach()in a tensor and synchronizing once per epoch avoids that cost. Measure it in the GPU lesson.
Evaluation combines two independent mechanisms. model.eval() changes mode-dependent modules’ behavior. torch.inference_mode() prevents autograd recording the graph, saving memory and time. Neither implies the other: with only inference_mode, dropout remains active and batch normalization keeps updating statistics; with only eval(), an unused graph is built and stored.
Metrics are summed and divided at the end by the number of examples. Averaging batch means is a classic mistake: if validation has 1000 examples in batches of 256, the last batch has 232 and weighs as much in the mean of means as batches of 256. With reduction="sum" in the loss and sums on GPU, the result is the exact mean.
Two everyday modules behave differently by mode and are the reason for train() and eval():
- Dropout. During training it zeroes each component with probability and multiplies survivors by , inverted dropout, preserving expected output. During evaluation it is identity.
- Batch normalization. In training,
BatchNormnormalizes using batch mean and biased batch variance, and updates buffers with and , where is the unbiased batch variance and by default. Note the convention: thismomentumweights the new value, unlike optimizer momentum. In evaluation it normalizes with and and changes nothing. Running statistics are studied in depth with batch normalization.
BatchNorm1d(3) followed by Dropout(p) and Linear(3, 1), evaluates the same 64-example validation set. Each ‘Validate’ is a complete pass with the chosen batch size. The first panel compares prediction and target on the last pass; the second shows each pass's MSE; the table shows normalization buffers. The initial state already contains two passes: one in eval() and one in train() with data sorted by label, like an unshuffled DataLoader over a sorted file. Validate in eval(): does it match the first pass? Then try batches of 4 and 64, shuffled data and the inference_mode switch.What you should have seen:
- In
eval(), validation is a deterministic function of the model. Repeating it yields the same number. Intrain(), each pass has different MSE because the dropout mask changes and, if data are shuffled, batch composition changes. - With sorted data,
trainmode destroys the signal. Each batch has examples with similar targets, and batch normalization subtracts the batch mean, precisely what distinguishes batches. Predictions collapse toward a horizontal band and MSE rises to roughly target variance, tens of times the original. With batches of 64, the whole set in one batch, damage comes almost entirely from dropout. - Validation in
trainmodifies the model. Each batch updatesrunning_meanandrunning_var, including insideinference_mode, because updates depend onself.training, not autograd. After a sorted pass with batches of 4, the nexteval()validation no longer gives original MSE: the saved checkpoint contains validation statistics, with later batches weighted more heavily.
The course reference training loop
This version, with small variations, is used throughout the course. train_one_epoch and evaluate know nothing about model or data; they receive the model, an iterable of batches, optimizer, scheduler and loss function. Batches come from a DataLoader, covered in the next lesson; here it suffices to know it is an iterable of (x, y) pairs.
import math, time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
def train_one_epoch(model, loader, opt, sched, loss_fn, device, max_norm=None):
model.train()
total, n, norms = 0.0, 0, []
for x, y in loader:
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
out = model(x)
loss = loss_fn(out, y)
opt.zero_grad(set_to_none=True)
loss.backward()
if max_norm is not None:
norms.append(nn.utils.clip_grad_norm_(model.parameters(), max_norm))
opt.step()
if sched is not None:
sched.step() # por paso: la lambda cuenta pasos
total += loss.detach() * len(x) # suma en la GPU: sin sincronizar en cada paso
n += len(x)
grad_norm = torch.stack(norms).max().item() if norms else float("nan")
return (total / n).item(), grad_norm
@torch.inference_mode()
def evaluate(model, loader, loss_fn, device, metrics=None):
model.eval()
metrics = metrics or {}
sums = {"loss": torch.zeros((), device=device), **{k: torch.zeros((), device=device) for k in metrics}}
n = 0
for x, y in loader:
x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
out = model(x)
sums["loss"] += loss_fn(out, y, reduction="sum") # suma, no media de medias
for k, f in metrics.items():
sums[k] += f(out, y).sum()
n += len(x)
return {k: (v / n).item() for k, v in sums.items()}
def warmup_cosine(step, warmup, total, floor=0.1):
if step < warmup:
return step / max(1, warmup)
prog = min(1.0, (step - warmup) / max(1, total - warmup))
return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * prog))
def param_groups(model, weight_decay):
decay, no_decay = [], []
for name, p in model.named_parameters():
if not p.requires_grad:
continue
(decay if p.ndim >= 2 else no_decay).append(p)
return [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}]npm run lab and open the connection link.The decorator @torch.inference_mode() wraps all evaluation, and model.eval() goes inside evaluate so nobody can forget it. Now consider a residual MLP with LayerNorm and dropout on a synthetic three-class spiral-boundary problem, and a hook logging each block’s mean residual-branch norm. Hooks are explained next; here observe that they are registered without changing the model class.
device = "cuda" if torch.cuda.is_available() else "cpu"
g = torch.Generator().manual_seed(0)
# Datos sintéticos: 3 clases separadas por una frontera en espiral en 2D, más 14 dimensiones de ruido
def make_data(n):
z = torch.randn(n, 2, generator=g) * 1.6
r, a = z.norm(dim=1), torch.atan2(z[:, 1], z[:, 0])
y = ((r + a / math.pi * 0.9 + 3) % 3).long()
x = torch.cat([z, 0.5 * torch.randn(n, 14, generator=g)], dim=1)
return x, y
Xtr, ytr = make_data(12_000)
Xva, yva = make_data(3_000)
train_loader = DataLoader(TensorDataset(Xtr, ytr), batch_size=256, shuffle=True, generator=g, pin_memory=(device == "cuda"))
val_loader = DataLoader(TensorDataset(Xva, yva), batch_size=1024, pin_memory=(device == "cuda"))
class MLP(nn.Module):
def __init__(self, d_in=16, d=128, n_layers=3, n_classes=3, p=0.1):
super().__init__()
self.inp = nn.Linear(d_in, d)
self.layers = nn.ModuleList([nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Dropout(p)) for _ in range(n_layers)])
self.head = nn.Linear(d, n_classes)
def forward(self, x):
h = self.inp(x)
for layer in self.layers:
h = h + layer(h) # bloque residual
return self.head(h)
torch.manual_seed(0)
model = MLP().to(device)
epochs, steps = 8, len(train_loader)
opt = torch.optim.AdamW(param_groups(model, 0.05), lr=3e-3)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: warmup_cosine(s, warmup=steps, total=epochs * steps))
acc = lambda out, y: (out.argmax(1) == y).float()
# Hook: norma media de la salida de la rama residual de cada bloque, sin tocar la clase MLP
act_norms = {}
def make_hook(name):
def hook(module, args, output):
act_norms.setdefault(name, []).append(output.detach().norm(dim=-1).mean())
return hook
handles = [layer.register_forward_hook(make_hook(f"layers.{i}")) for i, layer in enumerate(model.layers)]
print(f"dispositivo: {device} | {sum(p.numel() for p in model.parameters())} parámetros | {steps} pasos por época")
print(f"grupos: {[len(gr['params']) for gr in opt.param_groups]} tensores, weight decay {[gr['weight_decay'] for gr in opt.param_groups]}")
t0 = time.perf_counter()
for epoch in range(epochs):
act_norms.clear()
tr_loss, gmax = train_one_epoch(model, train_loader, opt, sched, F.cross_entropy, device, max_norm=1.0)
norms = {k: torch.stack(v).mean().item() for k, v in act_norms.items()} # solo pasos de entrenamiento
val = evaluate(model, val_loader, F.cross_entropy, device, {"acc": acc})
print(f"época {epoch}: lr {sched.get_last_lr()[0]:.2e} train {tr_loss:.3f} val {val['loss']:.3f} "
f"acc {val['acc']:.3f} |g|máx {gmax:.2f} |h| " + " ".join(f"{v:.1f}" for v in norms.values()))
print(f"{time.perf_counter() - t0:.1f} s")
for h in handles:
h.remove()
print("hooks activos tras remove():", sum(len(l._forward_hooks) for l in model.layers))npm run lab and open the connection link.Three readings of the output. The groups have 5 tensors with decay, the five matrices, and 11 without: five Linear biases and gains and biases of three LayerNorms. Validation loss is lower than training loss in every epoch: this is not data leakage but the combination of dropout, active only in training, and training loss being an average over an epoch in which the model improved. Residual-branch norms grow with depth and training, reaching about 8 in the first block and 17 in the last in the final epoch, the kind of signal hooks monitor without modifying the model; training instrumentation makes it a habit.
Hooks: looking inside without changing code
Module hooks are functions registered on a module for PyTorch to call at fixed points in forward or backward. They inspect and modify activations and gradients of a model whose code you cannot or do not want to change, such as a downloaded one.
| registration | function signature | when called | if it returns a value |
|---|---|---|---|
register_forward_pre_hook | hook(module, args) | before forward | replaces arguments |
register_forward_hook | hook(module, args, output) | after forward | replaces output |
register_full_backward_pre_hook | hook(module, grad_output) | before calculating gradients with respect to module inputs | replaces grad_output |
register_full_backward_hook | hook(module, grad_input, grad_output) | with gradients with respect to module inputs and outputs | replaces grad_input |
tensor.register_hook | hook(grad) | when that tensor’s gradient is calculated | replaces gradient |
args is the tuple of positional forward arguments, and grad_input and grad_output are tuples of gradients with respect to inputs and outputs, with None for those not requiring gradients. All registrations return a RemovableHandle; handle.remove() removes the hook. Removal matters: a forgotten hook keeps running every forward, accumulating data or changing outputs long after it is needed. A clean pattern is a context manager:
from contextlib import contextmanager
@contextmanager
def capture(model, names):
acts, handles = {}, []
modules = dict(model.named_modules())
for name in names:
def hook(module, args, output, name=name): # name=name: fija el valor de cada vuelta
acts[name] = output.detach()
handles.append(modules[name].register_forward_hook(hook))
try:
yield acts
finally: # se quitan aunque el forward falle
for h in handles:
h.remove()
with capture(model, ["layers.0", "layers.2"]) as acts:
model(x)
print({k: v.shape for k, v in acts.items()})
Four rules prevent common problems:
- Save
output.detach(), notoutput. The output carriesgrad_fn, and saving it keeps the entire graph and intermediate activations alive until the dictionary disappears. If accumulating many, move them to CPU. - Hooks run only when calling
model(x).model.forward(x)bypasses__call__and all hooks, another reason never to callforwarddirectly. - A forward hook returning a value changes the model. Useful for intervention experiments such as zeroing an attention head, but an accidental return such as
return output * 0in a debugging function changes computation. - Capture
namein the closure. A function defined in a loop sees the loop variable, not its value on each iteration: without default argumentname=name, every hook writes to the last layer’s key.
Hooks underpin instrumentation (per-layer activation and gradient norms), NaN and Inf tracing (a hook checking torch.isfinite on each output locates the first failing layer) and, later, mechanistic interpretability, which reads and modifies intermediate transformer activations without changing its code.
Common mistakes
Exercises
self.layers = [nn.Linear(64, 64) for _ in range(4)], uses them in a loop in forward, and also has self.head = nn.Linear(64, 10). You create opt = torch.optim.AdamW(model.parameters()) and train on CPU. Which statements are true? More than one may apply.More than one answer may be correct.
nn.Linear(768, 3072) have, with bias? This is the first MLP layer in each block of a transformer such as GPT-2 small.opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) and then adapt the model to 5 classes with model.head = nn.Linear(512, 5). You train several epochs with the canonical loop. What happens?torch.save(cmodel.state_dict(), 'ckpt.pt') with cmodel = torch.compile(model). In another script you load with model.load_state_dict(torch.load('ckpt.pt', weights_only=True), strict=False) into an uncompiled model of the same class. What happens?running_mean in BatchNorm1d with default momentum is . By mistake you validate in train mode inside torch.inference_mode() over 20 batches, each with feature mean . What is running_mean afterward?More than one answer may be correct.
Step 1 of 4. With constant , what should we prove by induction on ?
build_param_groups(model, weight_decay), returning two groups for a torch.optim optimizer: [{'params': con_decay, 'weight_decay': weight_decay}, {'params': sin_decay, 'weight_decay': 0.0}]. A parameter gets no weight decay if it has fewer than two dimensions (biases, normalization gains, scales) or belongs to an nn.Embedding; the rest get decay. Frozen parameters (requires_grad=False) belong to neither group, and every tensor must appear exactly once, including tied weights: if one tensor is registered in multiple modules, treat it as belonging to the first registering module in named_modules() order.import torch
import torch.nn as nn
def build_param_groups(model, weight_decay):
# devuelve [{"params": [...], "weight_decay": weight_decay}, {"params": [...], "weight_decay": 0.0}]
passmake_warmup_cosine(optimizer, warmup_steps, total_steps, min_ratio=0.0), returning a torch.optim.lr_scheduler.LambdaLR with the text's schedule: factor during warmup (), cosine decay from 1 to min_ratio between and , and min_ratio from onward. Here is the scheduler counter, 0 at construction and incremented by each scheduler.step(). With warmup_steps=0, the schedule must start at the peak. Tests check each group's lr at specific steps.import math
import torch
def make_warmup_cosine(optimizer, warmup_steps, total_steps, min_ratio=0.0):
def factor(step):
# step es el contador del scheduler: 0 al crearlo, +1 en cada sched.step()
return 1.0
return torch.optim.lr_scheduler.LambdaLR(optimizer, factor)Summary
nn.Module is a tree built automatically by assigning attributes: anything other than a Parameter, buffer or Module is invisible to parameters(), state_dict(), .to() and train()/eval(). An optimizer is a list of tensor references fixed at construction, organized in groups with their own hyperparameters, and a scheduler rewrites those groups’ lr each time it is called. The canonical loop connects all three; most failures are silent and can be avoided by knowing what each mechanism sees and when.- Registration by assignment.
__setattr__checks value type:Parameterto_parameters,Moduleto_modules, buffers withregister_buffer. Python lists and dictionaries hide contents; useModuleList,ModuleDictorSequential. Traversals deduplicate by identity, allowing tied weights. state_dictmaps hierarchical paths to tensors sharing memory with the model.load_state_dictcopies in place, compares keys withstrict, and never accepts different shapes.strict=Falserequires checkingmissing_keysandunexpected_keys.torch.optim:param_groupswith per-group hyperparameters, tensor-indexedstate,zero_grad(set_to_none=True)andstep. Saved state identifies parameters by position. Groups can exclude biases, normalizations and, by convention, embeddings from weight decay.- Schedulers count calls, not epochs, and multiply each group’s lr. Call them after
opt.step()in the unit used to write the schedule; decoupled weight decay depends on the lr sum. - The loop:
train(), forward, loss,zero_grad,backward, clipping,step,scheduler.step(); and evaluation witheval()andinference_mode(), summing metrics across examples. - Hooks are functions before and after module forward or during backward, with a handle for removal. Save graph-detached activations and always remove registered hooks.