Optimizers in networks: learning rate, warmup and weight decay
Apply SGD, momentum, AdamW, learning-rate range tests and schedules to networks. Examine warmup, the AdamW decay timescale, parameter groups and fair optimizer comparisons.
After this lesson you can
- Run and interpret a learning-rate range test to select candidate rates.
- Examine proposed warmup mechanisms by measuring loss and update norms in early steps.
- Derive AdamW's exponentially weighted update interpretation and its decay timescale.
- Configure parameter groups that exclude biases and normalization parameters from weight decay.
- Compare SGD with momentum and AdamW under an equivalent tuning budget.
Before you start
- 15Learning rate and batch size scalingMicro framework to PyTorch correspondenceOutput layer and loss pairing
- 06Heavy-ball momentumNesterov accelerated gradientStochastic momentumAdamAdamW (decoupled weight decay)Weight decay versus L2 regularizationLearning-rate schedulesGradient descent dynamics on quadratics
- 00PyTorch optimizer APIPyTorch learning rate schedulers
A step that is too large
A reasonable architecture can stall with a tiny rate or lose what it learned in a few steps with an excessive rate. Learning rate does not act alone: batch size, parameter scale, optimizer state, and schedule change the outcome. In the previous lesson you saw that changing batch size changes both noise and the number of steps.
To see the scale without noise, consider with . SGD with exact gradient gives . There is contraction if ; between 1 and 2 signs alternate, and from 2 onward there is no strict contraction. In a network curvature changes with position, minibatch, and direction, so this quadratic is a local guide, not a recipe for setting Adam.
SGD’s direction is the minibatch gradient. Momentum accumulates past directions; Adam maintains moving averages of the gradient and its square and divides by a per-coordinate scale estimate. See Adam for bias corrections. In AdamW, decay is applied separately to the parameter after constructing the adaptive direction. In PyTorch SGD, weight_decay is added to the gradient before momentum accumulation: this is not the same operation. Decay and L2 penalty can coincide in SGD without momentum under specific conditions, but not generally in Adam.
Finding a rate scale
The range test increases the rate during a short run, for example geometrically from a minimum to a maximum. Read loss against rate on a logarithmic axis: an initial plateau suggests steps too small for that budget; a sustained rise or non-finite values indicate the trajectory has stopped being useful. Batches change and the model evolves while rate changes, so each point is not an independent experiment with the same weights.
Smith’s method uses a progressive sweep; here we use an exponential variant. The observed minimum does not guarantee the best rate for a long run. Try a candidate before the rise and its neighbors, repeat across seeds, and decide with validation. The test changes weights, accumulators, and random state: save and restore all three before actual training. If the sweep ends due to non-finite values, do not extrapolate a nonexistent curve.
Warmup and schedules
Warmup begins at a lower rate and reaches the peak in updates. For steps , one linear choice is ; with the peak applies from the start. It directly reduces the length of the first update for the same direction. In Adam, the second moment initially comes from few observations; bias correction corrects its expectation under stationary assumptions but does not remove all uncertainty or guarantee a good direction. Kalra and Barkeshli study mechanisms involving stability and initial curvature in their models. These are hypotheses to measure, not a law predicting a peak for every network.
The curvature diagnostic is a Rayleigh quotient after five Hessian-vector products on a fixed batch. A large residual warns that the vector is not yet an eigenvector; even if it converges, power iteration can find the eigenvalue of largest magnitude, not the algebraic maximum. Threshold corresponds to plain gradient descent on a local positive quadratic, not a direct condition for Adam with adaptive state. In this test the first update decreases with warmup, but the curves do not prove it avoided a spike or a systematic curvature decrease.
After warmup, cosine decreases smoothly to its minimum; one-cycle rises then falls, and WSD keeps a plateau before decay. The step at which the scheduler is called matters: use the intended rate for each update and check endpoints with a small table. The end of a decay can reduce loss but also consumes budget that cannot be recovered if the run is extended. Hägele and colleagues compare schedules and extensions under specific conditions; no schedule wins on every task.
The lab’s one-cycle function represents only the rate, with linear rise and fall. Smith’s policy also studies varying momentum; do not confuse a demonstration of rate shape with a complete reproduction of that recipe. In every schedule in this lab, index zero is the first update and the final index the final step; with only one decay position, the minimum is used directly.
For example, in their Table 5, for a one-billion-parameter model trained on 100 000 million (100 billion) FineWeb tokens, aggregate score is 46.26 with cosine to 10% of the maximum rate and 46.20 with linear decay over the final 20% of training. This compares that task suite and budget; it does not guarantee equivalence for your network.
AdamW’s horizon
The AdamW timescale expresses how long the past influences the present. For a parameter receiving decay with constant rate and coefficient, write for Adam’s complete adaptive direction, including corrections. The recurrence is
If , expanding it gives
The approximation requires small . The weight of an update from steps ago is proportional to . With , the sum can be normalized as an exponential average with coefficient . This is an algebraic identity: depends on the trajectory, so preserving does not ensure the same learning. If the rate varies, initial retention is rather than a single exponential with fixed horizon.
With steps per epoch, the horizon is epochs. If the dataset grows to steps, exactly preserving retention per epoch at the same rate requires
When and is small, . This preserves the multiplicative factor’s memory, not a guarantee of optimal quality when changing dataset size, model, or duration. Wang and Aitchison study decay scales in specific settings and motivate this interpretation; testing the hypothesis requires your own sweep.
In one of their experiments, ResNet-18 and ViT train on ImageNet subsets reduced to , with batch 100, initial rate , and 100 epochs. Optimal decay changes with dataset size while the horizon measured in epochs varies less; the rate follows a cosine, so the horizon calculated using its initial value only approximately describes a variable-rate run.
Which parameters decay and how to compare
A common policy excludes biases, normalization scales and shifts, and sometimes embeddings. It is not a theorem: exclusion can help or hurt depending on model and task. Enumerate parameters by identity, not just name; an embedding tied to the output matrix can receive conflicting policies that must be resolved explicitly. The lab rejects conflicts; the exercise chooses to prioritize exclusion. Groups also allow per-layer rates, but that changes both updates and effective decay . Use one optimizer with documented groups and ensure each trainable parameter appears exactly once.
A fair comparison between SGD with momentum and AdamW controls split, architecture, initialization, examples processed, and tuning budget. Sweep both hyperparameters with the same number of configurations and seeds, select using validation, and reserve test. Their per-step cost and memory need not match; report both statistical budget and measured cost without turning a local measurement into a universal property. Results can change with architecture or data.
Lab from scratch: schedule and sweep
The tensor engine from the previous framework lesson is reused and included here so the notebook is self-contained. The stratified split separates validation; all comparisons use identical initial weights and minibatches. Sweep loss is training loss, measured on a different batch each step. The final comparison uses validation; it does not turn this short test into a definitive measure of generalization.
import numpy as np
from copy import deepcopy
def unbroadcast(grad, shape):
grad = np.asarray(grad)
while grad.ndim > len(shape):
grad = grad.sum(axis=0)
for axis, size in enumerate(shape):
if size == 1 and grad.shape[axis] != 1:
grad = grad.sum(axis=axis, keepdims=True)
if grad.shape != tuple(shape):
raise ValueError('formas incompatibles')
return grad
class Tensor:
def __init__(self, data, parents=(), backward=None):
self.data = np.array(data, dtype=np.float64, copy=True)
self.grad = np.zeros_like(self.data)
self.parents = tuple(parents)
self._backward = backward or (lambda: None)
@staticmethod
def wrap(x): return x if isinstance(x, Tensor) else Tensor(x)
def __add__(self, other):
other = Tensor.wrap(other)
a_shape, b_shape = self.data.shape, other.data.shape
out = Tensor(self.data + other.data, (self, other))
def backward():
self.grad += unbroadcast(out.grad, a_shape)
other.grad += unbroadcast(out.grad, b_shape)
out._backward = backward
return out
__radd__ = __add__
def __mul__(self, other):
other = Tensor.wrap(other)
a, b = self.data.copy(), other.data.copy()
out = Tensor(a*b, (self, other))
def backward():
self.grad += unbroadcast(out.grad*b, a.shape)
other.grad += unbroadcast(out.grad*a, b.shape)
out._backward = backward
return out
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-Tensor.wrap(other))
def __rsub__(self, other): return Tensor.wrap(other) - self
def __matmul__(self, other):
other = Tensor.wrap(other)
a, b = self.data.copy(), other.data.copy()
if a.ndim != 2 or b.ndim != 2:
raise ValueError('matmul admite matrices 2D')
out = Tensor(a @ b, (self, other))
def backward():
self.grad += out.grad @ b.T
other.grad += a.T @ out.grad
out._backward = backward
return out
def tanh(self):
y = np.tanh(self.data)
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*(1-y*y))
return out
def sigmoid(self):
x = self.data
y = np.exp(-np.logaddexp(0, -x))
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*y*(1-y))
return out
def relu(self):
mask = self.data > 0
out = Tensor(np.maximum(self.data, 0), (self,))
out._backward = lambda: self._accumulate(out.grad*mask)
return out
def exp(self):
y = np.exp(self.data)
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*y)
return out
def log(self):
x = self.data.copy()
if np.any(x <= 0): raise ValueError('log exige entrada positiva')
out = Tensor(np.log(x), (self,))
out._backward = lambda: self._accumulate(out.grad/x)
return out
def _accumulate(self, value): self.grad += value
def sum(self, axis=None, keepdims=False):
shape = self.data.shape
axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
axes = tuple(a % len(shape) for a in axes) if shape else ()
out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,))
def backward():
g = out.grad
if not keepdims:
for a in sorted(axes): g = np.expand_dims(g, a)
self.grad += np.broadcast_to(g, shape)
out._backward = backward
return out
def mean(self, axis=None, keepdims=False):
axes = tuple(range(self.data.ndim)) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
count = int(np.prod([self.data.shape[a] for a in axes]))
return self.sum(axis, keepdims) * (1.0/count)
def max(self, axis=None, keepdims=False):
shape = self.data.shape
axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
axes = tuple(a % len(shape) for a in axes) if shape else ()
maxima = self.data.max(axis=axis, keepdims=True)
mask = self.data == maxima
counts = mask.sum(axis=axis, keepdims=True)
out = Tensor(self.data.max(axis=axis, keepdims=keepdims), (self,))
def backward():
g = out.grad
if not keepdims:
for a in sorted(axes): g = np.expand_dims(g, a)
self.grad += mask * (g/counts)
out._backward = backward
return out
def reshape(self, *shape):
original = self.data.shape
out = Tensor(self.data.reshape(*shape), (self,))
out._backward = lambda: self._accumulate(out.grad.reshape(original))
return out
def transpose(self, *axes):
perm = (tuple(axes[0]) if len(axes) == 1 and isinstance(axes[0], (tuple, list))
else tuple(axes) if axes else tuple(reversed(range(self.data.ndim))))
transposed = self.data.transpose(perm) # NumPy valida la permutación.
normalized = tuple(a % self.data.ndim for a in perm) if self.data.ndim else ()
inverse = np.argsort(normalized)
out = Tensor(transposed, (self,))
out._backward = lambda: self._accumulate(out.grad.transpose(inverse))
return out
def __getitem__(self, index):
# También pueden mutarse listas o estructuras anidadas de índices.
index = deepcopy(index)
out = Tensor(self.data[index], (self,))
def backward(): np.add.at(self.grad, index, out.grad)
out._backward = backward
return out
@staticmethod
def concat(tensors, axis=0):
tensors = tuple(tensors)
cuts = np.cumsum([t.data.shape[axis] for t in tensors])[:-1]
out = Tensor(np.concatenate([t.data for t in tensors], axis=axis), tensors)
def backward():
for tensor, g in zip(tensors, np.split(out.grad, cuts, axis=axis)):
tensor.grad += g
out._backward = backward
return out
def backward(self, seed=None):
if seed is None:
if self.data.size != 1: raise ValueError('salida no escalar: proporciona semilla')
seed = np.ones_like(self.data)
seed = np.asarray(seed, dtype=float)
if seed.shape != self.data.shape: raise ValueError('forma de semilla incorrecta')
topo, seen, stack = [], set(), [(self, False)]
while stack:
node, done = stack.pop()
if done: topo.append(node)
elif node not in seen:
seen.add(node)
stack.append((node, True))
stack.extend((p, False) for p in reversed(node.parents))
for node in topo:
if node.parents: node.grad.fill(0)
self.grad += seed
for node in reversed(topo): node._backward()
return len(topo)
def cross_entropy(logits, labels):
z = logits.data.copy()
labels = np.asarray(labels)
if (z.ndim != 2 or z.shape[0] == 0 or z.shape[1] == 0 or
labels.ndim != 1 or labels.shape[0] != z.shape[0] or
not np.issubdtype(labels.dtype, np.integer) or
np.any(labels < 0) or np.any(labels >= z.shape[1])):
raise ValueError('formas o etiquetas incorrectas')
shifted = z - np.max(z, axis=1, keepdims=True)
exp = np.exp(shifted)
probabilities = exp/exp.sum(axis=1, keepdims=True)
loss = np.mean(np.log(exp.sum(axis=1))-shifted[np.arange(len(labels)), labels])
delta = probabilities.copy()
delta[np.arange(len(labels)), labels] -= 1
delta /= len(labels)
out = Tensor(loss, (logits,))
out._backward = lambda: logits._accumulate(out.grad*delta)
return outfrom sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import math
features, labels = load_digits(return_X_y=True)
X_all = features/16.0
train_index, valid_index = train_test_split(np.arange(len(labels)), test_size=0.2,
stratify=labels, random_state=42)
X_train, y_train = X_all[train_index], labels[train_index]
init = np.random.default_rng(123)
initial = [init.normal(0, np.sqrt(2/64), (64, 16)), np.zeros(16),
init.normal(0, np.sqrt(2/16), (16, 10)), np.zeros(10)]
def warmup(step, steps):
if steps < 0: raise ValueError('warmup no negativo')
return 1.0 if steps == 0 else min(1.0, (step+1)/steps)
def cosine_schedule(step, total, warm, peak, minimum=0.0):
if total <= warm or warm < 0 or not 0 <= step < total:
raise ValueError('calendario inválido')
if step < warm: return peak*warmup(step, warm)
if total-warm == 1: return minimum
position = (step-warm)/max(1, total-warm-1)
return minimum + (peak-minimum)*(1+math.cos(math.pi*position))/2
def wsd_schedule(step, total, warm, decay, peak, minimum=0.0):
if warm < 0 or decay < 1 or warm+decay > total or not 0 <= step < total:
raise ValueError('calendario inválido')
if step < warm: return peak*warmup(step, warm)
if step < total-decay: return peak
return minimum+(peak-minimum)*(total-1-step)/max(1, decay-1)
def one_cycle(step, total, rise, peak, minimum=0.0):
if rise < 1 or total <= rise or not 0 <= step < total:
raise ValueError('calendario inválido')
if step < rise: return peak*(step+1)/rise
return minimum+(peak-minimum)*(total-1-step)/max(1, total-rise-1)
class ScratchAdam:
def __init__(self, values, beta1=0.9, beta2=0.999, epsilon=1e-8):
self.p = [Tensor(a.copy()) for a in values]
self.m = [np.zeros_like(x.data) for x in self.p]
self.v = [np.zeros_like(x.data) for x in self.p]
self.t = 0; self.beta1 = beta1; self.beta2 = beta2; self.epsilon = epsilon
def forward(self, x):
return (Tensor(x) @ self.p[0] + self.p[1]).relu() @ self.p[2] + self.p[3]
def update(self, x, y, lr):
for p in self.p: p.grad.fill(0)
loss = cross_entropy(self.forward(x), y)
loss.backward()
self.t += 1
squared = 0.0
for p, m, v in zip(self.p, self.m, self.v):
m *= self.beta1; m += (1-self.beta1)*p.grad
v *= self.beta2; v += (1-self.beta2)*p.grad**2
step = lr*(m/(1-self.beta1**self.t))/(np.sqrt(v/(1-self.beta2**self.t))+self.epsilon)
squared += float(np.sum(step*step))
p.data -= step
return float(loss.data), math.sqrt(squared)
def batches(steps, seed=89, batch=64):
generator = np.random.default_rng(seed)
return [generator.integers(0, len(y_train), size=batch) for _ in range(steps)]
def lr_range(steps=120):
model = ScratchAdam(initial)
rates = np.geomspace(1e-5, 1.0, steps)
rows = []
for index, lr in zip(batches(steps), rates):
loss, norm = model.update(X_train[index], y_train[index], float(lr))
if not np.isfinite(loss) or not np.isfinite(norm): break
rows.append((float(lr), loss, norm))
return np.array(rows)
def run_warmup(warm, peak=0.02, steps=150):
model = ScratchAdam(initial)
rows = []
for i, index in enumerate(batches(steps)):
lr = peak*warmup(i, warm)
loss, norm = model.update(X_train[index], y_train[index], lr)
rows.append((loss, norm, lr))
return np.array(rows)
def compare_schedules(steps=150, peak=0.02):
schedules = {
'coseno': lambda i: cosine_schedule(i, steps, 10, peak),
'one-cycle': lambda i: one_cycle(i, steps, 10, peak),
'WSD': lambda i: wsd_schedule(i, steps, 10, 30, peak),
}
for name, schedule in schedules.items():
model = ScratchAdam(initial)
for i, index in enumerate(batches(steps)):
model.update(X_train[index], y_train[index], schedule(i))
scores = model.forward(X_all[valid_index]).data
valid_loss = float(cross_entropy(Tensor(scores), labels[valid_index]).data)
accuracy = float(np.mean(np.argmax(scores, axis=1) == labels[valid_index]))
print('calendario, pérdida y exactitud en validación', name, valid_loss, accuracy)
def compare_range_choices(rate, steps=150):
for factor in (1/3, 1, 3):
model = ScratchAdam(initial)
valid = True
for index in batches(steps):
loss, norm = model.update(X_train[index], y_train[index], rate*factor)
if not np.isfinite(loss) or not np.isfinite(norm):
valid = False
break
if not valid:
print('factor, carrera no finita', factor)
continue
scores = model.forward(X_all[valid_index]).data
print('factor, tasa, pérdida validación', factor, rate*factor,
float(cross_entropy(Tensor(scores), labels[valid_index]).data))
print('warmup', [warmup(i, 4) for i in range(5)])
print('coseno', [round(cosine_schedule(i, 8, 2, 0.1), 5) for i in range(8)])
print('WSD', [round(wsd_schedule(i, 8, 2, 3, 0.1), 5) for i in range(8)])
range_rows = lr_range()
if len(range_rows) == 0:
raise RuntimeError('El barrido no produjo ningún punto finito')
best = int(np.argmin(range_rows[:, 1]))
print('range: puntos, menor pérdida, tasa en mínimo', len(range_rows), range_rows[best, 1], range_rows[best, 0])
for warm in (0, 10, 50):
track = run_warmup(warm)
print('warmup, primer salto, pérdida inicial y final, salto máximo', warm,
track[0, 1], track[0, 0], track[-1, 0], np.max(track[:, 1]))
compare_schedules()
# Regla exploratoria: veinte puntos antes del mínimo, no una garantía de óptimo.
compare_range_choices(float(range_rows[max(0, best-20), 0]))With these seeds and 150 steps, schedules compare the same peak, not the same sum of rates: WSD remains longer on the plateau. A different effect can arise from that difference as well as schedule shape. The warmup test shares batches and starts with the same Adam state; the final loss is that of its last minibatch, not independent validation.
Reproducing the warmup figure
The figure stores nine 500-step runs with the same initialization and batches. The next cell requires PyTorch and scikit-learn locally. Diagnostic loss uses fixed training examples and is not interpreted as test. The code retains the residual of each curvature measurement and saves JSON in the working directory or ORYON_WARMUP_OUTPUT.
"""Experimento corto reproducible de Adam y warmup sobre load_digits.
El archivo de salida se puede configurar con ORYON_WARMUP_OUTPUT. No necesita
ficheros previos.
"""
import json
import os
from pathlib import Path
import numpy as np
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.set_num_threads(1)
torch.manual_seed(121)
torch.cuda.manual_seed_all(121)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.use_deterministic_algorithms(True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
data, targets = load_digits(return_X_y=True)
train_ids, test_ids = train_test_split(np.arange(len(targets)), test_size=.2, stratify=targets, random_state=122)
x = torch.tensor(data[train_ids] / 16, dtype=torch.float32, device=device)
y = torch.tensor(targets[train_ids], dtype=torch.long, device=device)
probe_x, probe_y = x[:128], y[:128]
def make_model():
return nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10)).to(device)
initial = make_model().state_dict()
initial = {key: value.detach().clone() for key, value in initial.items()}
random = np.random.default_rng(123)
indices = np.stack([random.integers(0, len(x), size=32) for _ in range(500)])
vector_rng = torch.Generator().manual_seed(124)
vector = torch.randn(sum(t.numel() for t in initial.values()), generator=vector_rng, dtype=torch.float32).to(device)
vector /= vector.norm()
def curvature(model):
"""Cociente de Rayleigh tras cinco iteraciones HVP; no garantiza el mayor autovalor algebraico."""
params = tuple(model.parameters())
loss = nn.functional.cross_entropy(model(probe_x), probe_y)
first = torch.autograd.grad(loss, params, create_graph=True)
v = vector
for _ in range(5):
product = sum((g.reshape(-1) * z).sum() for g, z in zip(first, v.split([p.numel() for p in params])))
hv = torch.cat([t.reshape(-1) for t in torch.autograd.grad(product, params, retain_graph=True)])
size = hv.norm()
if size < 1e-20: return 0.0, 0.0
v = hv / size
product = sum((g.reshape(-1) * z).sum() for g, z in zip(first, v.split([p.numel() for p in params])))
hv = torch.cat([t.reshape(-1) for t in torch.autograd.grad(product, params)])
rayleigh = (v * hv).sum()
residual = (hv - rayleigh * v).norm() / hv.norm().clamp_min(1e-20)
return float(rayleigh.detach()), float(residual.detach())
records = []
for peak in (0.003, 0.01, 0.03):
for warmup in (0, 25, 100):
model = make_model()
model.load_state_dict(initial)
optimizer = torch.optim.Adam(model.parameters(), lr=peak)
with torch.no_grad(): initial_loss = float(nn.functional.cross_entropy(model(probe_x), probe_y))
initial_curvature, initial_residual = curvature(model)
points = [{'step': 0, 'loss': initial_loss, 'lr': 0., 'update_norm': 0.,
'curvature': initial_curvature, 'curvature_residual': initial_residual}]
for step in range(1, 501):
lr = peak * min(step / warmup, 1.) if warmup else peak
optimizer.param_groups[0]['lr'] = lr
ids = torch.as_tensor(indices[step-1], dtype=torch.long, device=device)
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(x[ids]), y[ids])
loss.backward()
before = [p.detach().clone() for p in model.parameters()]
optimizer.step()
update_norm = torch.sqrt(sum((p.detach()-q).square().sum() for p,q in zip(model.parameters(), before)))
if step % 5 == 0 or step == 1:
with torch.no_grad(): diagnostic_loss = float(nn.functional.cross_entropy(model(probe_x), probe_y))
estimate, residual = curvature(model) if step % 10 == 0 else (None, None)
points.append({'step': step, 'loss': diagnostic_loss, 'lr': lr, 'update_norm': float(update_norm),
'curvature': estimate, 'curvature_residual': residual})
records.append({'peak': peak, 'warmup': warmup, 'points': points})
print('pico', peak, 'warmup', warmup, 'pérdida inicial', points[0]['loss'],
'primer paso', points[1]['loss'], 'final', points[-1]['loss'],
'primera norma de actualización', points[1]['update_norm'], flush=True)
del optimizer, model, before, update_norm, loss, ids
result = {
'dataset': 'sklearn.datasets.load_digits; partición estratificada 80/20, semilla 122',
'architecture': [64, 32, 10], 'activation': 'ReLU', 'optimizer': 'Adam con beta=(0.9,0.999), eps=1e-8',
'train_batch': 32, 'probe': '128 ejemplos fijos de entrenamiento',
'seeds': {'model': 121, 'split': 122, 'minibatch': 123, 'hvp_vector': 124},
'curvature': 'cociente de Rayleigh de Hessiano sobre lote diagnóstico tras cinco iteraciones HVP con vector inicial fijo; no garantiza el máximo algebraico',
'device': str(device), 'records': records,
}
target = Path(os.environ.get('ORYON_WARMUP_OUTPUT', 'warmup-measure.json'))
target.write_text(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False), encoding='utf-8')
print('resultado:', target, 'dispositivo:', device, flush=True)
del x, y, probe_x, probe_y, vector, initial
if device.type == 'cuda': torch.cuda.empty_cache()npm run lab and open the connection link.Local lab: SGD versus AdamW
On Fashion-MNIST, the following sweep uses a network with normalization, groups parameters, and handles shared weights explicitly. Keep the same seeds and number of runs per optimizer. Select using validation; consult the official test set after selection. The short run used to check the lesson does not replace the full sweep you run.
The short check uses one seed, 4096 training examples, and three epochs. In that run, the SGD selection reaches 0.8145 validation accuracy and AdamW 0.8281; their test-subset evaluations are 0.8096 and 0.8262. These are results of this small test, not a general conclusion about optimizers. The maps show validation and a constant contour: look for whether observed values align without assuming they must. In SGD with momentum, decay contributes to the accumulator, so that curve does not even preserve the same decoupled factor as in AdamW.
"""Comparación emparejada de SGD y AdamW en Fashion-MNIST.
ORYON_VERIFY_SHORT=1 ejecuta una verificación pequeña. ORYON_OPT_OUTPUT
permite elegir la ruta del JSON; por defecto se escribe en el directorio actual.
Las cifras del barrido pequeño no son resultados del barrido completo.
"""
import gc
import json
import math
import os
import time
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
torch.backends.cuda.matmul.allow_tf32 = False
if not torch.cuda.is_available():
raise RuntimeError('Se necesita CUDA para este experimento.')
device = torch.device('cuda')
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
def parameter_groups(model, weight_decay):
"""Deduplica por identidad y rechaza alias con políticas de decay opuestas."""
norm_types = (nn.LayerNorm, nn.GroupNorm, nn.modules.batchnorm._BatchNorm,
nn.modules.instancenorm._InstanceNorm)
seen, ordered = {}, []
for module_name, module in model.named_modules(remove_duplicate=False):
for local_name, parameter in module._parameters.items():
if parameter is None or not parameter.requires_grad:
continue
name = (module_name + '.' if module_name else '') + local_name
exclude = (local_name == 'bias' or parameter.ndim <= 1 or
isinstance(module, (nn.Embedding, nn.EmbeddingBag, *norm_types)))
key = id(parameter)
if key in seen:
if seen[key]['exclude'] != exclude:
raise ValueError('Políticas de decay incompatibles para el parámetro compartido: '
+ seen[key]['names'][0] + ' y ' + name)
seen[key]['names'].append(name)
else:
record = {'parameter': parameter, 'exclude': exclude, 'names': [name]}
seen[key] = record
ordered.append(record)
with_decay = [r['parameter'] for r in ordered if not r['exclude']]
no_decay = [r['parameter'] for r in ordered if r['exclude']]
groups = [{'params': with_decay, 'weight_decay': weight_decay},
{'params': no_decay, 'weight_decay': 0.0}]
description = [{'names': r['names'], 'shape': list(r['parameter'].shape),
'weight_decay': 0.0 if r['exclude'] else weight_decay}
for r in ordered]
return groups, description
def check_aliases():
class Shared(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Linear(3, 3, bias=False)
self.b = nn.Linear(3, 3, bias=False)
self.b.weight = self.a.weight
class Conflicting(nn.Module):
def __init__(self):
super().__init__()
self.embed = nn.Embedding(4, 3)
self.output = nn.Linear(3, 4, bias=False)
self.output.weight = self.embed.weight
groups, description = parameter_groups(Shared(), .01)
assert sum(len(g['params']) for g in groups) == 1
assert len(description[0]['names']) == 2
try:
parameter_groups(Conflicting(), .01)
except ValueError as error:
print('Prueba de conflicto detectado:', error, flush=True)
else:
raise AssertionError('Un peso compartido entre embedding y lineal debe señalar el conflicto.')
def build_model(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
return nn.Sequential(nn.Linear(784, 128), nn.LayerNorm(128), nn.ReLU(),
nn.Linear(128, 10)).to(device)
def evaluate(model, x, y):
model.eval()
n, total_loss, correct = len(y), 0., 0
with torch.no_grad():
for xb, yb in zip(x.split(512), y.split(512)):
logits = model(xb)
total_loss += float(nn.functional.cross_entropy(logits, yb, reduction='sum'))
correct += int((logits.argmax(dim=1) == yb).sum())
return {'loss': total_loss/n, 'accuracy': correct/n}
check_aliases()
FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
root = Path.home()/'.cache'/'atlas-data'
training = FashionMNIST(root, train=True, download=True)
test = FashionMNIST(root, train=False, download=True)
split = torch.randperm(len(training), generator=torch.Generator().manual_seed(101))
n_train, n_val, n_test = (4096, 1024, 1024) if short else (50000, 10000, 10000)
train_ids, val_ids = split[:n_train], split[n_train:n_train+n_val]
def on_device(dataset, indices):
x = dataset.data[indices].to(device=device, dtype=torch.float32).reshape(-1, 784)/255
y = dataset.targets[indices].to(device=device)
return x, y
X_train, y_train = on_device(training, train_ids)
X_val, y_val = on_device(training, val_ids)
# Test permanece en CPU y se transfiere solo después de seleccionar por validación.
test_ids = torch.arange(n_test)
batch_size, epochs = 128, (3 if short else 10)
seeds = [7] if short else [7, 11]
grid = {'SGD': [.01, .05, .1], 'AdamW': [.0003, .001, .003]}
decays = [.0001, .001, .01]
print('Dispositivo:', torch.cuda.get_device_name(device), 'modo corto:', short, flush=True)
print('Mismo presupuesto por configuración:', epochs, 'épocas, lote', batch_size,
'semillas', seeds, 'configuraciones por optimizador', len(grid['SGD'])*len(decays), flush=True)
def train_one(kind, lr, decay, seed):
model = build_model(seed)
groups, description = parameter_groups(model, decay)
if kind == 'SGD':
optimizer = torch.optim.SGD(groups, lr=lr, momentum=.9)
else:
optimizer = torch.optim.AdamW(groups, lr=lr)
shuffle = torch.Generator().manual_seed(1000 + seed)
history, steps, examples = [], 0, 0
torch.cuda.synchronize(device)
start = time.perf_counter()
valid = True
for epoch in range(epochs):
model.train()
order = torch.randperm(n_train, generator=shuffle)
for ids in order.split(batch_size):
ids = ids.to(device)
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(X_train[ids]), y_train[ids])
if not bool(torch.isfinite(loss)):
valid = False
break
loss.backward()
optimizer.step()
steps += 1
examples += len(ids)
if not valid:
break
metrics = evaluate(model, X_val, y_val)
if not all(math.isfinite(v) for v in metrics.values()):
valid = False
break
history.append({'epoch': epoch+1, 'steps': steps, 'examples': examples, **metrics})
torch.cuda.synchronize(device)
seconds = time.perf_counter()-start
record = {'optimizer': kind, 'lr': lr, 'weight_decay': decay, 'seed': seed, 'valid': valid,
'steps': steps, 'examples': examples, 'history': history,
'seconds_with_validation': seconds}
print(json.dumps(record, ensure_ascii=False), flush=True)
state = {name: tensor.detach().cpu().clone() for name, tensor in model.state_dict().items()} if valid else None
del model, optimizer, loss
gc.collect()
torch.cuda.empty_cache()
return record, state, description
records, saved = [], {}
group_description = None
for kind, rates in grid.items():
for lr in rates:
for decay in decays:
for seed in seeds:
record, state, group_description = train_one(kind, lr, decay, seed)
records.append(record)
saved[(kind, lr, decay, seed)] = state
winners = {}
for kind, rates in grid.items():
candidates = []
for lr in rates:
for decay in decays:
rows = [r for r in records if r['optimizer'] == kind and r['lr'] == lr and r['weight_decay'] == decay]
if len(rows) == len(seeds) and all(r['valid'] for r in rows):
score = sum(r['history'][-1]['accuracy'] for r in rows)/len(rows)
candidates.append((score, lr, decay))
if candidates:
# Desempate determinista por tasa y después por decay menores.
score, lr, decay = sorted(candidates, key=lambda item: (-item[0], item[1], item[2]))[0]
winners[kind] = {'lr': lr, 'weight_decay': decay, 'mean_validation_accuracy': score, 'test': []}
if winners:
X_test, y_test = on_device(test, test_ids)
for kind, choice in winners.items():
for seed in seeds:
model = build_model(seed)
model.load_state_dict(saved[(kind, choice['lr'], choice['weight_decay'], seed)])
choice['test'].append({'seed': seed, **evaluate(model, X_test, y_test)})
del model
del X_test, y_test
output = {'dataset': 'Fashion-MNIST', 'short': short, 'device': torch.cuda.get_device_name(device),
'train': n_train, 'validation': n_val, 'test_official': n_test,
'split_seed': 101, 'seeds': seeds, 'batch': batch_size, 'epochs': epochs,
'grid_lr': grid, 'grid_weight_decay': decays, 'parameter_groups_example': group_description,
'selection': 'media de precisión de validación al final; desempate por tasa y decay menores',
'records': records, 'selected_test': winners}
path = Path(os.environ.get('ORYON_OPT_OUTPUT', 'fashion-optimizer-sweep.json'))
path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
def log_edges(values):
centers = np.log10(values)
middle = (centers[:-1]+centers[1:])/2
return 10**np.r_[centers[0]-(middle[0]-centers[0]), middle,
centers[-1]+(centers[-1]-middle[-1])]
fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True)
measured_scores = [r['history'][-1]['accuracy'] for r in records if r['valid'] and r['history']]
vmin = min(measured_scores, default=0.)
vmax = max(measured_scores, default=1.)
if vmax == vmin:
vmin, vmax = max(0., vmin-.01), min(1., vmax+.01)
for ax, (kind, rates) in zip(axes, grid.items()):
values = np.full((len(rates), len(decays)), np.nan)
for i, lr in enumerate(rates):
for j, decay in enumerate(decays):
rows = [r for r in records if r['optimizer'] == kind and r['lr'] == lr and r['weight_decay'] == decay]
if len(rows) == len(seeds) and all(r['valid'] for r in rows):
values[i, j] = sum(r['history'][-1]['accuracy'] for r in rows)/len(rows)
mesh = ax.pcolormesh(log_edges(decays), log_edges(rates), values, vmin=vmin, vmax=vmax, cmap='viridis')
for i, lr in enumerate(rates):
for j, decay in enumerate(decays):
label = 'no finito' if np.isnan(values[i, j]) else f'{values[i, j]:.3f}'
text_color = 'black' if np.isnan(values[i, j]) else ('white' if values[i, j] < (vmin+vmax)/2 else 'black')
ax.text(decay, lr, label, color=text_color, ha='center', va='center', fontsize=8)
# Una isocurva ilustrativa: no implica equivalencia de trayectorias ni de precisión.
product = math.sqrt(min(rates)*min(decays)*max(rates)*max(decays))
xs = np.geomspace(min(decays), max(decays), 200)
ys = product/xs
valid = (ys >= min(rates)) & (ys <= max(rates))
ax.plot(xs[valid], ys[valid], '--', color='black', linewidth=1,
label='eta·lambda constante')
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xticks(decays, [str(v) for v in decays])
ax.set_yticks(rates, [str(v) for v in rates])
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax.set_xlabel('weight decay λ')
ax.set_ylabel('tasa η')
ax.set_title(kind + ': precisión de validación')
ax.legend(loc='lower left', fontsize=7)
fig.colorbar(mesh, ax=axes, label='Precisión media de validación', shrink=.8)
figure = path.with_suffix('.png')
fig.savefig(figure, dpi=150)
plt.close(fig)
print('Selección por validación y test reservado:', json.dumps(winners, ensure_ascii=False), flush=True)
print('Resultado guardado en', path, flush=True)
print('Mapas de validación guardados en', figure, flush=True)
del X_train, y_train, X_val, y_val, saved
torch.cuda.empty_cache()npm run lab and open the connection link.To explore the frontier, also try training without a schedule and parameterization-dependent rates, studied in the μP lesson. Compare using declared budgets and splits: a recipe does not replace diagnosis.
Exercises
def make_param_groups(model, wd):
passStep 1 of 3. What expression results after two steps?