Batch normalization
Batch normalization standardizes each channel using minibatch statistics and learns scale and shift. Derive and implement forward and backward passes, examine running statistics and evaluation, and analyze evidence and scale invariance.
After this lesson you can
- Implement batch normalization forward passes for training and evaluation with running statistics.
- Derive and implement the compact backward pass and check it numerically.
- Explain issues from small and non-iid batches and information leakage between examples.
- Analyze scale invariance and its relationship with effective learning rate and weight decay.
- Critically assess proposed explanations for batch normalization's effects.
Before you start
A prediction can depend on its neighbors
A large activation does not tell the whole story: its scale can change during training and a rate that works in one region can fail in another. Moment propagation described initialization; now statistics depend on examples present during training. Batch normalization, or BN, centers and scales each channel using batch statistics during training. It then applies a learnable scale and shift. This is a collective operation: changing other examples can change the output of one you did not modify.
The figure uses explicit 2D points: the first point is an anchor and enabling the outlier adds one element to the batch. Mean and variance are computed per coordinate. This is not a sample from a real population or a training experiment.
Forward pass per channel
For values in one channel, define
Forward variance uses divisor . For , the normalized batch mean is zero but its variance is , not exactly one. If all values coincide, and output is ; a subsequent derivative need not be zero for . For example, the cell below obtains input gradient with and on a constant batch.
For BatchNorm1d applied to a matrix (N,C), each channel aggregates values. For BatchNorm2d with (N,C,H,W), it aggregates : a batch of one image can be valid if there is more than one spatial value per channel. PyTorch rejects in training. The mathematical formula for one value and returns and zero input gradient, but does not provide an unbiased variance estimate to update running state.
A common order is affine layer, BN, then activation. Moving activation before BN changes statistics and the function; they are not interchangeable. For example, in a CNN an Conv2d(3,16,3,padding=1,bias=False) layer followed by BatchNorm2d(16) and ReLU accepts (N,3,28,28) inputs and normalizes each of 16 output channels over values during training. Convolution bias can be omitted in that configuration, subject to the evaluation caveat below.
Backward without treating the mean as constant
The batch normalization backward pass must also differentiate batch statistics. Write and . Perturbing changes the mean by and, since ,
Applying the vector-Jacobian product and grouping terms depending on each gives
Means and sums are over the channel’s values; is shared within it. This is the training derivative for variance with divisor . Do not replace with 1 if : it equals . In evaluation, if running statistics are treated as constant, input gradient is simply . The cell checks this with finite differences in both modes.
Training and evaluation are different operations
Running statistics record a history of batches so evaluation can avoid depending on an example’s companions. In PyTorch, with momentum=m, the update is
and analogously for variance. Here assigns 10% to the new statistic: it is not the coefficient retaining the previous state. PyTorch uses variance with divisor in forward, but updates running_var using the corrected estimator with divisor . With momentum=None it averages batch statistics; that average is not generally global variance because batch means may differ.
model.train() uses batch statistics and updates buffers; model.eval() uses saved buffers without updating them when track_running_stats=True. If tracking is disabled, even eval() uses batch statistics. Evaluating with train() can change predictions and modify buffers; disabling gradients is insufficient. To recalibrate, pass representative training data and state the procedure without using test data to select it.
Small batches produce more variable statistics, but the gap has no fixed sign and is not explained by size alone. Batch examples sharing class, domain, or time can shift statistics; mixing examples that should be independent can also leak information through normalization. Ghost batch norm computes statistics in virtual sub-batches during training, while batch renormalization introduces corrections toward running statistics; both change behavior and must be evaluated on the task. See Hoffer and colleagues and Ioffe.
In the figure’s short run, for seed 31, batch 4, and momentum 0.1, step 120 gives 40.625% in train mode and 54.296875% in eval on the same 256 images. The difference changes under other combinations; these are not independent sets or a generalization comparison. Statistics used in the train diagnostic are restored before continuing.
What evidence do we have for its effect?
Ioffe and Szegedy proposed BN and linked it to changing internal distributions. In their Inception comparison, BN-x5 reaches 72.2% with 14 times fewer steps, after other training modifications were also applied; this is neither a time measurement nor an isolated BN effect. Santurkar and colleagues question whether stabilizing those distributions is the whole explanation and present evidence of a smoother optimization landscape in their experiments. This is a useful framework, not proof of one universal mechanism.
Bjorck and colleagues compare initial rates 0.0001, 0.003, and 0.1 in ResNet-110 over five runs and study the role of a large rate. The comparison changes with architecture, budget, and initialization: do not conclude BN always permits any rate or accelerates every network.
Scale, gradient, and decay
Scale invariance is exact in an ideal case: for , statistics from the same batch, and positive variance, normalizing gives the same output as normalizing . With ,
so equality is only approximate when the stabilizer is small relative to variance. In evaluation with frozen statistics, one also cannot scale input and assume invariance. A linear bias before BN cancels in training when subtracting the same batch mean; with uncalibrated evaluation buffers, that cancellation does not automatically follow.
If a differentiable loss satisfies for every , differentiating with respect to at 1 gives . Also, . With , , the gradient is tangent and its magnitude scales as ; in plain SGD the small angular change is proportional to . This is a property of the homogeneous model, not an exact identity for BN with arbitrary .
In the figure’s model, and . For SGD with coupled decay and ,
If and are frozen, the radius equating both sides satisfies . In a real trajectory changes with direction, so instantaneous equilibrium does not guarantee a constant long-term radius. Momentum, Adam, parameters excluded from decay, and changing statistics need another analysis. van Laarhoven and Kosson and colleagues study the relationship between norm, decay, and angular dynamics under their assumptions.
Lab: the explicit batch
The first figure uses the following point set and its 24 combinations of size, outlier, and ε. Tests check mean, variance, reordering, and a constant channel.
"""Puntos 2D explícitos y BN por canal para un interactivo determinista.
El primer punto es el ancla. El tamaño indica puntos ordinarios; activar el
atípico añade un punto y aumenta el tamaño efectivo en uno. γ=1, β=0.
"""
import json
from pathlib import Path
import numpy as np
POINTS = np.array([
[.3, -.4], [-1.1, .8], [.8, .5], [-.4, -.9],
[1.1, -.2], [-.8, -.1], [.2, 1.2], [.6, -.7],
[-1.2, .4], [.9, 1.0], [-.3, .2], [.4, -.1],
[-.6, -.6], [1.3, .7], [-.9, 1.1], [.1, -.8],
])
OUTLIER = np.array([6., -5.])
SIZES = (2, 4, 8, 16)
EPSILONS = (1e-5, .01, .1)
def normalize(points, epsilon):
points = np.asarray(points, dtype=float)
if points.ndim != 2 or points.shape[1] != 2 or points.shape[0] < 1:
raise ValueError('Se espera una matriz de puntos 2D no vacía.')
if not np.isfinite(epsilon) or epsilon <= 0 or not np.isfinite(points).all():
raise ValueError('Las entradas y ε deben ser finitos, con ε positivo.')
mean = points.mean(axis=0)
variance = ((points-mean)**2).mean(axis=0)
output = (points-mean) / np.sqrt(variance+epsilon)
return mean, variance, output
def run(size, outlier, epsilon):
if size not in SIZES: raise ValueError('tamaño ordinario no soportado')
points = np.vstack((POINTS[:size], OUTLIER)) if outlier else POINTS[:size].copy()
mean, variance, output = normalize(points, epsilon)
return {'ordinary_size': size, 'with_outlier': outlier, 'epsilon': epsilon,
'effective_size': len(points), 'points': points.tolist(),
'mean': mean.tolist(), 'variance': variance.tolist(),
'output': output.tolist(), 'anchor': output[0].tolist()}
def validate():
records = []
for size in SIZES:
for eps in EPSILONS:
for outlier in (False, True):
row = run(size, outlier, eps)
data, output = np.array(row['points']), np.array(row['output'])
mean, variance = np.array(row['mean']), np.array(row['variance'])
assert len(data) == size + int(outlier)
assert np.array_equal(data[0], POINTS[0]) and np.isfinite(output).all()
assert np.allclose(output.mean(axis=0), 0, atol=1e-12)
assert np.allclose(output.var(axis=0), variance/(variance+eps), atol=1e-12)
translated_mean, _, translated = normalize(data+np.array([11., -8.]), eps)
assert np.allclose(translated_mean, mean+[11., -8.])
assert np.allclose(translated, output, atol=1e-12)
order = np.arange(len(data))[::-1]
_, _, permuted = normalize(data[order], eps)
assert np.allclose(permuted[::-1], output, atol=1e-12)
records.append(row)
# Una característica constante permanece en cero porque ε evita división por cero.
_, var, out = normalize([[2., 0.], [2., 1.]], .01)
assert var[0] == 0 and np.all(out[:,0] == 0)
# Con solo dos puntos, cada coordenada es ±d/sqrt(d²+4ε).
two = run(2, False, .01)
delta = POINTS[0]-POINTS[1]
assert np.allclose(two['anchor'], delta/np.sqrt(delta**2+4*.01))
return records
if __name__ == '__main__':
records = validate()
destination = Path('batch-points.json')
destination.write_text(json.dumps({'points': POINTS.tolist(), 'outlier': OUTLIER.tolist(),
'sizes': SIZES, 'epsilons': EPSILONS, 'records': records},
ensure_ascii=False, indent=2), encoding='utf-8')
print('Combinaciones y pruebas:', len(records), 'correctas')
for size in SIZES:
a, b = run(size, False, .01), run(size, True, .01)
print('Tamaño ordinario', size, 'ancla sin atípico', np.array(a['anchor']),
'con atípico', np.array(b['anchor']), 'media y varianza con atípico',
np.array(b['mean']), np.array(b['variance']))Lab from scratch: forward, backward, and ten layers
The first cell implements BN per feature with explicit state; it checks backward by finite differences in both modes and distinguishes forward variance from the running update. The second includes the tensor engine from lesson 9. The third connects manual backward to autograd and trains a ten-layer MLP on load_digits with and without BN. Both runs use the same weights and minibatches; validation uses evaluation statistics and does not update state.
"""BatchNorm 2D por características, forward/backward y pruebas independientes.
La varianza del forward usa ddof=0; la móvil usa ddof=1 como PyTorch.
El modo train con una muestra solo se admite sin actualizar la varianza móvil,
para ilustrar la fórmula matemática. BatchNorm1d de PyTorch rechaza N=1.
"""
import numpy as np
def forward(x, gamma, beta, *, training, running_mean, running_var, momentum=.1, eps=1e-5, update=True):
x, gamma, beta = np.asarray(x, dtype=float), np.asarray(gamma, dtype=float), np.asarray(beta, dtype=float)
mean_state, var_state = np.asarray(running_mean, dtype=float), np.asarray(running_var, dtype=float)
if x.ndim != 2 or x.shape[0] == 0 or x.shape[1] == 0:
raise ValueError('x debe ser una matriz no vacía')
if any(y.shape != (x.shape[1],) for y in (gamma, beta, mean_state, var_state)):
raise ValueError('vectores por característica con forma incorrecta')
if not 0 <= momentum <= 1 or not np.isfinite(eps) or eps < 0:
raise ValueError('momentum o epsilon inválido')
if any(not np.all(np.isfinite(y)) for y in (x, gamma, beta, mean_state, var_state)) or np.any(var_state < 0):
raise ValueError('datos o estadísticas no finitos, o varianza negativa')
if training:
mean = x.mean(axis=0)
variance = ((x-mean)**2).mean(axis=0)
if update and len(x) < 2: raise ValueError('varianza móvil insesgada requiere al menos dos muestras')
else:
mean, variance = mean_state, var_state
if np.any(variance+eps <= 0): raise ValueError('denominador nulo')
inv_std = 1 / np.sqrt(variance+eps)
normalized = (x-mean)*inv_std
y = gamma*normalized+beta
if training and update:
new_mean = (1-momentum)*mean_state+momentum*mean
new_var = (1-momentum)*var_state+momentum*variance*len(x)/(len(x)-1)
else:
new_mean, new_var = mean_state.copy(), var_state.copy()
return y, (normalized, inv_std, gamma.copy(), training), new_mean, new_var
def backward(gy, cache):
normalized, inv_std, gamma, training = cache
gy = np.asarray(gy, dtype=float)
if gy.shape != normalized.shape or not np.all(np.isfinite(gy)):
raise ValueError('gradiente de salida inválido')
dbeta = gy.sum(axis=0)
dgamma = (gy*normalized).sum(axis=0)
if training:
dx = gamma*inv_std*(gy-gy.mean(axis=0)-normalized*(gy*normalized).mean(axis=0))
else:
dx = gamma*inv_std*gy
return dx, dgamma, dbeta
def check_gradients(training):
generator = np.random.default_rng(1515)
x, gamma, beta, gy = generator.normal(size=(4,3)), generator.normal(size=3), generator.normal(size=3), generator.normal(size=(4,3))
mean, var = generator.normal(size=3), generator.uniform(.3, 2., size=3)
def objective(a, b, c):
y, _, _, _ = forward(a, b, c, training=training, running_mean=mean, running_var=var, eps=1e-4, update=False)
return np.sum(y*gy)
_, cache, _, _ = forward(x, gamma, beta, training=training, running_mean=mean, running_var=var, eps=1e-4, update=False)
analytic = backward(gy, cache)
step, errors = 1e-6, []
for slot, values in enumerate((x, gamma, beta)):
numeric = np.empty_like(values)
for index in np.ndindex(values.shape):
originals = [x.copy(), gamma.copy(), beta.copy()]
originals[slot][index] += step
plus = objective(*originals)
originals[slot][index] -= 2*step
numeric[index] = (plus-objective(*originals))/(2*step)
errors.append(float(np.max(np.abs(numeric-analytic[slot]))))
assert max(errors) < 1e-8
return errors
if __name__ == '__main__':
for mode in (True, False):
print('Gradcheck train' if mode else 'Gradcheck eval', check_gradients(mode))
# El backward debe usar el gamma del forward, incluso si el llamador lo modifica.
gamma_mutable = np.array([2.])
_, saved, _, _ = forward(np.array([[1.], [2.], [4.]]), gamma_mutable, np.array([0.]),
training=True, running_mean=[0.], running_var=[1.])
before = backward(np.array([[1.], [0.], [-1.]]), saved)[0]
gamma_mutable[0] = 3.
after = backward(np.array([[1.], [0.], [-1.]]), saved)[0]
assert np.array_equal(before, after)
print('Caché: gamma del forward preservado frente a mutación posterior')
gamma, beta = np.array([2.]), np.array([.3])
x = np.array([[1.],[2.],[3.]])
y, cache, mean, var = forward(x, gamma, beta, training=True, running_mean=[0.], running_var=[1.])
assert np.allclose(mean, [.2]) and np.allclose(var, [1.])
_, _, mean, var = forward(2*x, gamma, beta, training=True, running_mean=mean, running_var=var)
assert np.allclose(mean, [.58]) and np.allclose(var, [1.3])
print('Estadísticas móviles tras dos lotes:', mean, var)
old_mean, old_var = mean.copy(), var.copy()
a, eval_cache, mean2, var2 = forward(x[:1], gamma, beta, training=False, running_mean=mean, running_var=var)
b, _, _, _ = forward(x, gamma, beta, training=False, running_mean=mean, running_var=var)
assert np.allclose(a[0], b[0]) and np.array_equal(mean,mean2) and np.array_equal(var,var2)
assert np.array_equal(mean,old_mean) and np.array_equal(var,old_var)
print('Eval: el mismo ejemplo da el mismo resultado y no actualiza estadísticas.')
single, single_cache, _, _ = forward(x[:1], gamma, beta, training=True, running_mean=mean, running_var=var, update=False)
dx, _, _ = backward(np.ones_like(single), single_cache)
assert np.allclose(single, [beta]) and np.allclose(dx, 0.)
try: forward(x[:1], gamma, beta, training=True, running_mean=mean, running_var=var)
except ValueError: pass
else: raise AssertionError('N=1 no admite actualización insesgada')
print('Lote de uno, fórmula matemática: salida β y gradiente de entrada cero; estado móvil no actualizado.')
constant = np.full((3,1), 2.)
_, constant_cache, _, _ = forward(constant, gamma, beta, training=True, running_mean=mean, running_var=var, eps=.04)
dx, _, _ = backward(np.array([[1.],[0.],[-1.]]), constant_cache)
assert np.allclose(dx.ravel(), [10.,0.,-10.])
print('Lote constante: gradiente de entrada con ε=0,04:', dx.ravel())
# ε rompe la invariancia exacta de escala; con ε=0 sí se conserva para varianza positiva.
yy0, _, _, _ = forward(x, gamma, beta, training=True, running_mean=mean, running_var=var, eps=0, update=False)
yy1, _, _, _ = forward(2*x, gamma, beta, training=True, running_mean=mean, running_var=var, eps=0, update=False)
yy2, _, _, _ = forward(x, gamma, beta, training=True, running_mean=mean, running_var=var, eps=.2, update=False)
yy3, _, _, _ = forward(2*x, gamma, beta, training=True, running_mean=mean, running_var=var, eps=.2, update=False)
assert np.allclose(yy0, yy1) and np.max(np.abs(yy2-yy3)) > .01
print('Cambio de salida al duplicar x: ε=0:', np.max(np.abs(yy0-yy1)),
'; ε=0,2:', np.max(np.abs(yy2-yy3)))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 numpy as np
data, labels = load_digits(return_X_y=True)
data = data/16.0
train_ids, validation_ids = train_test_split(np.arange(len(labels)), test_size=.2,
random_state=1501, stratify=labels)
x_train, y_train = data[train_ids], labels[train_ids]
x_valid, y_valid = data[validation_ids], labels[validation_ids]
def batchnorm_tensor(x, gamma, beta, state, training):
y, cache, new_mean, new_var = forward(x.data, gamma.data, beta.data,
training=training, running_mean=state[0], running_var=state[1],
momentum=.1, eps=1e-5, update=training)
if training: state[0][:], state[1][:] = new_mean, new_var
result = Tensor(y, (x, gamma, beta))
def apply_backward():
dx, dg, db = backward(result.grad, cache)
x.grad += dx; gamma.grad += dg; beta.grad += db
result._backward = apply_backward
return result
# Verifica también el enlace de la operación con el motor Tensor, no solo la
# función NumPy: comparamos los tres gradientes en train y en eval.
check_rng = np.random.default_rng(1504)
check_x = check_rng.normal(size=(4, 3))
check_gamma = check_rng.normal(size=3)
check_beta = check_rng.normal(size=3)
check_seed = check_rng.normal(size=(4, 3))
for mode in (True, False):
x, gamma, beta = Tensor(check_x), Tensor(check_gamma), Tensor(check_beta)
states = [np.zeros(3), np.ones(3)]
result = batchnorm_tensor(x, gamma, beta, states, mode)
(result * Tensor(check_seed)).sum().backward()
_, cache, _, _ = forward(check_x, check_gamma, check_beta, training=mode,
running_mean=np.zeros(3), running_var=np.ones(3), update=False)
expected = backward(check_seed, cache)
assert all(np.allclose(actual.grad, target, rtol=1e-12, atol=1e-12)
for actual, target in zip((x, gamma, beta), expected))
print('VJP de Tensor coincide con NumPy en train y eval')
x, gamma, beta = Tensor(check_x), Tensor(check_gamma), Tensor(check_beta)
states = [np.zeros(3), np.ones(3)]
output = batchnorm_tensor(x, gamma, beta, states, True)
_, saved, _, _ = forward(check_x, check_gamma, check_beta, training=True,
running_mean=np.zeros(3), running_var=np.ones(3), update=False)
expected_dx = backward(check_seed, saved)[0]
gamma.data[:] += 3.
(output * Tensor(check_seed)).sum().backward()
assert np.allclose(x.grad, expected_dx, rtol=1e-12, atol=1e-12)
print('Autograd: mutar gamma después del forward no altera el backward guardado')
def initial_parameters(seed=1502, depth=10, width=24):
rng = np.random.default_rng(seed)
sizes = [64] + [width]*depth + [10]
weights = [rng.normal(0, np.sqrt(2/a), (a,b)) for a,b in zip(sizes[:-1], sizes[1:])]
biases = [np.zeros(b) for b in sizes[1:]]
return weights, biases
class Network:
def __init__(self, use_bn):
weights, biases = initial_parameters()
self.weights = [Tensor(w) for w in weights]
self.biases = [Tensor(b) for b in biases]
self.gamma = [Tensor(np.ones(24)) for _ in range(10)] if use_bn else []
self.beta = [Tensor(np.zeros(24)) for _ in range(10)] if use_bn else []
self.states = [[np.zeros(24), np.ones(24)] for _ in range(10)] if use_bn else []
self.use_bn = use_bn
self.params = self.weights + self.biases + self.gamma + self.beta
def __call__(self, x, training):
h = Tensor(x)
for i in range(10):
h = h @ self.weights[i] + self.biases[i]
if self.use_bn: h = batchnorm_tensor(h, self.gamma[i], self.beta[i], self.states[i], training)
h = h.relu()
return h @ self.weights[-1] + self.biases[-1]
def evaluate(self):
scores = self(x_valid, False).data
return float(cross_entropy(Tensor(scores), y_valid).data), float(np.mean(scores.argmax(axis=1) == y_valid))
def run_comparison(use_bn, steps=80, batch_size=32, lr=.1):
model = Network(use_bn)
generator = np.random.default_rng(1503)
result = [(0, *model.evaluate())]
for step in range(1, steps+1):
idx = generator.integers(0, len(y_train), size=batch_size)
for p in model.params: p.grad.fill(0)
loss = cross_entropy(model(x_train[idx], True), y_train[idx])
if not np.isfinite(loss.data):
print('carrera detenida por pérdida no finita, paso', step)
break
loss.backward()
if any(not np.all(np.isfinite(p.grad)) for p in model.params):
print('carrera detenida por gradiente no finito, paso', step)
break
for p in model.params: p.data -= lr*p.grad
if step in (20, 40, 80): result.append((step, *model.evaluate()))
return result
for bn in (False, True):
print('BN',bn,'paso, pérdida y exactitud de validación:', run_comparison(bn))With these seeds and 80 steps, final validation loss is approximately 1.5869 without BN and 0.8482 with BN. This is a short run of one network; it does not measure the best rate or prove a universal advantage.
Local labs: modes and stability
The first cell reproduces the train–eval figure data: for each batch size and momentum it uses the same validation images grouped into blocks, measures both modes, and restores buffers and counter after diagnosis. With equal steps, batch sizes process different numbers of examples. The second compares networks with and without BN, rates, and weight decay on Fashion-MNIST; it records divergence and layer norms without consulting official test data. Both provide full mode for the reader and a short check.
"""Barrido reproducible de BatchNorm y estadísticas móviles en Fashion-MNIST.
Cada condición entrena un MLP real. Comparamos train y eval sobre exactamente
los mismos ejemplos de validación y restauramos el estado de BatchNorm. El
modo corto genera las mediciones para la figura; no consulta el test oficial.
"""
import json
import math
import os
from pathlib import Path
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
short = os.getenv('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_size = 4096 if short else 50000
validation_size = 256 if short else 10000
diagnostic_size = 256 if short else 1024
width = 64 if short else 256
depth = 3
steps = 120 if short else 2000
every = 20 if short else 100
learning_rate = 0.05
batch_sizes = (4, 16, 64)
momenta = (0.01, 0.1, 0.5)
seeds = (17, 31) if short else (17, 31, 43)
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(15151))
train_ids, validation_ids = split[:train_size], split[train_size:train_size+validation_size]
assert not set(train_ids.tolist()).intersection(validation_ids.tolist())
assert diagnostic_size <= validation_size and all(diagnostic_size % b == 0 for b in batch_sizes)
train_x = (dataset.data[train_ids].reshape(train_size, -1).float() / 255).to(device)
train_y = dataset.targets[train_ids].to(device)
ids = validation_ids[:diagnostic_size]
valid_x = (dataset.data[ids].reshape(diagnostic_size, -1).float() / 255).to(device)
valid_y = dataset.targets[ids].to(device)
class Network(nn.Module):
def __init__(self, seed, momentum):
super().__init__()
torch.manual_seed(seed)
sizes = [784] + [width] * depth
self.hidden = nn.ModuleList([nn.Linear(sizes[i], sizes[i+1], bias=False) for i in range(depth)])
self.bns = nn.ModuleList([nn.BatchNorm1d(width, momentum=momentum) for _ in range(depth)])
self.output = nn.Linear(width, 10)
for layer in self.hidden:
nn.init.kaiming_normal_(layer.weight, nonlinearity='relu')
nn.init.xavier_normal_(self.output.weight)
nn.init.zeros_(self.output.bias)
def forward(self, x):
for layer, bn in zip(self.hidden, self.bns):
x = torch.relu(bn(layer(x)))
return self.output(x)
@torch.no_grad()
def compare_modes(model, batch_size):
old_mode = model.training
model.eval()
snapshots = [(b.running_mean.clone(), b.running_var.clone(), b.num_batches_tracked.clone()) for b in model.bns]
def measure():
logits = torch.cat([model(valid_x[i:i+batch_size]) for i in range(0, diagnostic_size, batch_size)])
if not torch.isfinite(logits).all():
return None
loss = nn.functional.cross_entropy(logits, valid_y)
if not torch.isfinite(loss):
return None
return {'loss': float(loss.item()), 'accuracy': float((logits.argmax(1) == valid_y).float().mean().item())}
try:
evaluation = measure()
for bn in model.bns:
bn.train()
training = measure()
finally:
for bn, (mean, var, count) in zip(model.bns, snapshots):
bn.running_mean.copy_(mean)
bn.running_var.copy_(var)
bn.num_batches_tracked.copy_(count)
model.train(old_mode)
assert all(torch.equal(bn.running_mean, mean) and torch.equal(bn.running_var, var)
and torch.equal(bn.num_batches_tracked, count)
for bn, (mean, var, count) in zip(model.bns, snapshots))
return training, evaluation
records = []
for seed in seeds:
generator = torch.Generator().manual_seed(seed + 900)
sample_indices = torch.randint(train_size, (steps, max(batch_sizes)), generator=generator)
for batch_size in batch_sizes:
for momentum in momenta:
model = Network(seed, momentum).to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
train_metric, eval_metric = compare_modes(model, batch_size)
status = 'complete' if train_metric is not None and eval_metric is not None else 'nonfinite_initial'
points = []
if status == 'complete':
points.append({'step': 0, 'train': train_metric, 'eval': eval_metric})
attempted = 0
for step in range(1, steps+1):
if status != 'complete':
break
attempted = step
model.train()
ids = sample_indices[step-1, :batch_size].to(device)
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(train_x[ids]), train_y[ids])
if not torch.isfinite(loss):
status = 'nonfinite_loss'
break
loss.backward()
if not all(p.grad is None or torch.isfinite(p.grad).all() for p in model.parameters()):
status = 'nonfinite_gradient'
break
optimizer.step()
if step == 1 or step % every == 0 or step == steps:
train_metric, eval_metric = compare_modes(model, batch_size)
if train_metric is None or eval_metric is None:
status = 'nonfinite_diagnostic'
break
points.append({'step': step, 'train': train_metric, 'eval': eval_metric})
records.append({'seed': seed, 'batch': batch_size, 'momentum': momentum,
'status': status, 'last_attempted_step': attempted, 'points': points})
print('seed', seed, 'batch', batch_size, 'momentum', momentum, 'status', status,
'último', points[-1] if points else None, flush=True)
del model, optimizer
if device.type == 'cuda':
torch.cuda.empty_cache()
output = {'dataset':'Fashion-MNIST, train oficial', 'source':'https://github.com/zalandoresearch/fashion-mnist',
'mode':'short' if short else 'reader', 'device':str(device), 'torch':torch.__version__,
'split_seed':15151, 'train_examples':train_size, 'validation_examples':validation_size,
'diagnostic_examples':diagnostic_size, 'width':width, 'depth':depth, 'steps':steps, 'lr':learning_rate,
'batch_sizes':list(batch_sizes), 'momenta':list(momenta), 'seeds':list(seeds),
'protocol':'mismos ejemplos de validación, partidas disjuntas, estadísticas móviles restauradas; '
'120 pasos en ensayo corto con mismo número de actualizaciones, no de ejemplos',
'records':records}
target = Path(os.getenv('ORYON_BN_SWEEP_OUTPUT', 'batchnorm-train-eval.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')
print('Datos guardados en', target, flush=True)
del train_x, train_y, valid_x, valid_y
if device.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link."""BatchNorm en Fashion-MNIST: ensayo corto reproducible o laboratorio del lector.
ORYON_VERIFY_SHORT=1 reduce datos, anchura y pasos para verificar el flujo.
El diagnóstico train/eval usa ejemplos de validación, sin actualizar las
estadísticas que el entrenamiento utilizará después. Test oficial sin consultar.
"""
import json
import math
import os
from pathlib import Path
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short = os.getenv('ORYON_VERIFY_SHORT') == '1'
train_size, validation_size = (2048, 128) if short else (50000, 10000)
diagnostic_size = 128 if short else 256
steps = 60 if short else 2000
check_every = 20 if short else 200
width = 64 if short else 256
depth = 4
batch_size = 4
seeds = (17, 31) if short else (17, 31, 43)
learning_rates = (0.01, 0.1, 1.0)
decays = (0.0, 0.001)
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(15150))
train_ids = split[:train_size]
validation_ids = split[train_size:train_size + validation_size]
assert len(set(train_ids.tolist()).intersection(validation_ids.tolist())) == 0
assert diagnostic_size <= validation_size and diagnostic_size % batch_size == 0
train_x = (dataset.data[train_ids].reshape(train_size, -1).float() / 255).to(device)
train_y = dataset.targets[train_ids].to(device)
diagnostic_ids = validation_ids[:diagnostic_size]
diagnostic_x = (dataset.data[diagnostic_ids].reshape(diagnostic_size, -1).float() / 255).to(device)
diagnostic_y = dataset.targets[diagnostic_ids].to(device)
class Network(nn.Module):
def __init__(self, seed, use_bn):
super().__init__()
torch.manual_seed(seed)
dimensions = [784] + [width] * depth
self.layers = nn.ModuleList([nn.Linear(dimensions[i], dimensions[i+1], bias=False) for i in range(depth)])
self.norms = nn.ModuleList([nn.BatchNorm1d(width, momentum=0.1) if use_bn else nn.Identity() for _ in range(depth)])
self.output = nn.Linear(width, 10)
for layer in self.layers:
nn.init.kaiming_normal_(layer.weight, mode='fan_in', nonlinearity='relu')
nn.init.xavier_normal_(self.output.weight)
nn.init.zeros_(self.output.bias)
def forward(self, x):
for layer, norm in zip(self.layers, self.norms):
x = torch.relu(norm(layer(x)))
return self.output(x)
def parameter_groups(model, decay):
weights = [layer.weight for layer in model.layers] + [model.output.weight]
weight_ids = {id(p) for p in weights}
others = [p for p in model.parameters() if id(p) not in weight_ids]
assert len({id(p) for p in weights + others}) == len(list(model.parameters()))
return [{'params': weights, 'weight_decay': decay}, {'params': others, 'weight_decay': 0.0}]
@torch.no_grad()
def diagnostics(model):
"""Mismos ejemplos y bloques de cuatro en train y eval; restaura el estado BN."""
was_training = model.training
model.eval()
bns = [m for m in model.modules() if isinstance(m, nn.BatchNorm1d)]
snapshots = [(m.running_mean.clone(), m.running_var.clone(), m.num_batches_tracked.clone()) for m in bns]
def evaluate_chunks():
chunks = [model(diagnostic_x[i:i+batch_size]) for i in range(0, diagnostic_size, batch_size)]
logits = torch.cat(chunks)
if not torch.isfinite(logits).all():
return None
loss = nn.functional.cross_entropy(logits, diagnostic_y)
if not torch.isfinite(loss):
return None
return {'loss': float(loss.item()), 'accuracy': float((logits.argmax(1) == diagnostic_y).float().mean().item())}
try:
evaluation = evaluate_chunks()
# Solo cambian temporalmente las BN; no se activan hipotéticos dropout.
for bn in bns:
bn.train()
training = evaluate_chunks()
finally:
for bn, (mean, var, counter) in zip(bns, snapshots):
bn.running_mean.copy_(mean)
bn.running_var.copy_(var)
bn.num_batches_tracked.copy_(counter)
model.train(was_training)
assert all(torch.equal(bn.running_mean, mean) and torch.equal(bn.running_var, var)
and torch.equal(bn.num_batches_tracked, counter)
for bn, (mean, var, counter) in zip(bns, snapshots))
return training, evaluation
def weight_norms(model):
return [float(layer.weight.detach().double().norm().item()) for layer in model.layers]
records = []
for seed in seeds:
plain_initial, bn_initial = Network(seed, False), Network(seed, True)
assert all(torch.equal(a.weight, b.weight) for a, b in zip(plain_initial.layers, bn_initial.layers))
assert torch.equal(plain_initial.output.weight, bn_initial.output.weight)
assert torch.equal(plain_initial.output.bias, bn_initial.output.bias)
del plain_initial, bn_initial
generator = torch.Generator().manual_seed(seed + 1515)
batch_indices = torch.randint(train_size, (steps, batch_size), generator=generator)
for use_bn in (False, True):
for lr in learning_rates:
for decay in decays:
model = Network(seed, use_bn).to(device)
optimizer = torch.optim.SGD(parameter_groups(model, decay), lr=lr)
train_metric, eval_metric = diagnostics(model)
norms = weight_norms(model)
status = 'complete' if train_metric is not None and eval_metric is not None and all(map(math.isfinite, norms)) else 'nonfinite_initial'
points = []
if status == 'complete':
points.append({'step': 0, 'train_mode': train_metric, 'eval_mode': eval_metric, 'weight_norms': norms})
attempted = 0
for step in range(1, steps + 1):
if status != 'complete':
break
attempted = step
model.train()
ids = batch_indices[step-1].to(device)
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(train_x[ids]), train_y[ids])
if not torch.isfinite(loss):
status = 'nonfinite_loss'
break
loss.backward()
if not all(p.grad is None or torch.isfinite(p.grad).all() for p in model.parameters()):
status = 'nonfinite_gradient'
break
optimizer.step()
if step == 1 or step % check_every == 0 or step == steps:
train_metric, eval_metric = diagnostics(model)
norms = weight_norms(model)
if train_metric is None or eval_metric is None or not all(map(math.isfinite, norms)):
status = 'nonfinite_diagnostic'
break
points.append({'step': step, 'train_mode': train_metric, 'eval_mode': eval_metric, 'weight_norms': norms})
result = {'seed': seed, 'bn': use_bn, 'lr': lr, 'decay': decay,
'status': status, 'last_attempted_step': attempted, 'points': points}
records.append(result)
print(f'seed={seed} BN={use_bn} lr={lr} decay={decay} status={status} step={attempted} '
f'last={points[-1] if points else None}', flush=True)
del model, optimizer
if device.type == 'cuda':
torch.cuda.empty_cache()
output = {
'dataset': 'Fashion-MNIST, partición oficial train', 'source': 'https://github.com/zalandoresearch/fashion-mnist',
'mode': 'short' if short else 'reader', 'device': str(device), 'torch': torch.__version__,
'split_seed': 15150, 'train_examples': train_size, 'validation_examples': validation_size,
'diagnostic_examples': diagnostic_size, 'diagnostic_batch_size': batch_size, 'batch_size': batch_size,
'steps': steps, 'depth': depth, 'width': width, 'seeds': list(seeds),
'learning_rates': list(learning_rates), 'decays': list(decays),
'batches': 'con reemplazo, semilla de lote = semilla de modelo + 1515; compartidos entre configuraciones',
'decay_policy': 'SGD L2 acoplado aplicado a matrices lineales; bias y parámetros de BN excluidos',
'diagnostics': 'misma partición y bloques en ambos modos; estadísticas móviles restauradas',
'records': records,
}
target = Path(os.getenv('ORYON_BN_OUTPUT', 'batchnorm-fashion.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')
print('Datos guardados en', target, flush=True)
del train_x, train_y, diagnostic_x, diagnostic_y
if device.type == 'cuda':
torch.cuda.empty_cache()
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, axes = plt.subplots(3, len(learning_rates), figsize=(15, 10), constrained_layout=True, squeeze=False)
colors = {(False, 0.0):'tab:gray', (False, 0.001):'tab:blue', (True, 0.0):'tab:green', (True, 0.001):'tab:orange'}
linestyles = {seed: style for seed, style in zip(seeds, ('-', '--', ':'))}
for record in records:
column = learning_rates.index(record['lr'])
key = (record['bn'], record['decay'])
label = f"{'BN' if record['bn'] else 'sin BN'}, λ={record['decay']}, semilla {record['seed']}"
if record['status'] != 'complete':
label += f" (detenido {record['last_attempted_step']})"
points = record['points']
if not points:
continue
kwargs = dict(color=colors[key], linestyle=linestyles[record['seed']], linewidth=1.4, label=label)
xs = [p['step'] for p in points]
metrics = [[p['eval_mode']['accuracy'] for p in points],
[p['train_mode']['accuracy'] - p['eval_mode']['accuracy'] for p in points],
[p['weight_norms'][0] for p in points]]
for row, values in enumerate(metrics):
axes[row, column].plot(xs, values, marker='.', **kwargs)
if record['status'] != 'complete':
axes[row, column].plot(xs[-1], values[-1], marker='x', color=colors[key], markersize=7)
for col, lr in enumerate(learning_rates):
axes[0, col].set_title(f'Tasa η={lr}')
for row in range(3):
axes[row, col].grid(alpha=.25)
axes[row, col].set_xlabel('Paso')
axes[0, col].set_ylim(0, 1)
axes[1, col].axhline(0, color='black', linewidth=.7)
axes[2, col].set_yscale('log')
axes[0, 0].set_ylabel('Precisión eval')
axes[1, 0].set_ylabel('Precisión train − eval')
axes[2, 0].set_ylabel('Norma pesos primera capa (log)')
axes[0, 0].legend(fontsize=6, loc='best')
fig.suptitle('Fashion-MNIST: lotes de 4 y diagnóstico en los mismos ejemplos (' + ('ensayo corto' if short else 'laboratorio del lector') + ')')
figure_path = target.with_suffix('.png')
fig.savefig(figure_path, dpi=140)
plt.close(fig)
print('Gráfica guardada en', figure_path, flush=True)npm run lab and open the connection link.Exercises
Step 1 of 4. What are the affine parameter gradients?
Step 1 of 3. What follows from differentiating L(cw) with respect to c at c=1?
import numpy as np
def bn_forward(x, gamma, beta, eps):
pass
def bn_backward(g, cache):
pass