Module contents
Lesson 16 of 22Core 75 min

Layer normalization and the normalization family

Compare layer, group, instance and weight normalization through their axes, gradients, invariances and practical choices, including train and evaluation behavior.

After this lesson you can

  • Implement layer normalization forward and backward passes and explain its invariances.
  • Classify batch, layer, instance and group normalization by their statistic axes.
  • Implement weight normalization as a reparameterization and compare it with activation normalization.
  • Choose normalization based on batch size, data and architecture.

Before you start

Who shares the statistics?

The same example can receive a different representation in batch normalization when its batch companions change. In a sequence, a per-token prediction must be computable without future tokens; in a vision network, memory may limit a batch to a few images. Layer norm and group norm choose statistics within each example, independent of other samples. This does not guarantee accuracy independent of batch size: optimizer updates and step counts still change.

InteractiveWhich elements share statistics?

Tensor shape (N,C,H,W) = (2,4,2,2). Height represents channel, depth H, and width W; the two marked sets correspond to different examples. Select an element with controls or click a block.

  • Selected element
  • Shares mean and variance
  • Does not share statistics

For each channel, average over N, H, and W using batch statistics during training.

To check calculations, each block contains x[n,c,h,w] = 16n + 4c + 2h + w. Variance uses denominator M; (x−μ)/√(v+0.1) is shown before the affine transform with the same ε for all. The selected element is included in the count.

GroupNorm with G=1 shares statistics with LayerNorm((C,H,W)); with G=C it shares InstanceNorm per-channel statistics. Equal statistics do not always imply equal output: LayerNorm can learn γ and β for each (c,h,w), while GroupNorm learns them per channel. For G=C, GN and IN outputs match with equal ε and per-channel affine parameters and input statistics; InstanceNorm2d defaults to affine=False in PyTorch. BatchNorm in eval can use running statistics instead of the current batch.

Normalization
Selected index (n, c, h, w)(0, 1, 0, 0)
Elements sharing statistics8
Mean and variance13.500; 65.250
Normalized element value−1.175
Select a family and an element. Highlighting shows elements included in its mean and variance, not affine parameters.

For an image tensor (N,C,H,W)(N,C,H,W), reduced indices are:

OperationStatistics shared byReduced indices
Batch norm in trainingOne channelN,H,WN,H,W
Layer norm over the whole imageOne exampleC,H,WC,H,W
Instance normOne example and channelH,WH,W
Group norm with GG groupsOne example and channel groupC/G,H,WC/G,H,W

In group norm we require GG to be a positive integer dividing CC. Changing GG from 1 to CC changes statistics from layer norm over C,H,WC,H,W to instance norm. This does not make the complete layers always equal: GroupNorm uses one γc,βc\gamma_c,\beta_c per channel and LayerNorm([C,H,W]) defaults to per-element parameters. They coincide if affine parameters are constrained equal across spatial positions and ε\varepsilon and other settings align. Instance norm also requires affine parameters and statistic tracking to align.

In a tensor (N,T,D)(N,T,D), LayerNorm(D) reduces DD per example and time position. By contrast, LayerNorm([T,D]) mixes times: including future tokens can violate causality. Axes are part of the operation’s definition, not a cosmetic detail.

For GN, each statistic groups (C/G)HW(C/G)HW values of one sample. Increasing GG reduces that set and changes channel coupling; it is not equivalent to increasing batch size. If one value remains per group, centering makes it zero: affine output no longer carries that activation. If HH and WW are large, even a one-image batch contributes many spatial values to each BN statistic, although those values can be correlated and do not simply substitute for independent images.

Layer norm as geometry

For a vector x∈Rdx\in\mathbb R^d from one sample, layer normalization computes

μ=1d∑ixi,v=1d∑i(xi−μ)2,x^i=xi−μv+ε,yi=γix^i+βi.\mu=\frac1d\sum_i x_i,\quad v=\frac1d\sum_i(x_i-\mu)^2,\quad \hat x_i=\frac{x_i-\mu}{\sqrt{v+\varepsilon}},\quad y_i=\gamma_i\hat x_i+\beta_i.

Variance uses divisor dd, not d−1d-1. Centering is equivalent to applying projection P=I−11T/dP=I-\mathbf1\mathbf1^{\mathsf T}/d. The centered vector lies in the plane perpendicular to 1\mathbf1. Before the affine transform,

∥x^∥2=dvv+ε.\|\hat x\|_2=\sqrt{\frac{d v}{v+\varepsilon}}.

If v>0v>0 and ε=0\varepsilon=0, it lies on a sphere of radius d\sqrt d inside that plane; in three dimensions this is a circle. With ε>0\varepsilon>0 the radius depends on vv and is smaller. If v=0v=0 and ε>0\varepsilon>0, x^=0\hat x=0 and output is β\beta; if both are zero, normalization is undefined. Per-component scale γ\gamma deforms the circle and β\beta shifts it; zero components of γ\gamma can make it degenerate.

InteractiveProjection, radius, and affine transformation

One example has three features: x = c·(1, 0.3, −0.8) + b·(1, 1, 1). Centering projects it onto the plane orthogonal to (1, 1, 1); it is then divided by √(v + ε) and the per-feature affine transform is applied.

  • Input x
  • Centered projection
  • Normalized x̂
  • Affine output y
  • Affine image of circle

The gray circle lies in the centered plane and has the current input radius. The colored curve is the circle’s image under γ⊙x̂ + β; it can degenerate to a segment or point. Vectors start at the origin and can overlap. To fit the scene, all objects share a scale that can change with controls. Compare numeric readouts for sizes across states.

The exact radius is √(3v/(v + ε)), with v = ‖x − mean(x)‖²/3. It equals √3 only for v > 0 and ε = 0. With positive ε it decreases as the factor shrinks; if c = 0 and ε > 0, input is constant, x̂ = 0 and output is β.

The common shift cancels exactly. With ε = 0 and nonzero c, changing its magnitude does not change normalization, but a negative factor reverses direction. With positive ε, changing magnitude also changes radius. If ε = 0 and c = 0, variance is zero and LayerNorm is undefined.

1.0
0.5
1.3
0.7
1.0
0.4
−0.2
0.3
Input x(1.500, 0.800, −0.300)
Mean of x0.667
Variance of x0.549
Radius of x̂1.483
Normalized vector x̂(0.963, 0.154, −1.117)
Output γ⊙x̂ + β(1.652, −0.092, −0.817)
Modify the vector, ε, and affine parameters. Compare actual center and radius with the ideal sphere at ε equal to zero.

Adding b1b\mathbf1 to xx does not change the result. For a>0a>0, equality LN⁡(ax)=LN⁡(x)\operatorname{LN}(ax)=\operatorname{LN}(x) is exact if ε=0\varepsilon=0 and v>0v>0, and approximate when a2va^2v and vv greatly exceed ε\varepsilon. With a<0a<0 the normalized part changes sign. Thus, with ε>0\varepsilon>0 one cannot claim all scale information has disappeared. Layer norm does exactly remove common shift, which could be useful for the task if no other path preserves it.

For example, two vectors differing only by a common constant become indistinguishable to this layer. Affine parameters are shared across examples and cannot reconstruct that shift. A residual connection can offer another path for the original signal, but its effect depends on architecture: it does not automatically make normalization invertible.

Deriving the backward pass

The same batch norm backward structure appears when reducing over another axis. Let gi=∂L/∂yig_i=\partial L/\partial y_i and qi=giγiq_i=g_i\gamma_i. With r=(v+ε)−1/2r=(v+\varepsilon)^{-1/2},

∂L∂xi=r[qi−mean⁡(q)−x^imean⁡(qx^)].\frac{\partial L}{\partial x_i} =r\left[q_i-\operatorname{mean}(q)-\hat x_i\operatorname{mean}(q\hat x)\right].

The two subtractions come from the mean and variance depending on all features of the same example. Do not pull γ\gamma outside the means: it can vary across features. The gradient of γi\gamma_i sums gix^ig_i\hat x_i over examples and other axes sharing that parameter; that of βi\beta_i sums gig_i over the same axes. With ε>0\varepsilon>0, the radial component does not vanish exactly. With one feature, centering always gives zero, output is β\beta, and input gradient is zero.

To derive this, write c=Pxc=Px and r=(v+ε)−1/2r=(v+\varepsilon)^{-1/2}. A change dxdx produces dc=P dxdc=P\,dx and dv=2cTdx/ddv=2c^{\mathsf T}dx/d, because cc is already orthogonal to 1\mathbf1. By the chain rule,

dx^=rP dx−rx^ mean⁡(x^⊙dx).d\hat x=rP\,dx-r\hat x\,\operatorname{mean}(\hat x\odot dx).

The dot product of this expression with qq gives the previous formula: PP is symmetric and Px^=x^P\hat x=\hat x. When ε=0\varepsilon=0 and v>0v>0, the Jacobian also annihilates the radial direction; with ε>0\varepsilon>0 it attenuates but does not eliminate it.

Layer norm and group norm use each example’s own statistics in training and evaluation. Instance norm also does this in its usual configuration, but can use running means in evaluation if statistic tracking is enabled. Other model layers, such as dropout, can still behave differently between modes. The choice of groups controls which features are coupled; it does not by itself change the semantics of all training.

Weight directions, not batches

Weight normalization reparameterizes each weight vector as w=gv/∥v∥2w=g v/\|v\|_2, with v≠0v\ne0 and scalar gg. It operates on parameters, not activations or sample statistics. If gg can be negative, ∥w∥=∣g∣\|w\|=|g|. For u=v/∥v∥u=v/\|v\| and h=∇wLh=\nabla_w L,

∂L∂g=uTh,∇vL=g∥v∥(I−uuT)h.\frac{\partial L}{\partial g}=u^{\mathsf T}h,\qquad \nabla_v L=\frac{g}{\|v\|}(I-uu^{\mathsf T})h.

The gradient of vv is tangent to the sphere of directions; the parameterization does not automatically normalize layer output. Salimans and Kingma study this parameterization in classification, generative models, and reinforcement learning. Decay treatment for gg, vv, γ\gamma, and β\beta is an experimental decision: excluding normalization parameters is common, not a law guaranteeing better results.

[ ]Weight norm and its gradientBrowser
import numpy as np

def weight_norm(v, gain):
    length = np.linalg.norm(v)
    if not np.isfinite(length) or length == 0: raise ValueError('v debe tener norma positiva y finita')
    return gain*v/length

def weight_norm_backward(v, gain, dw):
    length = np.linalg.norm(v)
    if not np.isfinite(length) or length == 0: raise ValueError('v debe tener norma positiva y finita')
    unit = v/length
    return gain/length*(dw-unit*np.dot(unit,dw)), np.dot(unit,dw)

v = np.array([1., -2., 3.])
gain = -1.7
upstream = np.array([.2, .4, -.8])
dv, dg = weight_norm_backward(v, gain, upstream)
step = 1e-6
numerical_v = np.array([np.dot(upstream,weight_norm(v+step*e,gain)-weight_norm(v-step*e,gain))/(2*step) for e in np.eye(3)])
numerical_g = np.dot(upstream,weight_norm(v,gain+step)-weight_norm(v,gain-step))/(2*step)
assert np.max(np.abs(dv-numerical_v)) < 1e-9 and abs(dg-numerical_g) < 1e-9
assert abs(np.dot(v,dv)) < 1e-12
print('norma del peso y |ganancia|:', np.linalg.norm(weight_norm(v,gain)), abs(gain))
print('error de gradiente v y g:', np.max(np.abs(dv-numerical_v)), abs(dg-numerical_g))

Comparing batch sizes

InteractiveAccuracy and batch size

These curves show final validation accuracy in real short Fashion-MNIST runs. The vertical line marks selected batch size. All use the same architecture and rate, but not all normalizations use the same statistics in training and inference.

Preparing chart…
BatchNorm: loss 2.1273LayerNorm: loss 1.5282GroupNorm (8 groups): loss 1.5017

Per seed there is a 784→64→64→64→10 MLP, He initialization, and SGD with η=0.03. The same initialization and index sequence are used for all three normalizations. Data comprise 4096 training images and 512 disjoint validation images; measurement uses eval mode and official test data are not consulted. GroupNorm divides 64 features into eight groups.

The budget is 80 updates per condition. Larger batches process more examples and batches are sampled with replacement; curves therefore do not isolate batch-size effects at equal example counts. They do not prove one normalization always wins. The lab reproduces the sweep and saves its results.

2
BatchNorm25.2 %
LayerNorm35.9 %
GroupNorm (8 groups)43.9 %
Examples processed160
Compare measured results, their seeds, and budget. A crossing of curves belongs to this experiment, not every architecture.

In Table 2 of Wu and He, ResNet-50 on ImageNet has validation error 34.7% with BN and 24.1% with GN using two images per GPU: a 10.6 percentage-point difference. With 32 images per GPU, figures are 23.6% and 24.1%. Their eight GPUs calculate BN without synchronizing statistics; they keep epochs fixed and scale rate with batch size. This is a result of that protocol, not a guarantee for every network.

The from-scratch cell below compares BN and LN on load_digits with the same seeds, initial weights, split, and 1024 examples sampled with replacement. Batches of 8, 32, and 64 imply 128, 32, and 16 updates, respectively. This is a short comparison with one seed: changing batch size also changes step count. The figure uses its own measurements as indicated there.

In that run, with batch 8 final validation accuracy is 44.17% with BN and 20.56% with LN; with batch 64 it is 16.39% and 20.56%, respectively. These are small-budget results, not a general ranking. BN is evaluated with running statistics and LN with each example’s current features; even before training, the networks can produce different outputs despite sharing weights.

When choosing a starting point, consider which units can share information. In segmentation with few images per GPU, GN avoids estimating statistics across images; with a large batch, BN is reasonable if evaluation respects running statistics. For causal sequences, Ba, Kiros and Hinton propose LN per time step without depending on other samples. For fast style transfer, Ulyanov, Vedaldi and Lempitsky study replacing BN with IN. In every case, check architecture and task: removing per-channel spatial mean and scale can help style but hurt when those quantities contain needed signal.

Lab from scratch

First BN is checked with the current implementation from the previous lesson, then LN, RMSNorm, and GN. RMSNorm does not subtract the mean: x/mean⁡(x2)+εx/\sqrt{\operatorname{mean}(x^2)+\varepsilon} preserves information removed by LN centering. This previews RMSNorm in transformers; pre-norm versus post-norm placement also changes the gradient path.

[ ]Tensor and its vector-Jacobian productsBrowser
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
[ ]Batch norm and its derivativesBrowser
"""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)))
[ ]Layer norm, RMSNorm, and group normBrowser
"""LayerNorm, RMSNorm y GroupNorm con gradientes y pruebas NumPy.

LN/RMS normalizan el último eje; GN usa (N,C,H,W) y γ/β por canal.
Cada función guarda sus propios datos para que mutaciones posteriores no
alteren el backward. Las estadísticas usan la varianza con divisor M.
"""
import numpy as np


def layer_forward(x, gamma, beta, eps=1e-5):
    x, gamma, beta = np.asarray(x, dtype=float), np.asarray(gamma, dtype=float), np.asarray(beta, dtype=float)
    if x.ndim < 2 or x.shape[-1] == 0 or gamma.shape != x.shape[-1:] or beta.shape != gamma.shape:
        raise ValueError('formas incompatibles')
    if not np.isfinite(eps) or eps <= 0: raise ValueError('epsilon positivo y finito')
    centered = x-x.mean(axis=-1, keepdims=True)
    inv = 1/np.sqrt(np.mean(centered**2, axis=-1, keepdims=True)+eps)
    normalized = centered*inv
    return normalized*gamma+beta, (normalized, inv, gamma.copy())


def layer_backward(g, cache):
    normalized, inv, gamma = cache
    q = g*gamma
    dx = inv*(q-q.mean(axis=-1, keepdims=True)-normalized*(q*normalized).mean(axis=-1, keepdims=True))
    axes = tuple(range(g.ndim-1))
    return dx, np.sum(g*normalized, axis=axes), np.sum(g, axis=axes)


def rms_forward(x, gamma, eps=1e-5):
    x, gamma = np.asarray(x, dtype=float), np.asarray(gamma, dtype=float)
    if x.ndim < 2 or x.shape[-1] == 0 or gamma.shape != x.shape[-1:]: raise ValueError('formas incompatibles')
    if not np.isfinite(eps) or eps <= 0: raise ValueError('epsilon positivo y finito')
    inv = 1/np.sqrt(np.mean(x*x, axis=-1, keepdims=True)+eps)
    normalized = x*inv
    return normalized*gamma, (normalized, inv, gamma.copy())


def rms_backward(g, cache):
    normalized, inv, gamma = cache
    q = g*gamma
    dx = inv*(q-normalized*(q*normalized).mean(axis=-1, keepdims=True))
    axes = tuple(range(g.ndim-1))
    return dx, np.sum(g*normalized, axis=axes)


def group_forward(x, gamma, beta, groups, eps=1e-5):
    x, gamma, beta = np.asarray(x, dtype=float), np.asarray(gamma, dtype=float), np.asarray(beta, dtype=float)
    if x.ndim != 4 or any(d < 1 for d in x.shape) or isinstance(groups, (bool, np.bool_)) or not isinstance(groups, (int, np.integer)) or groups < 1 or x.shape[1] % groups:
        raise ValueError('forma o grupos inválidos')
    n, c, h, w = x.shape
    if gamma.shape != (c,) or beta.shape != (c,): raise ValueError('afines por canal')
    if not np.isfinite(eps) or eps <= 0: raise ValueError('epsilon positivo y finito')
    grouped = x.reshape(n, groups, c//groups, h, w)
    centered = grouped-grouped.mean(axis=(2,3,4), keepdims=True)
    inv = 1/np.sqrt(np.mean(centered**2, axis=(2,3,4), keepdims=True)+eps)
    normalized = (centered*inv).reshape(x.shape)
    return normalized*gamma[None,:,None,None]+beta[None,:,None,None], (normalized, inv, gamma.copy(), groups)


def group_backward(g, cache):
    normalized, inv, gamma, groups = cache
    n, c, h, w = g.shape
    q = (g*gamma[None,:,None,None]).reshape(n,groups,c//groups,h,w)
    z = normalized.reshape(n,groups,c//groups,h,w)
    dx = inv*(q-q.mean(axis=(2,3,4),keepdims=True)-z*(q*z).mean(axis=(2,3,4),keepdims=True))
    return dx.reshape(g.shape), np.sum(g*normalized,axis=(0,2,3)), np.sum(g,axis=(0,2,3))


def gradcheck(function, backward, args, upstream, eps_step=1e-6):
    y, cache = function(*args)
    analytic = backward(upstream, cache)
    errors = []
    for slot, value in enumerate(args):
        numeric = np.empty_like(value)
        for index in np.ndindex(value.shape):
            trial = [v.copy() for v in args]
            trial[slot][index] += eps_step
            plus = np.sum(function(*trial)[0]*upstream)
            trial[slot][index] -= 2*eps_step
            minus = np.sum(function(*trial)[0]*upstream)
            numeric[index] = (plus-minus)/(2*eps_step)
        errors.append(float(np.max(np.abs(numeric-analytic[slot]))))
    assert max(errors) < 1e-8
    return errors


if __name__ == '__main__':
    rng = np.random.default_rng(1616)
    x, g = rng.normal(size=(2,3,4)), rng.normal(size=(2,3,4))
    gamma, beta = rng.normal(size=4), rng.normal(size=4)
    print('LN errores dx, dγ, dβ:', gradcheck(lambda a,b,c: layer_forward(a,b,c,.02), layer_backward, [x,gamma,beta],g))
    print('RMS errores dx, dγ:', gradcheck(lambda a,b: rms_forward(a,b,.02), rms_backward, [x,gamma],g))
    image, gout = rng.normal(size=(2,4,2,2)), rng.normal(size=(2,4,2,2))
    gamma4, beta4 = rng.normal(size=4), rng.normal(size=4)
    for groups in (1,2,4):
        errors = gradcheck(lambda a,b,c: group_forward(a,b,c,groups,.02), group_backward, [image,gamma4,beta4],gout)
        print('GN', groups, 'grupos, errores dx, dγ, dβ:', errors)

    # GN con un grupo coincide con LN sobre C,H,W si también igualamos sus afines.
    gy, gc = group_forward(image, gamma4, beta4, 1, .02)
    flat = image.reshape(2,-1)
    aff_gamma = np.broadcast_to(gamma4[:,None,None], (4,2,2)).reshape(-1)
    aff_beta = np.broadcast_to(beta4[:,None,None], (4,2,2)).reshape(-1)
    ly, lc = layer_forward(flat, aff_gamma, aff_beta, .02)
    assert np.allclose(gy, ly.reshape(image.shape), atol=1e-12)
    dxg, dgg, dbg = group_backward(gout,gc)
    dxl, dgl, dbl = layer_backward(gout.reshape(2,-1),lc)
    assert np.allclose(dxg, dxl.reshape(image.shape), atol=1e-12)
    assert np.allclose(dgg, dgl.reshape(4,2,2).sum(axis=(1,2)), atol=1e-12)
    assert np.allclose(dbg, dbl.reshape(4,2,2).sum(axis=(1,2)), atol=1e-12)
    print('GN(1) y LN(C,H,W) coinciden al compartir afines por canal, también en backward.')

    # GN con C grupos coincide con normalizar H,W por separado para cada N,C.
    gy, _ = group_forward(image, np.ones(4), np.zeros(4), 4, .02)
    instance, _ = layer_forward(image.reshape(2,4,-1), np.ones(4), np.zeros(4), .02)
    assert np.allclose(gy,instance.reshape(image.shape),atol=1e-12)
    print('GN(C) e instance norm coinciden en estadísticas sin afines.')

    # LN: desplazamiento exacto; escalado solo aproximado cuando ε > 0.
    vector = np.array([[1.,2.,3.,6.]])
    y, cache = layer_forward(vector,np.ones(4),np.zeros(4),.1)
    shift, _ = layer_forward(vector+5,np.ones(4),np.zeros(4),.1)
    scale, _ = layer_forward(vector*2,np.ones(4),np.zeros(4),.1)
    assert np.allclose(y,shift) and np.max(np.abs(y-scale)) > .01
    variance = np.var(vector)
    assert np.allclose(np.linalg.norm(y), np.sqrt(4*variance/(variance+.1)))
    print('LN desplazamiento y radio exactos; diferencia al doblar con ε=0,1:', float(np.max(np.abs(y-scale))))
    # Dimensión uno, y caché independiente de mutaciones posteriores.
    x1, ga, be = np.array([[7.]]), np.array([2.]), np.array([.3])
    y1, cache1 = layer_forward(x1,ga,be,.01)
    dx, _, _ = layer_backward(np.array([[1.]]),cache1)
    assert np.allclose(y1,be) and np.allclose(dx,0.)
    print('Una característica: LN devuelve β y dx=0.')
    for name, fun, back, args, upstream in (
        ('LN', lambda a,b,c: layer_forward(a,b,c,.02), layer_backward,
         [x.copy(),gamma.copy(),beta.copy()], g),
        ('RMS', lambda a,b: rms_forward(a,b,.02), rms_backward,
         [x.copy(),gamma.copy()], g),
        ('GN', lambda a,b,c: group_forward(a,b,c,2,.02), group_backward,
         [image.copy(),gamma4.copy(),beta4.copy()], gout),
    ):
        result, saved = fun(*args)
        before = [value.copy() for value in back(upstream, saved)]
        for value in args: value.fill(123.)
        result.fill(456.)
        assert all(np.array_equal(a,b) for a,b in zip(before,back(upstream,saved)))
        print(name, 'caché conserva estado frente a mutaciones posteriores.')
[ ]Autograd integration and BN–LN comparisonBrowser
"""LN/GN enlazadas al motor Tensor y comparación controlada con BN.

Requiere las celdas previas del motor de m15-l09, BN de m15-l15 y las
funciones de la celda anterior. El lote total es igual; los pasos difieren.
"""
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np


def layer_tensor(x, gamma, beta):
    values, cache = layer_forward(x.data, gamma.data, beta.data)
    result = Tensor(values, (x, gamma, beta))
    def backward_op():
        dx, dg, db = layer_backward(result.grad, cache)
        x.grad += dx; gamma.grad += dg; beta.grad += db
    result._backward = backward_op
    return result


def group_tensor(x, gamma, beta, groups):
    values, cache = group_forward(x.data, gamma.data, beta.data, groups)
    result = Tensor(values, (x, gamma, beta))
    def backward_op():
        dx, dg, db = group_backward(result.grad, cache)
        x.grad += dx; gamma.grad += dg; beta.grad += db
    result._backward = backward_op
    return result


def batch_tensor(x, gamma, beta, state, training):
    values, cache, next_mean, next_var = forward(x.data, gamma.data, beta.data,
        training=training, running_mean=state[0], running_var=state[1], update=training)
    if training: state[0][:], state[1][:] = next_mean, next_var
    result = Tensor(values, (x, gamma, beta))
    def backward_op():
        dx, dg, db = backward(result.grad, cache)
        x.grad += dx; gamma.grad += dg; beta.grad += db
    result._backward = backward_op
    return result


# Confronta el enlace del grafo con las VJP independientes ya verificadas.
check_rng = np.random.default_rng(1619)
for kind in ('LN','GN'):
    x0 = check_rng.normal(size=(3,4) if kind == 'LN' else (3,4,2,2))
    g0, b0, upstream = check_rng.normal(size=4), check_rng.normal(size=4), check_rng.normal(size=x0.shape)
    x, gamma, beta = Tensor(x0), Tensor(g0), Tensor(b0)
    if kind == 'LN':
        result = layer_tensor(x,gamma,beta)
        _, cache = layer_forward(x0,g0,b0)
        expected = layer_backward(upstream,cache)
    else:
        result = group_tensor(x,gamma,beta,2)
        _, cache = group_forward(x0,g0,b0,2)
        expected = group_backward(upstream,cache)
    (result*Tensor(upstream)).sum().backward()
    error = max(float(np.max(np.abs(actual.grad-target))) for actual,target in zip((x,gamma,beta),expected))
    assert error < 1e-12
    print('Enlace Tensor',kind,'error máximo:',error)


features, labels = load_digits(return_X_y=True)
features = features/16.
train_ids, valid_ids = train_test_split(np.arange(len(labels)), test_size=.2, stratify=labels, random_state=1620)
train_x, train_y = features[train_ids], labels[train_ids]
valid_x, valid_y = features[valid_ids], labels[valid_ids]


class Network:
    def __init__(self, kind, depth=6, width=16):
        rng = np.random.default_rng(1621)
        sizes = [64]+[width]*depth+[10]
        self.w = [Tensor(rng.normal(0,np.sqrt(2/a),(a,b))) for a,b in zip(sizes[:-1],sizes[1:])]
        self.b = [Tensor(np.zeros(b)) for b in sizes[1:]]
        self.gamma = [Tensor(np.ones(width)) for _ in range(depth)]
        self.beta = [Tensor(np.zeros(width)) for _ in range(depth)]
        self.state = [[np.zeros(width),np.ones(width)] for _ in range(depth)]
        self.params = self.w+self.b+self.gamma+self.beta
        self.kind, self.depth = kind, depth

    def __call__(self, x, training):
        h = Tensor(x)
        for i in range(self.depth):
            h = h@self.w[i]+self.b[i]
            h = batch_tensor(h,self.gamma[i],self.beta[i],self.state[i],training) if self.kind == 'BN' else layer_tensor(h,self.gamma[i],self.beta[i])
            h = h.relu()
        return h@self.w[-1]+self.b[-1]

    def evaluate(self):
        scores = self(valid_x,False).data
        return float(cross_entropy(Tensor(scores),valid_y).data), float(np.mean(scores.argmax(axis=1)==valid_y))


indices = np.random.default_rng(1622).integers(0,len(train_y),size=1024)
def train(kind, batch_size, lr=.03):
    model = Network(kind)
    initial = model.evaluate()
    updates = 0
    for start in range(0,len(indices),batch_size):
        batch = indices[start:start+batch_size]
        for p in model.params: p.grad.fill(0)
        loss = cross_entropy(model(train_x[batch],True),train_y[batch])
        if not np.isfinite(loss.data): raise RuntimeError('pérdida no finita')
        loss.backward()
        if any(not np.all(np.isfinite(p.grad)) for p in model.params): raise RuntimeError('gradiente no finito')
        for p in model.params: p.data -= lr*p.grad
        updates += 1
    return initial, model.evaluate(), updates


for size in (8,32,64):
    for kind in ('BN','LN'):
        initial, final, updates = train(kind,size)
        print('lote',size,'norma',kind,'ejemplos',len(indices),'pasos',updates,
              'validación inicial',initial,'final',final)

Finite differences check operator gradients and integration with the tensor engine checks LN and GN VJPs. In trained models, BN validation uses running statistics while LN computes statistics per example. Results depend on task, initialization, and budget; figure curves should not be replaced with values chosen to produce a crossing.

Local lab: parity and cost

The next cell reproduces the figure’s Fashion-MNIST test with a short verification budget and a full budget for the reader. Official test data are reserved.

[ ]Fashion-MNIST experiment dataLocal GPU
"""Barrido de tamaños de lote y normalizaciones en Fashion-MNIST.

ORYON_VERIFY_SHORT=1 usa un ensayo reducido para verificar todo el flujo.
El tamaño de lote cambia el número de ejemplos vistos: esta comparación
mantiene igual el número de actualizaciones, no el presupuesto en ejemplos.
La comparación usa validación; el test oficial no se consulta.
"""
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 = (4096, 512) if short else (50000, 10000)
steps = 80 if short else 1200
width = 64 if short else 256
depth = 3
groups = 8
learning_rate = 0.03
batch_sizes = (2, 4, 8, 16, 32, 64, 128, 256)
seeds = (13, 29) if short else (13, 29, 47)
normalizations = ('batch', 'layer', 'group')
assert width % groups == 0

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(16160))
train_ids = split[:train_size]
validation_ids = split[train_size:train_size + validation_size]
assert not set(train_ids.tolist()).intersection(validation_ids.tolist())
train_x = (dataset.data[train_ids].reshape(train_size, -1).float() / 255).to(device)
train_y = dataset.targets[train_ids].to(device)
validation_x = (dataset.data[validation_ids].reshape(validation_size, -1).float() / 255).to(device)
validation_y = dataset.targets[validation_ids].to(device)


class Network(nn.Module):
    def __init__(self, seed, normalization):
        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)])
        if normalization == 'batch':
            self.norm = nn.ModuleList([nn.BatchNorm1d(width) for _ in range(depth)])
        elif normalization == 'layer':
            self.norm = nn.ModuleList([nn.LayerNorm(width) for _ in range(depth)])
        elif normalization == 'group':
            self.norm = nn.ModuleList([nn.GroupNorm(groups, width) for _ in range(depth)])
        else:
            raise ValueError('normalización desconocida')
        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, norm in zip(self.hidden, self.norm):
            x = torch.relu(norm(layer(x)))
        return self.output(x)


@torch.no_grad()
def evaluate(model):
    model.eval()
    losses, correct = 0.0, 0
    for offset in range(0, validation_size, 256):
        x, y = validation_x[offset:offset+256], validation_y[offset:offset+256]
        logits = model(x)
        if not torch.isfinite(logits).all():
            return None
        loss = nn.functional.cross_entropy(logits, y, reduction='sum')
        if not torch.isfinite(loss):
            return None
        losses += float(loss.item())
        correct += int((logits.argmax(1) == y).sum().item())
    return {'loss': losses / validation_size, 'accuracy': correct / validation_size}


def parity_check():
    # Parámetros afines desactivados para comparar solo las estadísticas.
    x = torch.arange(96, dtype=torch.float64, device=device).reshape(4, 8, 3) / 17
    eps = 1e-5
    grouped = x.reshape(4, 2, -1)
    mu = grouped.mean(dim=-1, keepdim=True)
    var = ((grouped-mu)**2).mean(dim=-1, keepdim=True)
    manual = ((grouped-mu)/torch.sqrt(var+eps)).reshape_as(x)
    actual = nn.GroupNorm(2, 8, eps=eps, affine=False).to(device)(x)
    layer = nn.LayerNorm((8, 3), eps=eps, elementwise_affine=False).to(device)(x)
    one_group = nn.GroupNorm(1, 8, eps=eps, affine=False).to(device)(x)
    errors = {'group_manual_max_abs': float((manual-actual).abs().max().item()),
              'one_group_layer_max_abs': float((one_group-layer).abs().max().item())}
    assert max(errors.values()) < 1e-10
    return errors


parity = parity_check()
print('Paridad GN y LN sin afines:', parity, flush=True)
records = []
for seed in seeds:
    # Comprueba que la normalización no cambia los pesos comunes iniciales.
    reference = Network(seed, 'batch')
    for kind in ('layer', 'group'):
        candidate = Network(seed, kind)
        assert all(torch.equal(a.weight, b.weight) for a, b in zip(reference.hidden, candidate.hidden))
        assert torch.equal(reference.output.weight, candidate.output.weight)
        assert torch.equal(reference.output.bias, candidate.output.bias)
    del reference, candidate
    generator = torch.Generator().manual_seed(seed + 1600)
    batches = torch.randint(train_size, (steps, max(batch_sizes)), generator=generator)
    for batch in batch_sizes:
        for kind in normalizations:
            model = Network(seed, kind).to(device)
            optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
            initial = evaluate(model)
            status = 'complete' if initial is not None else 'nonfinite_initial'
            completed = 0
            for step in range(1, steps+1):
                if status != 'complete':
                    break
                model.train()
                ids = batches[step-1, :batch].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()
                completed = step
            final = evaluate(model) if status == 'complete' else None
            if status == 'complete' and final is None:
                status = 'nonfinite_validation'
            records.append({'seed':seed, 'batch':batch, 'normalization':kind, 'status':status,
                            'steps_completed':completed, 'initial':initial, 'final':final})
            print('seed', seed, 'batch', batch, 'normalización', kind, 'estado', status,
                  'pasos', completed, 'validación', final, 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':16160,
          'train_examples':train_size, 'validation_examples':validation_size, 'steps':steps, 'width':width,
          'depth':depth, 'groups':groups, 'learning_rate':learning_rate, 'batch_sizes':list(batch_sizes),
          'seeds':list(seeds), 'normalizations':list(normalizations), 'parity':parity,
          'budget':'mismas actualizaciones por condición; a mayor lote se ven más ejemplos',
          'sampling':'con reemplazo; lotes de distinto tamaño comparten los primeros índices en cada paso',
          'notes':'Sin dropout ni weight decay; las métricas se miden en eval sobre validación disjunta; '
                  'BN usa medias móviles, LN y GN no dependen del lote; test oficial sin consultar.',
          'records':records}
target = Path(os.getenv('ORYON_NORM_OUTPUT', 'fashion-norm-sweep.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, validation_x, validation_y
if device.type == 'cuda':
    torch.cuda.empty_cache()

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

fig, axis = plt.subplots(figsize=(8, 5), constrained_layout=True)
colors = {'batch':'tab:blue', 'layer':'tab:orange', 'group':'tab:green'}
styles = {seed: style for seed, style in zip(seeds, ('-', '--', ':'))}
for seed in seeds:
    for kind in normalizations:
        selected = [r for r in records if r['seed'] == seed and r['normalization'] == kind]
        # NaN corta la línea en una ejecución fallida, sin unirla con la siguiente.
        ys = [r['final']['accuracy'] if r['final'] is not None else float('nan') for r in selected]
        axis.plot(batch_sizes, ys, color=colors[kind], linestyle=styles[seed], marker='o',
                  label=f'{kind}, semilla {seed}')
axis.set_xscale('log', base=2)
axis.set_xticks(batch_sizes, labels=[str(b) for b in batch_sizes])
axis.set_ylim(0, 1)
axis.set_xlabel('Tamaño de lote')
axis.set_ylabel('Precisión de validación en eval')
axis.set_title('Fashion-MNIST: mismas actualizaciones (' + ('ensayo corto' if short else 'laboratorio del lector') + ')')
axis.grid(alpha=.25)
axis.legend(fontsize=8)
figure_path = target.with_suffix('.png')
fig.savefig(figure_path, dpi=140)
plt.close(fig)
print('Gráfica guardada en', figure_path, flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell checks outputs and three gradients against nn.LayerNorm and nn.GroupNorm in float64 with a fixed output gradient. It then compares the GPU cost of a wide MLP with LN or GN, including forward and backward. The GPU is warmed up and synchronized, and mean time over repetitions and observed throughput are reported. Results depend on hardware, load, and shapes: repeat measurements before drawing conclusions. ORYON_VERIFY_SHORT=1 reduces shape and repetition count to check the full path.

[ ]LN and GN parity and costLocal GPU
"""Paridad NumPy/PyTorch de LN y GN, y coste sintético en GPU.

ORYON_VERIFY_SHORT=1 ejecuta una prueba pequeña. Sin esa variable se usa
un MLP ancho para el lector. Los tiempos son mediciones de esta máquina,
no propiedades universales de las capas ni un benchmark de entrenamiento real.
"""
import json
import os
from numbers import Integral
from pathlib import Path

import numpy as np
import torch
from torch import nn


def layernorm_numpy(x, gamma, beta, eps):
    """LN sobre todas las dimensiones de gamma, después del eje N."""
    x, gamma, beta = np.asarray(x), np.asarray(gamma), np.asarray(beta)
    if x.ndim < 2 or any(d < 1 for d in x.shape) or x.shape[1:] != gamma.shape or beta.shape != gamma.shape or not np.isfinite(eps) or eps <= 0:
        raise ValueError('formas incompatibles o epsilon no positivo')
    axes = tuple(range(1, x.ndim))
    center = x - x.mean(axis=axes, keepdims=True)
    inv = 1 / np.sqrt(np.mean(center**2, axis=axes, keepdims=True) + eps)
    z = center * inv
    return z*gamma + beta, (z, inv, gamma.copy(), axes)


def layernorm_backward(grad, cache):
    z, inv, gamma, axes = cache
    dz = grad * gamma
    dx = inv * (dz - dz.mean(axis=axes, keepdims=True) - z*(dz*z).mean(axis=axes, keepdims=True))
    return dx, np.sum(grad*z, axis=0), np.sum(grad, axis=0)


def groupnorm_numpy(x, gamma, beta, groups, eps):
    """GN en tensor N,C,H,W; affine por canal como nn.GroupNorm."""
    x, gamma, beta = np.asarray(x), np.asarray(gamma), np.asarray(beta)
    if (x.ndim != 4 or any(d < 1 for d in x.shape) or isinstance(groups, (bool, np.bool_))
            or not isinstance(groups, Integral) or groups <= 0 or x.shape[1] % groups
            or gamma.shape != (x.shape[1],) or beta.shape != gamma.shape or not np.isfinite(eps) or eps <= 0):
        raise ValueError('formas, grupos o epsilon inválidos')
    n, c, h, w = x.shape
    grouped = x.reshape(n, groups, c//groups, h, w)
    axes = (2, 3, 4)
    center = grouped - grouped.mean(axis=axes, keepdims=True)
    inv = 1 / np.sqrt(np.mean(center**2, axis=axes, keepdims=True) + eps)
    z = center * inv
    return z.reshape(x.shape)*gamma[None, :, None, None] + beta[None, :, None, None], (z, inv, gamma.copy(), x.shape)


def groupnorm_backward(grad, cache):
    z, inv, gamma, shape = cache
    dz = (grad * gamma[None, :, None, None]).reshape(z.shape)
    axes = (2, 3, 4)
    dx = (inv * (dz - dz.mean(axis=axes, keepdims=True) - z*(dz*z).mean(axis=axes, keepdims=True))).reshape(shape)
    return dx, np.sum(grad*z.reshape(shape), axis=(0,2,3)), np.sum(grad, axis=(0,2,3))


def parity():
    generator = np.random.default_rng(1616)
    records = []
    for invalid_groups in (0, 2.0, True, 3):
        try:
            groupnorm_numpy(np.ones((2, 4, 2, 3)), np.ones(4), np.zeros(4), invalid_groups, .03)
        except ValueError:
            pass
        else:
            raise AssertionError('Grupos inválidos no rechazados')
    for invalid_eps in (0., float('nan')):
        try:
            layernorm_numpy(np.ones((2, 4)), np.ones(4), np.zeros(4), invalid_eps)
        except ValueError:
            pass
        else:
            raise AssertionError('Epsilon inválido no rechazado')
    for shape, groups in [((2, 6), None), ((2, 4, 2, 3), None), ((2, 4, 2, 3), 1),
                          ((2, 4, 2, 3), 2), ((2, 4, 2, 3), 4)]:
        for constant in (False, True):
            x = np.full(shape, 2.) if constant else generator.normal(size=shape)
            gamma_shape = shape[1:] if groups is None else (shape[1],)
            gamma = generator.normal(size=gamma_shape)
            beta = generator.normal(size=gamma_shape)
            upstream = generator.normal(size=shape)
            eps = .03
            if groups is None:
                y, cache = layernorm_numpy(x, gamma, beta, eps)
                dx, dg, db = layernorm_backward(upstream, cache)
                layer = nn.LayerNorm(gamma_shape, eps=eps, dtype=torch.float64)
                kind = 'LN'
            else:
                y, cache = groupnorm_numpy(x, gamma, beta, groups, eps)
                dx, dg, db = groupnorm_backward(upstream, cache)
                layer = nn.GroupNorm(groups, shape[1], eps=eps, dtype=torch.float64)
                kind = 'GN'
            mutable_gamma = gamma.copy()
            if groups is None:
                _, snapshot = layernorm_numpy(x, mutable_gamma, beta, eps)
                mutable_gamma.fill(99.)
                preserved = layernorm_backward(upstream, snapshot)
            else:
                _, snapshot = groupnorm_numpy(x, mutable_gamma, beta, groups, eps)
                mutable_gamma.fill(99.)
                preserved = groupnorm_backward(upstream, snapshot)
            assert all(np.allclose(a, b, rtol=0, atol=0) for a, b in zip(preserved, (dx, dg, db)))
            with torch.no_grad():
                layer.weight.copy_(torch.from_numpy(gamma))
                layer.bias.copy_(torch.from_numpy(beta))
            tx = torch.tensor(x, dtype=torch.float64, requires_grad=True)
            ty = layer(tx)
            (ty * torch.from_numpy(upstream)).sum().backward()
            errors = {name: float(np.max(np.abs(np_value - th_value.detach().numpy())))
                      for name, np_value, th_value in [('forward', y, ty), ('dx', dx, tx.grad),
                                                     ('dgamma', dg, layer.weight.grad), ('dbeta', db, layer.bias.grad)]}
            assert max(errors.values()) < 1e-10, (kind, shape, groups, errors)
            # Diferencias finitas del backward en un elemento de cada variable.
            def objective(a, b, c):
                if groups is None: value, _ = layernorm_numpy(a, b, c, eps)
                else: value, _ = groupnorm_numpy(a, b, c, groups, eps)
                return float(np.sum(value * upstream))
            for slot, (array, analytic) in enumerate(((x, dx), (gamma, dg), (beta, db))):
                index = (0,) * array.ndim
                args = [x.copy(), gamma.copy(), beta.copy()]
                args[slot][index] += 1e-6
                plus = objective(*args)
                args[slot][index] -= 2e-6
                minus = objective(*args)
                numerical = (plus - minus) / 2e-6
                assert np.isclose(numerical, analytic[index], rtol=1e-6, atol=1e-7)
            records.append(dict(kind=kind, shape=shape, groups=groups, constant=constant, max_error=errors))
    return records


class MLP(nn.Module):
    def __init__(self, width, depth, groupnorm):
        super().__init__()
        self.layers = nn.ModuleList([nn.Linear(width, width, bias=False) for _ in range(depth)])
        self.norms = nn.ModuleList([nn.GroupNorm(8, width) if groupnorm else nn.LayerNorm(width) for _ in range(depth)])

    def forward(self, x):
        for linear, norm in zip(self.layers, self.norms):
            x = torch.relu(norm(linear(x)))
        return x


def benchmark(device, short):
    if device.type != 'cuda':
        return {'status': 'skipped', 'reason': 'CUDA no disponible; no se informa coste GPU'}
    width, depth, batch, warmup, repetitions = (256, 3, 32, 3, 10) if short else (2048, 6, 256, 20, 100)
    results = []
    for kind in ('LN', 'GN'):
        torch.manual_seed(1616)
        torch.cuda.manual_seed_all(1616)
        model = MLP(width, depth, kind == 'GN').to(device)
        x = torch.randn(batch, width, device=device)
        def iteration():
            model.zero_grad(set_to_none=True)
            y = model(x)
            loss = y.square().mean()
            loss.backward()
        for _ in range(warmup):
            iteration()
        torch.cuda.synchronize(device)
        torch.cuda.reset_peak_memory_stats(device)
        start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
        start.record()
        for _ in range(repetitions):
            iteration()
        end.record()
        end.synchronize()
        elapsed_ms = start.elapsed_time(end)
        if not np.isfinite(elapsed_ms) or elapsed_ms <= 0:
            raise RuntimeError('Cronometraje CUDA inválido')
        results.append({'normalization': kind, 'mean_gpu_ms_forward_backward': elapsed_ms/repetitions,
                        'examples_per_second': batch*repetitions*1000/elapsed_ms,
                        'peak_allocated_bytes': torch.cuda.max_memory_allocated(device)})
        del model, x, start, end
        torch.cuda.empty_cache()
    return {'status':'complete', 'width':width, 'depth':depth, 'batch':batch, 'warmup':warmup,
            'repetitions':repetitions, 'dtype':'float32', 'groups':8, 'results':results,
            'scope':'MLP sintético, forward + backward, sin actualización del optimizador ni transferencia de datos',
            'timing':'eventos CUDA en el flujo actual, sincronizados; una única ejecución',
            'caveat':'Los tiempos dependen de hardware, software, forma y carga compartida; repetir y comparar distribuciones.'}


def main():
    torch.set_num_threads(1)
    short = os.getenv('ORYON_VERIFY_SHORT') == '1'
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    errors = parity()
    print('Paridad float64: LN y GN, 10 casos, forward y tres gradientes comprobados.', flush=True)
    print('Error máximo:', max(max(record['max_error'].values()) for record in errors), flush=True)
    timing = benchmark(device, short)
    print('Benchmark:', json.dumps(timing, ensure_ascii=True), flush=True)
    output = {'verification': 'short' if short else 'full', 'torch': torch.__version__,
              'device': str(device), 'device_name': torch.cuda.get_device_name(device) if device.type == 'cuda' else None,
              'parity': errors, 'benchmark': timing}
    target = Path(os.getenv('ORYON_LN_GN_OUTPUT', 'layernorm-groupnorm-results.json'))
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(output, indent=2, ensure_ascii=False, allow_nan=False), encoding='utf-8')
    print('Datos guardados en', target, flush=True)
    if device.type == 'cuda':
        torch.cuda.empty_cache()


if __name__ == '__main__':
    main()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

For sequences, Ba and colleagues studied layer norm with per-step statistics and the same rule in training and inference. In stylization networks, Ulyanov and colleagues observed qualitative improvements using instance norm in both modes. These observations guide tests: instance norm is not always best for images, and batch-independent statistics do not alone determine generalization.

Exercises

ProofWhich transformations does layer norm preserve?
Prove: Determine which invariances are exact and which require an assumption about ε.
0
Let x be a vector with positive variance and LN without affine parameters. Each example's d features are normalized.

Step 1 of 3. What happens when b is added to all features?

CodeBackward across features
Implement layernorm_backward(x, gamma, g, eps) for x and g of shape (N,D), gamma of shape (D,), and positive eps. Return dx, dgamma, and dbeta for y=gamma·(x−mean)/√(variance+eps)+beta and L=Σ(g·y). Use variance with divisor D; do not modify inputs.
import numpy as np

def layernorm_backward(x, gamma, g, eps):
  pass
Shift+Enter to run
QuizChoosing for the task
Which starting points are most defensible for segmentation with two images per GPU, an MLP with a large batch, a causal transformer, and fast style transfer?
NumericNormalizing four features
Apply layer norm without affine parameters to (1,2,3,6), using variance with divisor 4 and negligible ε. What is the first component?