Diagnostics I: reading learning curves and the training recipe
Diagnose training by checking initial loss and small-batch overfitting, interpreting learning curves, investigating label noise, and comparing changes under a documented incremental recipe.
After this lesson you can
- Predict initial loss and check whether a small batch can be overfit before large training runs.
- Recognize learning-curve patterns and test plausible causes with controls.
- Examine memorization of noisy labels alongside clean validation.
- Follow an incremental training recipe from baseline to complete model.
- Compare differences between curves with variability across seeds.
Before you start
A curve is a clue
A network can train without exceptions while optimizing the wrong task. It may receive misaligned labels, accidentally share examples across splits, or evaluate with dropout active. Learning-curve patterns are clues, but loss alone does not identify a cause. Good curve reading proposes hypotheses and tests them with interventions changing one thing at a time.
Before spending the budget
Inspect images, labels, and units; split data by the relevant entity and check duplicates. Record a trivial baseline, for example always predicting the most frequent class. Fit data preparation on training data, then apply it to validation and test without using those sets to calculate means, variances, or feature selection.
With equal logits, softmax assigns to each class and initial cross-entropy is . For 100 classes this is approximately 4.60517. In binary classification, a single initial zero logit implies probability 0.5 and loss , even if positive prevalence is 0.1. If bias is initialized to , expected loss of the constant predictor under that prior is . These references are no longer exact if logits differ, class weights are used, or evaluation prior differs.
Next try to overfit a small batch: disable augmentation and regularization, check labels match inputs, and inspect forward pass, gradients, and updates. If loss cannot decrease, check wiring, optimizer, and capacity before launching large training. Succeeding does not prove generalization.
Finding causes with controls
| Observed pattern | Hypothesis worth testing | Control or intervention |
|---|---|---|
| Loss oscillates, rises, or becomes non-finite | Rate too high, abnormal scale or gradients | Reduce only rate and check norms and finiteness |
| Training and validation barely improve | Small rate, capacity, data, or bug | Overfit a batch and sweep rate |
| Training improves and validation worsens | Overfitting or distribution shift | Check splits, checkpoint, and regularization |
| Surprisingly good validation | Leakage, duplicates, or sample differences | Audit identities and refit preparation on train only |
| Metrics change with batch size or companions | Evaluation in train mode or statistic dependence | Repeat in eval and preserve BN buffers |
These patterns can have alternative causes. A high rate does not always explode; a flat curve can reflect label errors or a small rate; and validation loss better than training can be legitimate with augmentation or dropout. Compare metrics under the same mode and distribution before calling a gap leakage.
The local clinic below separately injects six faults into Fashion-MNIST: excessive rate, altered labels, overlap, evaluation in train mode, evaluation statistics used in preprocessing, and unshuffled order. Each run saves its intervention and controls. The split called “simulated test” is diagnostic: never use official test data to choose the protocol. If an intervention does not produce a striking shape, the result remains valid and is not replaced by an invented curve.
Corrupted labels and memorization
Arpit and colleagues studied MNIST and CIFAR-10, comparing real data and labels with random variants. To analyze easy examples, they trained from 100 different initializations and orders for one epoch and measured errors on 1000 examples; results suggest a tendency to learn shared patterns before memorizing noise, not a law for every network.
In this lesson’s reproducible experiment, an MLP trained on 240 load_digits examples with 40% altered labels reaches validation accuracy 0.7611 at step 175 and ends at 0.6778 at step 600. At the final step it correctly classifies 0.9792 of clean examples and matches 0.5208 of corrupted labels received. We also measure accuracy against those same examples’ original labels: matching altered labels and recovering true labels are different questions. The validation maximum is selected retrospectively and its checkpoint restored; it is not an independent test or a guarantee that a particular patience would find it.
What smoothing hides
An exponential average with responds more slowly to an event. In the cell’s synthetic signal, the jump between steps 74 and 75 goes from 0.80145 in the raw curve to 0.00892 with . That does not prove the event disappeared from training. A logarithmic scale requires positive values and changes representation, not data; it can make small improvements visible after loss has already fallen substantially.
Accuracy can also stay unchanged while cross-entropy improves or worsens: it depends on assigned confidence, not only the winning class. Group by steps or examples, mark epoch boundaries, and check whether jumps coincide with shuffling, rate changes, or evaluation. Save raw observations and show smoothing as an additional view.
Typical overfitting is not an irreversible law either. In a modular division experiment, Power and colleagues show near-perfect training before steps and near-perfect validation around ; validation improves much later. Their small algorithmic tasks illustrate grokking; they do not guarantee extending any training run will fix overfitting.
How far apart are seeds?
A single run cannot distinguish improvement from initialization or batch-order noise. Repeat with declared seeds and splits; if seeds are paired, calculate the spread of paired differences. If samples are independent, estimated standard error of the difference in means is
With five seeds per configuration and standard deviations of 0.4 and 0.5 percentage points, this gives 0.28636 points. A difference of 0.4 points gives an approximate 95% normal interval of [−0.1613; 0.9613] points, including zero. With five observations the normal approximation is fragile: the Welch interval computed in the cell is wider. Neither proves configurations are identical. If runs are paired, covariance or individual differences are needed for the correct error.
An incremental recipe
The systematic training recipe starts by understanding data and getting a small version working before adding complexity, as Karpathy proposes. The tuning playbook emphasizes recording conditions and systematic comparison. A practical sequence is:
- Inspect data, splits, labels, and baseline; record seeds and versions.
- Check initial loss, gradients, and that a small batch can be overfit.
- Establish a baseline without additional interventions and measure train and validation consistently.
- Change one variable, keep the budget, and record the result and uncertainty across seeds.
- Only then add regularization, augmentation, or architecture and run ablations. Reserve test for the already selected protocol.
Labs
The first cell reproduces numerical figures and the synthetic smoothing case. It is followed by the current tensor engine and a real experiment with altered labels. The third, local lab trains the gallery runs with a short check and a full budget for the reader.
"""Curva sintética declarada: EMA causal y transformación logarítmica."""
import json
from pathlib import Path
import numpy as np
from scipy.stats import t
rng = np.random.default_rng(1818)
steps = np.arange(201)
base = .04 + np.exp(-steps/35)
noise = rng.normal(0,.012,size=len(steps))
raw = np.maximum(.005,base+noise)
raw[75] += .8
def ema(values, beta):
if not 0 <= beta < 1: raise ValueError('0 ≤ β < 1')
result = np.empty_like(values)
result[0] = values[0]
for i in range(1,len(values)): result[i] = beta*result[i-1]+(1-beta)*values[i]
return result
records=[]
for beta in (0.,.5,.9,.98):
curve=ema(raw,beta)
assert np.all(np.isfinite(curve)) and np.all(curve>0)
records.append({'beta':beta,'values':curve.tolist()})
print('beta',beta,'pico visible',curve[75], 'variación al pico',curve[75]-curve[74])
assert np.array_equal(ema(raw,0),raw)
assert abs(ema(raw,.98)[75]-ema(raw,.98)[74]) < abs(raw[75]-raw[74])
se = np.sqrt((.4**2+.5**2)/5)
df = ((.4**2/5+.5**2/5)**2)/((.4**2/5)**2/4+(.5**2/5)**2/4)
print('Pérdidas ln(100), ln(2), entropía prior 0,1:',np.log(100),np.log(2),-(.1*np.log(.1)+.9*np.log(.9)))
print('SE en puntos:',se,'intervalo normal:',.4-1.96*se,.4+1.96*se,
'Welch:',.4-t.ppf(.975,df)*se,.4+t.ppf(.975,df)*se,'gl:',df)
output={'model':'0,04+exp(−paso/35)+ruido normal(0;0,012), recortado a 0,005; '
'se suma 0,8 en el paso 75', 'seed':1818,'steps':steps.tolist(),
'raw':raw.tolist(),'peak_step':75,'records':records}
destination=Path(__file__).with_suffix('.json') if '__file__' in globals() else Path('smoothing.json')
destination.write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf-8')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 out"""Memorización de etiquetas corruptas en load_digits con Tensor de m15-l09.
Las fracciones seleccionan ejemplos de un mismo orden aleatorio y se garantiza
que toda etiqueta elegida cambie. Validación limpia y disjunta; una semilla.
"""
import json
from pathlib import Path
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
data, true_labels = load_digits(return_X_y=True)
data = data/16.
pool, valid_ids = train_test_split(np.arange(len(true_labels)), test_size=.2,
stratify=true_labels, random_state=1801)
train_ids, _ = train_test_split(pool, train_size=240, stratify=true_labels[pool], random_state=1802)
x_train, clean_y = data[train_ids], true_labels[train_ids]
x_valid, valid_y = data[valid_ids], true_labels[valid_ids]
assert not np.intersect1d(train_ids,valid_ids).size
permutation = np.random.default_rng(1803).permutation(len(train_ids))
shifts = np.random.default_rng(1804).integers(1,10,size=len(train_ids))
def corrupt(fraction):
if fraction not in (0.,.2,.4,.6): raise ValueError('fracción no preparada')
count = int(round(fraction*len(train_ids)))
mask = np.zeros(len(train_ids),dtype=bool)
mask[permutation[:count]] = True
observed = clean_y.copy()
observed[mask] = (observed[mask]+shifts[mask])%10
assert np.array_equal(mask,observed!=clean_y)
return observed,mask
class Network:
def __init__(self):
init = np.random.default_rng(1805)
dims = [64,48,48,10]
self.weights = [Tensor(init.normal(0,np.sqrt(2/a),(a,b))) for a,b in zip(dims[:-1],dims[1:])]
self.biases = [Tensor(np.zeros(b)) for b in dims[1:]]
self.params = self.weights+self.biases
def __call__(self,x):
h = Tensor(x)
for w,b in zip(self.weights[:-1],self.biases[:-1]): h = (h@w+b).relu()
return [email protected][-1]+self.biases[-1]
def train_noise(fraction,steps=600,interval=25,lr=.1):
observed,mask = corrupt(fraction)
net = Network()
generator = np.random.default_rng(1806)
history = []
best_accuracy, best_snapshot = -1., None
for step in range(steps+1):
if step % interval == 0 or step == steps:
pred = net(x_train).data.argmax(axis=1)
valid = net(x_valid).data
row = {'step':step,
'clean_accuracy':float(np.mean(pred[~mask]==clean_y[~mask])) if (~mask).any() else None,
'corrupt_observed_accuracy':float(np.mean(pred[mask]==observed[mask])) if mask.any() else None,
'corrupt_true_accuracy':float(np.mean(pred[mask]==clean_y[mask])) if mask.any() else None,
'validation_accuracy':float(np.mean(valid.argmax(axis=1)==valid_y)),
'validation_loss':float(cross_entropy(Tensor(valid),valid_y).data)}
history.append(row)
if row['validation_accuracy'] > best_accuracy:
best_accuracy = row['validation_accuracy']
best_snapshot = [parameter.data.copy() for parameter in net.params]
if step == steps: break
ids = generator.integers(0,len(train_ids),size=32)
for p in net.params: p.grad.fill(0)
loss = cross_entropy(net(x_train[ids]),observed[ids])
if not np.isfinite(loss.data): raise RuntimeError('pérdida no finita')
loss.backward()
if any(not np.isfinite(p.grad).all() for p in net.params): raise RuntimeError('gradiente no finito')
for p in net.params: p.data -= lr*p.grad
best = max(history,key=lambda row:row['validation_accuracy'])
for parameter,saved in zip(net.params,best_snapshot): parameter.data[:] = saved
restored = net(x_valid).data
restored_accuracy = float(np.mean(restored.argmax(axis=1)==valid_y))
restored_loss = float(cross_entropy(Tensor(restored),valid_y).data)
assert restored_accuracy == best['validation_accuracy'] and abs(restored_loss-best['validation_loss']) < 1e-12
return {'fraction':fraction,'seed':1805,'steps':steps,'history':history,
'best_validation_step':best['step'],'best_validation_accuracy':best['validation_accuracy'],
'restored_validation_loss':restored_loss}
def save_results(records):
output = {'dataset':'sklearn load_digits','train_examples':len(train_ids),'validation_examples':len(valid_ids),
'steps':records[0]['steps'],'interval':25,'split_seed':1801,'sample_seed':1802,
'notes':'Precisión corrupta frente a etiqueta observada, con curva adicional de etiqueta original; '
'mejor validación elegido retrospectivamente, primera ocurrencia de un empate.',
'records':records}
path = Path(__file__).with_suffix('.json') if '__file__' in globals() else Path('label-noise.json')
path.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
return output
if __name__ == '__main__':
records = [train_noise(p) for p in (0.,.2,.4,.6)]
save_results(records)
for row in records:
print('ruido',row['fraction'],'mejor',row['best_validation_step'],row['best_validation_accuracy'],
'último',row['history'][-1])"""Clínica reproducible de curvas con seis fallos, Fashion-MNIST.
ORYON_VERIFY_SHORT=1 verifica el flujo con presupuesto pequeño. El test oficial
no se consulta. La supuesta normalización con estadísticas de test se emula
intencionalmente con un conjunto diagnóstico de validación separado de train.
ORYON_CLINIC_OUTPUT permite elegir el JSON; la salida normal es fashion-clinic.json.
"""
import copy
import json
import math
import os
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_size, valid_size = (1024, 512) if short else (5000, 1000)
width = 64 if short else 256
steps, batch_size, every = (160, 64, 20) if short else (2000, 64, 100)
seed = 1818
configs = ['control', 'lr_alto', 'etiquetas_corruptas', 'fuga_ejemplos',
'eval_train', 'estadisticas_validacion', 'sin_barajar']
FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
dataset = FashionMNIST(Path.home()/'.cache'/'atlas-data', train=True, download=True)
split = torch.randperm(len(dataset), generator=torch.Generator().manual_seed(18180))
train_ids, valid_ids = split[:train_size], split[train_size:train_size+valid_size]
assert not set(train_ids.tolist()).intersection(valid_ids.tolist())
train_pixels = dataset.data[train_ids].reshape(train_size, -1).float().div_(255)
valid_pixels = dataset.data[valid_ids].reshape(valid_size, -1).float().div_(255)
train_y, valid_y = dataset.targets[train_ids].to(device), dataset.targets[valid_ids].to(device)
mean, std = train_pixels.mean(), train_pixels.std(unbiased=False)
valid_mean, valid_std = valid_pixels.mean(), valid_pixels.std(unbiased=False)
train_x = ((train_pixels-mean)/(std+1e-6)).to(device)
valid_x = ((valid_pixels-mean)/(std+1e-6)).to(device)
leaky_normalized_x = ((valid_pixels-valid_mean)/(valid_std+1e-6)).to(device)
order = torch.argsort(train_y.cpu(), stable=True)
shuffle = torch.Generator().manual_seed(18181)
random_orders = [torch.randperm(train_size, generator=shuffle) for _ in range((steps*batch_size//train_size)+2)]
random_indices = torch.cat(random_orders)[:steps*batch_size].reshape(steps,batch_size)
ordered_indices = order.repeat((steps*batch_size//train_size)+2)[:steps*batch_size].reshape(steps,batch_size)
corrupt_y = train_y.clone()
noise_generator = torch.Generator().manual_seed(18182)
selected = torch.randperm(train_size, generator=noise_generator)[:int(.4*train_size)]
offsets = torch.randint(1, 10, (len(selected),), generator=noise_generator).to(device)
corrupt_y[selected.to(device)] = (corrupt_y[selected.to(device)]+offsets)%10
assert int((corrupt_y != train_y).sum()) == len(selected)
class Network(nn.Module):
def __init__(self):
super().__init__()
torch.manual_seed(seed)
self.net = nn.Sequential(nn.Linear(784,width),nn.ReLU(),nn.Linear(width,width),
nn.BatchNorm1d(width),nn.ReLU(),nn.Dropout(.25),nn.Linear(width,10))
def forward(self,x): return self.net(x)
@torch.no_grad()
def measure(model, x, y, broken_mode=False, step=0):
# Usar una copia impide que evaluar en train contamine buffers BN del modelo.
probe = copy.deepcopy(model)
probe.train(broken_mode)
count, total = 0, 0.
devices = [torch.cuda.current_device()] if device.type == 'cuda' else []
with torch.random.fork_rng(devices=devices):
torch.manual_seed(seed+100000+step)
for xb,yb in zip(x.split(batch_size),y.split(batch_size)):
z = probe(xb)
if not torch.isfinite(z).all(): return None
total += float(nn.functional.cross_entropy(z,yb,reduction='sum'))
count += int((z.argmax(1)==yb).sum())
return {'loss':total/len(y),'accuracy':count/len(y)}
def run(case):
model = Network().to(device)
if device.type=='cuda': torch.cuda.manual_seed_all(seed)
optimizer = torch.optim.SGD(model.parameters(),lr=5. if case=='lr_alto' else .05)
y_train = corrupt_y if case=='etiquetas_corruptas' else train_y
indices = ordered_indices if case=='sin_barajar' else random_indices
history = []
status = 'complete'
completed = 0
for step in range(steps+1):
if step%every == 0 or step == steps:
tr=measure(model,train_x,y_train,step=step)
clean=measure(model,valid_x,valid_y,step=step)
if case=='fuga_ejemplos':
shown=measure(model,train_x[:valid_size],train_y[:valid_size],step=step)
elif case=='eval_train':
shown=measure(model,valid_x,valid_y,broken_mode=True,step=step)
elif case=='estadisticas_validacion':
shown=measure(model,leaky_normalized_x,valid_y,step=step)
else: shown=clean
if tr is None or clean is None or shown is None:
status='nonfinite_diagnostic'; break
history.append({'step':step,'train':tr,'validation':shown,'clean_validation':clean})
if step==steps: break
model.train()
ids=indices[step].to(device)
optimizer.zero_grad(set_to_none=True)
loss=nn.functional.cross_entropy(model(train_x[ids]),y_train[ids])
if not torch.isfinite(loss): status='nonfinite_loss'; break
loss.backward()
if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
status='nonfinite_gradient'; break
optimizer.step()
completed=step+1
del model,optimizer
return {'id':case,'seed':seed,'status':status,'steps_completed':completed,'history':history}
records=[run(case) for case in configs]
output={'dataset':'Fashion-MNIST train oficial, particiones disjuntas',
'source':'https://github.com/zalandoresearch/fashion-mnist',
'mode':'short' if short else 'full','device':str(device),'torch':torch.__version__,
'train_size':train_size,'validation_size':valid_size,'width':width,'steps':steps,
'batch_size':batch_size,'every':every,'seed':seed,'split_seed':18180,
'train_mean':float(mean),'train_std':float(std),'validation_mean':float(valid_mean),'validation_std':float(valid_std),
'protocol':'Misma inicialización y secuencia de lotes salvo sin_barajar. Evaluación normal en modo eval; eval_train se calcula en una copia en train. El test oficial no se consulta. clean_validation conserva la métrica limpia.',
'cases':{'control':'SGD 0,05 y validación disjunta',
'lr_alto':'SGD 5,0',
'etiquetas_corruptas':'40 % de etiquetas de train sustituidas por otra clase',
'fuga_ejemplos':'validación mostrada sustituida por ejemplos de train',
'eval_train':'evaluación en train, con dropout y BN de lote, en copia aislada',
'estadisticas_validacion':'normalización de validación con sus propias estadísticas, simulando un uso indebido de estadísticas de test',
'sin_barajar':'train ordenado por clase, sin barajar'},'records':records}
target=Path(os.environ.get('ORYON_CLINIC_OUTPUT','fashion-clinic.json'))
target.parent.mkdir(parents=True,exist_ok=True)
target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
fig,axes=plt.subplots(2,4,figsize=(15,7),constrained_layout=True)
for ax,record in zip(axes.flat,records):
rows=record['history']
for key,label in [('train','train observado'),('validation','validación mostrada'),('clean_validation','validación limpia')]:
ax.plot([r['step'] for r in rows],[r[key]['accuracy'] for r in rows],label=label)
ax.set_title(record['id']+' ('+record['status']+')')
ax.set_xlabel('Actualizaciones'); ax.set_ylim(0,1); ax.grid(alpha=.2)
axes.flat[-1].axis('off'); axes.flat[0].legend(fontsize=7)
fig.savefig(target.with_suffix('.png'),dpi=130); plt.close(fig)
for r in records:
print(r['id'],r['status'],'pasos',r['steps_completed'],'última medición',r['history'][-1] if r['history'] else None)
if device.type=='cuda': torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
The following check examines differential dependence on the particular batch: a zero cross-Jacobian at one point does not prove global independence. For example, if example i’s output contains the square of an input of example j, its cross-derivative is zero when that input is zero, even though output depends on it elsewhere. Repeat the test on varied batches and combine it with interventions on batch companions.
import numpy as np
def batch_independence_check(model,x,i,j,tol=1e-10):
pass