Module contents
Lesson 14 of 22Core 85 min

Initialization: breaking symmetry and preserving variance

Derive forward and backward moment propagation and the Xavier, He, LeCun and orthogonal initializations. Examine symmetry breaking, dynamical isometry and practical output-layer choices.

After this lesson you can

  • Explain and demonstrate when symmetric initialization prevents neurons from differentiating.
  • Derive preactivation moment propagation and Xavier and He scaling conditions.
  • Implement Xavier, He, LeCun and orthogonal initialization and examine 50-layer signal propagation.
  • Choose output-layer and bias initialization with the expected initial loss in mind.
  • Explain norm preservation in orthogonal linear networks and limitations in nonlinear networks.

Before you start

Before the first step

Two networks with identical architecture and data can start in very different regimes. If signals attenuate, early layers receive weak corrections; if they grow too much, activations can saturate or loss become non-finite. The previous lesson showed the product of Jacobians. Now we choose an initial distribution that makes the first forward and backward paths reasonable, without confusing an average result with a guarantee for each network.

InteractiveSignal through 50 layers

A fixed batch of 48 vectors passes through 50 layers of width 16, without biases. The same initial random numbers are used when controls change. The network is not trained.

Calculating propagation…

Standard normal inputs use seed 1414 and Gaussian matrices seed 1415. He uses deviation √(2/16); Xavier and LeCun use 1/√16, equal here because layers are square. Orthogonal initialization orthonormalizes Gaussian rows with two passes and uses gain 1. Weights are then multiplied by the chosen scale.

In the idealized model, He preserves the second moment of ReLU preactivations in expectation under symmetry and independence, not the observed deviation of every layer or finite realization. ReLU mean is positive, so its variance is not its second moment; tanh and sigmoid can saturate and orthogonality alone does not prevent that loss.

1.0
Choose activation, initializer, and scale. Compare preactivation second moment with activation standard deviation and their histograms.

This figure computes a finite realization: square matrices, one fixed batch, and one seed. Xavier and LeCun coincide here because input and output widths match. A scale preserving a moment in expectation under an idealized model need not keep this particular trajectory flat; spread can accumulate and an activation can introduce a nonzero mean.

Breaking symmetry

Symmetry breaking allows neurons in the same layer to receive different corrections. Consider two units hi=ϕ(wiTx+bi)h_i=\phi(w_i^\mathsf Tx+b_i) and an output v1h1+v2h2+cv_1h_1+v_2h_2+c. If w1=w2w_1=w_2, b1=b2b_1=b_2, and v1=v2v_1=v_2, both activations coincide for every input. By the chain rule their incoming gradients are equal, as are gradients of outgoing connections. With deterministic SGD, identical initial momentum states, and identical treatment, equality is preserved by induction after each step.

Equal incoming weights alone are insufficient: if v1≠v2v_1\neq v_2, the backpropagation factor can differ from the first step. Different optimizer states or independent dropout masks can also break symmetry. Adding noise distinguishes units but does not guarantee specialization or growing distance for every task.

InteractiveThe identical-neuron trap

Two tanh neurons form a 1 → 2 → 1 network trained on five points of y = x². The symmetric setting starts with w₁ = w₂ = 1, b₁ = b₂ = 0.4 and v₁ = v₂ = 0.8; the others change one initial condition. SGD uses momentum 0.8 and rate 0.05, without noise during training.

step 200 / 200
  • Neuron 1
  • Neuron 2
Preparing charts…
Horizontal axis: optimizer steps

Curves are computed with mean loss ½·E[(ŷ − y)²]. The perturbation adds 0.05 to w₁; different outputs add 0.2 to v₁; different momentum starts with state 0.2 for w₁ and zero for w₂. Other parameters and states are equal. If incoming weights, biases, outgoing weights, and states are identical, the same gradient preserves symmetry; changing one condition can break it.

With perturbation, the initial difference grows, but another task or initialization can make it decrease. The lab reproduces the trajectories and checks their gradient with finite differences.

Input-weight difference0.0000
Output-weight difference0.0000
Input-gradient difference0.0000
Input-momentum difference0.0000
Batch loss0.08497
Compare complete equality, perturbation, different outgoing connections, and different momentum states on the same problem.

What is preserved in the forward pass

For a layer with ninn_{\mathrm{in}} inputs, zi=∑jWijhj+biz_i=\sum_j W_{ij}h_j+b_i. Assume zero biases, zero-mean weights independent of one another and of their input activations, with common variance vv. If activations have the same second moment qh=E[hj2]<∞q_h=\mathbb E[h_j^2]<\infty, cross terms vanish when averaging over weights and

E[zi]=0,Var⁡(zi)=ninv qh.\mathbb E[z_i]=0,\qquad \operatorname{Var}(z_i)=n_{\mathrm{in}}v\,q_h.

This moment propagation equation does not require zero-mean activations because it uses E[h2]\mathbb E[h^2], not Var⁡(h)\operatorname{Var}(h). Independence concerns the new matrix and its incoming signal; after training, weights and signals may be correlated. This is also an average over initializations and data under these assumptions, not a promise for a fixed matrix.

If zz has a symmetric distribution and finite second moment, E[ReLU⁡(z)2]=E[z2]/2\mathbb E[\operatorname{ReLU}(z)^2]=\mathbb E[z^2]/2. Thus, under the homogeneous-layer approximation, choosing v=2/ninv=2/n_{\mathrm{in}} preserves preactivation second moment from layer to layer. This is the He condition for ReLU; the corresponding normal standard deviation is 2/nin\sqrt{2/n_{\mathrm{in}}}. If zz is centered Gaussian with variance qq, output has mean q/(2π)\sqrt{q/(2\pi)} and variance q(1/2−1/(2π))q(1/2-1/(2\pi)), not q/2q/2. One half corresponds to the second moment.

With an approximately linear activation and centered inputs, qh≈Var⁡(z)q_h\approx\operatorname{Var}(z), and v≈1/ninv\approx1/n_{\mathrm{in}} preserves forward scale. This is LeCun’s rule in this idealized case. Tanh is approximately linear only near zero; sigmoid has nonzero mean and saturation, so neither formula ensures exact stability at every scale.

The backward direction and Xavier

Backpropagation introduces WTW^\mathsf T and one derivative per unit. Under a mean-field approximation treating weights, error signal, and activation gates as sufficiently independent, gradient variance is multiplied approximately by noutv E[ϕ′(z)2]n_{\mathrm{out}}v\,\mathbb E[\phi'(z)^2]. Independence is not exact in a general network: the gate depends on its preactivations and error comes from the same network.

For an almost linear activation, preserving forward scale suggests v=1/ninv=1/n_{\mathrm{in}} and preserving backward scale suggests v=1/noutv=1/n_{\mathrm{out}}. If sizes differ, both equalities cannot hold with the same variance. Xavier or Glorot takes the compromise

v=2nin+nout,Wij∼U ⁣[−6nin+nout,6nin+nout],v=\frac{2}{n_{\mathrm{in}}+n_{\mathrm{out}}},\qquad W_{ij}\sim U\!\left[-\sqrt{\frac{6}{n_{\mathrm{in}}+n_{\mathrm{out}}}}, \sqrt{\frac{6}{n_{\mathrm{in}}+n_{\mathrm{out}}}}\right],

because a symmetric uniform distribution with limit aa has variance a2/3a^2/3. It matches both linear conditions when sizes are equal. For square ReLU layers, Xavier has variance 1/n1/n and the idealized model halves the second moment per layer; this does not imply every realization or gradient falls by exactly that factor. Glorot and Bengio analyze propagation and propose the compromise; He and colleagues derive the scale adapted to rectifiers.

Orthogonality and isometry

A square matrix QQ with QTQ=IQ^\mathsf TQ=I exactly preserves ∥Qx∥2=∥x∥2\|Qx\|_2=\|x\|_2 and also preserves norm during backpropagation. A product of square orthogonal matrices remains orthogonal. A rectangular matrix with orthonormal columns preserves norms of all input vectors under the column convention; if it has only orthonormal rows, it can discard null-space components. With gain gg, preserved norms are multiplied by ∣g∣|g|.

Orthogonal initialization uses QR of a Gaussian matrix and sign correction on the diagonal of RR; the cell and exercise cover both rectangular shapes. In a nonlinear network each Jacobian includes activation derivatives: orthogonality of WW does not imply the complete product is an isometry. Pennington and colleagues study that spectrum in specific regimes; for ReLU, even with critical orthogonal weights, they find the spectrum widens with depth. The previous lesson’s figure lets you inspect the product, not merely each isolated matrix.

Preparing the output layer

Output initialization controls logits before learning. If the CC logits are equal for each example, softmax assigns 1/C1/C and cross-entropy is log⁡C\log C: with ten classes, log⁡10≈2,302585\log 10\approx2{,}302585. A common constant across logits does not change softmax; scaling one class bias can. If labels have positive prior πc\pi_c and a constant prediction equal to that prior is desired, use bc=log⁡πc+C0b_c=\log\pi_c+C_0. Expected loss under that prior is −∑cπclog⁡πc-\sum_c\pi_c\log\pi_c, equal to log⁡C\log C only for equiprobable classes.

InteractiveInitial loss under control

Explicit ten-class model: zᵣ꜀ = scale · xᵣ · w꜀ + κ log(π꜀) + b, with xᵣ = (2r − 9)/9 and w꜀ = (2c − 9)/3. π is the selected prior and b is added equally to every logit.

Prior π, classes 0 to 9: 0.30 · 0.20 · 0.15 · 0.10 · 0.07 · 0.05 · 0.04 · 0.04 · 0.03 · 0.02.

Probabilities for input r = 5

Each bar is a class; height uses a 0–100% scale. Probabilities: 10.0 % · 10.0 % · 10.0 % · 10.0 % · 10.0 % · 10.0 % · 10.0 % · 10.0 % · 10.0 % · 10.0 %.

Histogram of initial probabilities

Ten equal-width intervals; the tallest bar contains 100 of 100 probabilities. At a boundary, the 10⁻¹² tolerance corrects rounding. The distribution includes all ten classes for each of the ten inputs.

The dataset combines each of ten inputs with classes of frequencies π, so input and label are independent. Loss averages −log p(true class); predicted entropy averages −Σp log p. They are different quantities. This is a synthetic model, not a training result.

With zero scale and κ = 0, prediction is uniform and loss is ln 10. With zero scale and κ = 1, it predicts π and loss is H(π). A common bias cancels in softmax: changing probabilities requires differences between classes. If π is uniform, κ log(π) is also a common bias.

Class distribution
0.0
0.00
0
5
Mean label loss2.3026
Mean predicted entropy2.3026
ln 102.3026
Prior entropy1.9748
Mean true-class probability10.0 %
Compare scales, prior, and biases in an explicit ten-class model. Common bias is a control: it does not change probabilities.

Setting the output matrix exactly to zero gives equal logits if biases are also equal, but the gradient toward earlier layers is zero on that first step. A small nonzero output allows signal to reach them from the start. The decision depends on task and prior: high initial loss can suggest excessive logits but does not by itself prove initialization is wrong.

Practice and diagnosis

In torch.nn.init, kaiming_normal_ accepts mode='fan_in' or mode='fan_out'; check the matrix shape convention and the activation actually applied. Default nn.Linear uses kaiming_uniform_ with a=5a=\sqrt5, equivalent to U(−1/nin,1/nin)U(-1/\sqrt{n_{\mathrm{in}}},1/\sqrt{n_{\mathrm{in}}}) for its weights. Its variance is 1/(3nin)1/(3n_{\mathrm{in}}): not the He variance for ReLU. For input width 512, the corresponding standard deviation is approximately 0.02552 versus 0.0625 for He normal.

LSUV starts with orthogonal weights and adjusts layer by layer using minibatch statistics. Mishkin and Matas report that adjustment required one to five iterations in their experiments and study tolerances between 0.01 and 0.1. This is data-dependent initial calibration, not equivalent to keeping batch normalization active during training. Normalization can relieve scale problems but does not guarantee good training with every initialization.

Lab from scratch: fifty layers

Build Xavier, He, LeCun, and orthogonal initializations with NumPy and propagate a batch through 50 layers. The convention is WW of shape (fan_in, fan_out) and row vectors. The terminal backpropagation direction is fixed and does not come from a loss: we measure the Jacobian response, not classifier quality. Each combination uses the same initial seed, and results are sample moments from one realization.

[ ]Moments across 50 layersBrowser
"""Inicializadores y medición en una red de 50 capas, compatible con Pyodide.

Convención de forma: (fan_in, fan_out), vectores fila y z = h @ W.
Los momentos son muestrales, no garantías para toda realización finita.
"""
import numpy as np


def orthogonal_init(shape, gain, generator):
    fan_in, fan_out = shape
    if fan_in < 1 or fan_out < 1 or not np.isfinite(gain):
        raise ValueError('forma o ganancia inválida')
    matrix = generator.normal(size=(max(fan_in, fan_out), min(fan_in, fan_out)))
    q, r = np.linalg.qr(matrix, mode='reduced')
    q *= np.where(np.diag(r) < 0, -1., 1.)
    return gain * (q if fan_in >= fan_out else q.T)


def initialize(shape, kind, generator):
    fan_in, fan_out = shape
    if min(shape) < 1: raise ValueError('forma vacía')
    if kind == 'xavier': std = np.sqrt(2. / (fan_in + fan_out))
    elif kind == 'he': std = np.sqrt(2. / fan_in)
    elif kind == 'lecun': std = np.sqrt(1. / fan_in)
    elif kind == 'ortogonal': return orthogonal_init(shape, 1., generator)
    else: raise ValueError('inicializador desconocido')
    return generator.normal(0., std, size=shape)


def activate(z, kind):
    if kind == 'lineal': return z, np.ones_like(z)
    if kind == 'tanh':
        a = np.tanh(z)
        return a, 1.-a*a
    if kind == 'relu': return np.maximum(0., z), (z > 0).astype(float)
    if kind == 'sigmoide':
        a = np.exp(-np.logaddexp(0., -z))
        return a, a*(1.-a)
    raise ValueError('activación desconocida')


def experiment(activation, initializer, width=16, batch=32, depth=50):
    generator = np.random.default_rng(1401)
    data_rng = np.random.default_rng(1402)
    h = data_rng.normal(size=(batch, width))
    # Misma dirección terminal para todas las combinaciones, no un gradiente de pérdida.
    terminal = data_rng.normal(size=(batch, width))
    terminal /= np.sqrt(np.mean(terminal*terminal))
    layers, moments = [], []
    for layer in range(1, depth+1):
        w = initialize((width, width), initializer, generator)
        z = h @ w
        h, derivative = activate(z, activation)
        layers.append((w, derivative))
        moments.append({'layer': layer, 'z_mean': float(z.mean()),
                        'z_second_moment': float(np.mean(z*z)),
                        'activation_mean': float(h.mean()), 'activation_std': float(h.std())})
    gradient = terminal
    gradient_rms = [0.]*(depth+1)
    gradient_rms[-1] = float(np.sqrt(np.mean(gradient*gradient)))
    for i in range(depth-1, -1, -1):
        w, derivative = layers[i]
        gradient = (gradient*derivative) @ w.T
        gradient_rms[i] = float(np.sqrt(np.mean(gradient*gradient)))
    assert np.isfinite(gradient).all() and all(np.isfinite(x) for x in gradient_rms)
    return moments, gradient_rms


# Comprobaciones independientes sobre formas rectangulares y escala esperada.
test_rng = np.random.default_rng(1403)
for shape in ((7, 3), (3, 7), (4, 4)):
    q = orthogonal_init(shape, 1.5, test_rng)
    gram = q.T @ q if shape[0] >= shape[1] else q @ q.T
    assert np.max(np.abs(gram-2.25*np.eye(min(shape)))) < 1e-12
big = initialize((512, 256), 'he', np.random.default_rng(1404))
expected = np.sqrt(2/512)
assert abs(big.std()/expected-1) < .02
print('He esperado y medido:', expected, float(big.std()))
print('ln 10:', np.log(10), 'desviación predeterminada Linear fan_in=512:', 1/np.sqrt(3*512))
print('QR rectangular: columnas o filas ortogonales, gain 1,5: comprobado')

# VJP independiente en una red tanh pequeña mediante diferencias centrales.
check_rng = np.random.default_rng(1405)
check_weights = [initialize((4, 4), 'xavier', check_rng) for _ in range(3)]
check_x, check_terminal = check_rng.normal(size=(1,4)), check_rng.normal(size=(1,4))
def evaluate_tanh(x):
    for w in check_weights: x = np.tanh(x @ w)
    return x
saved = []
h = check_x.copy()
for w in check_weights:
    h = np.tanh(h @ w); saved.append(h)
gradient = check_terminal.copy()
for w, a in zip(reversed(check_weights), reversed(saved)):
    gradient = (gradient*(1-a*a)) @ w.T
epsilon = 1e-6
direction = check_rng.normal(size=(1,4))
numerical = np.sum(check_terminal * (evaluate_tanh(check_x+epsilon*direction)-
                                    evaluate_tanh(check_x-epsilon*direction))) / (2*epsilon)
error = abs(float(np.sum(gradient*direction))-float(numerical))
assert error < 1e-8
print('Error VJP frente a diferencia finita:', error)

results = {}
for activation in ('lineal', 'tanh', 'relu', 'sigmoide'):
    for scheme in ('xavier', 'he', 'lecun', 'ortogonal'):
        moments, backward = experiment(activation, scheme)
        results[(activation, scheme)] = (moments, backward)
        first, last = moments[0], moments[-1]
        print(activation, scheme, 'std activaciones capas 1 y 50',
              f"{first['activation_std']:.4e}", f"{last['activation_std']:.4e}",
              'RMS gradiente entrada', f'{backward[0]:.4e}')

# Ortogonal cuadrada + lineal: preserva exactamente la norma matricial hacia atrás.
linear_backward = results[('lineal', 'ortogonal')][1]
assert max(abs(x-1.) for x in linear_backward) < 1e-12
print('Error máximo de RMS hacia atrás, lineal ortogonal:',
      max(abs(x-1.) for x in linear_backward))

The cell shows that a square orthogonal matrix and linear activation preserve backward norm up to numerical error. For ReLU with He in a narrow network, observed statistics can deviate greatly from the theoretical average. Compare histograms and repeat with greater width or more seeds before concluding a formula failed.

Reproducing symmetry

This experiment calculates all trajectories in the figure and checks their gradients with finite differences. Each neuron receives the same five synthetic points and the optimizer has explicit momentum.

[ ]Identical-neuron trajectoriesBrowser
"""MLP 1→2→1 con tanh, pérdida MSE media y SGD con momentum explícito.

Todos los experimentos usan los mismos cinco puntos y la misma tasa. Se
comparan igualdad completa, perturbación de entrada, peso de salida desigual
y estado de momentum desigual. No usa aleatoriedad ni datos externos.
"""
import json
from pathlib import Path
import numpy as np

X = np.array([-1., -.5, 0., .5, 1.])
Y = X**2
ETA = .05
MOMENTUM = .8
STEPS = 200


def loss_gradient(p):
    # p = [w1, w2, b1, b2, v1, v2, c]
    w, b, v, c = p[:2], p[2:4], p[4:6], p[6]
    h = np.tanh(X[:, None]*w + b)
    prediction = h @ v + c
    error = prediction-Y
    loss = .5*np.mean(error**2)
    d = error[:, None] * v * (1-h*h) / len(X)
    grad = np.r_[np.sum(d*X[:, None], axis=0), np.sum(d, axis=0),
                 np.mean(error[:, None]*h, axis=0), np.mean(error)]
    return float(loss), grad


def trajectory(case):
    p = np.array([1., 1., .4, .4, .8, .8, 0.])
    momentum = np.zeros(7)
    if case == 'ruido_entrada': p[0] += .05
    elif case == 'salidas_distintas': p[4] += .2
    elif case == 'momento_distinto': momentum[0] = .2
    elif case != 'simetrica': raise ValueError('caso desconocido')
    rows = []
    for step in range(STEPS+1):
        loss, g = loss_gradient(p)
        rows.append({'step':step, 'loss':loss, 'weights':p.tolist(),
                     'momentum':momentum.tolist(), 'gradient':g.tolist()})
        if step < STEPS:
            momentum = MOMENTUM*momentum + g
            p = p - ETA*momentum
    return rows


def validate():
    p = np.array([.4, .45, .2, .17, .8, .5, .1])
    eps = 1e-6
    _, grad = loss_gradient(p)
    basis = np.eye(len(p))
    numerical = np.array([(loss_gradient(p+eps*e)[0]-loss_gradient(p-eps*e)[0])/(2*eps) for e in basis])
    error = float(np.max(np.abs(numerical-grad)))
    assert error < 1e-9
    records = {name: trajectory(name) for name in ('simetrica', 'ruido_entrada', 'salidas_distintas', 'momento_distinto')}
    for row in records['simetrica']:
        for vals in (row['weights'], row['momentum'], row['gradient']):
            assert vals[0] == vals[1] and vals[2] == vals[3] and vals[4] == vals[5]
    for name in ('ruido_entrada', 'salidas_distintas', 'momento_distinto'):
        assert abs(records[name][1]['weights'][0]-records[name][1]['weights'][1]) > 1e-8
    return error, records


if __name__ == '__main__':
    error, records = validate()
    path = Path('symmetry-prototype.json')
    path.write_text(json.dumps({'x':X.tolist(),'y':Y.tolist(),'eta':ETA,'momentum':MOMENTUM,
                                'finite_difference_max_error':error,'records':records},
                               ensure_ascii=False, indent=2), encoding='utf-8')
    print('Error máximo por diferencias finitas:', error)
    for name, rows in records.items():
        print(name, 'diferencia inicial', abs(rows[0]['weights'][0]-rows[0]['weights'][1]),
              'diferencia paso 1', abs(rows[1]['weights'][0]-rows[1]['weights'][1]),
              'diferencia paso 200', abs(rows[-1]['weights'][0]-rows[-1]['weights'][1]),
              'pérdida final', rows[-1]['loss'])

Local lab: initialization and training

On Fashion-MNIST, a deep network compares He at half and double scale with default nn.Linear values. All conditions use the same splits and minibatch sequences per seed; validation loss and gradient norms are recorded. Official test data are reserved. Short mode checks implementation and normal mode provides the complete experiment to the reader.

In the short check, with two seeds and 120 steps, He at scale 1 ends with validation losses 0.8754 and 0.8694; scale 0.5 ends at 2.3014 and 2.3008. Scale 2 produces non-finite loss at steps 4 and 5. The default configuration ends at 2.3040 and 2.3027. Here the default also includes its initial biases and output is common to all conditions. These observations describe one architecture and budget; they do not prove one rule always wins.

[ ]Initialization on Fashion-MNISTLocal GPU
"""Comparación reproducible de escalas de He en Fashion-MNIST.

Con ORYON_VERIFY_SHORT=1 ejecuta un ensayo reducido para verificar el flujo.
Sin esa variable, prepara el presupuesto destinado al lector; no se ejecuta aquí.
La validación se reserva para comparar configuraciones; no se 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)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short = os.getenv('ORYON_VERIFY_SHORT') == '1'
train_size, valid_size = (4096, 1024) if short else (50000, 10000)
steps = 120 if short else 5000
batch_size = 64 if short else 128
width = 96 if short else 256
depth = 8
learning_rate = 0.01
scales = ('default', 0.5, 1.0, 2.0)
seeds = (11, 29) if short else (11, 29, 47)
eval_every = 10 if short else 100

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(14140))
train_ids = split[:train_size]
valid_ids = split[train_size:train_size + valid_size]
assert not set(train_ids.tolist()).intersection(valid_ids.tolist())
train_x = (dataset.data[train_ids].reshape(train_size, -1).float() / 255).to(device)
train_y = dataset.targets[train_ids].to(device)
valid_x = (dataset.data[valid_ids].reshape(valid_size, -1).float() / 255).to(device)
valid_y = dataset.targets[valid_ids].to(device)


class Network(nn.Module):
    def __init__(self, seed, scale):
        super().__init__()
        torch.manual_seed(seed)
        self.hidden = nn.ModuleList()
        size = 784
        for _ in range(depth):
            self.hidden.append(nn.Linear(size, width))
            size = width
        self.output = nn.Linear(width, 10)
        defaults = [(layer.weight.detach().clone(), layer.bias.detach().clone()) for layer in self.hidden]
        # Idénticos números de partida en las tres escalas: solo cambia el
        # multiplicador de las matrices ocultas. Para default se ejecuta la
        # misma secuencia aleatoria antes de restaurar los parámetros originales.
        for layer in self.hidden:
            nn.init.kaiming_normal_(layer.weight, mode='fan_in', nonlinearity='relu')
            with torch.no_grad():
                layer.weight.mul_(1.0 if scale == 'default' else scale)
                layer.bias.zero_()
        nn.init.xavier_normal_(self.output.weight)
        nn.init.zeros_(self.output.bias)
        if scale == 'default':
            with torch.no_grad():
                for layer, (weight, bias) in zip(self.hidden, defaults):
                    layer.weight.copy_(weight)
                    layer.bias.copy_(bias)

    def forward(self, x):
        for layer in self.hidden:
            x = torch.relu(layer(x))
        return self.output(x)


def check_initialization(seed):
    reference = Network(seed, 1.0)
    default = Network(seed, 'default')
    for scale in (0.5, 2.0, 'default'):
        candidate = Network(seed, scale)
        assert torch.equal(candidate.output.weight, reference.output.weight)
        assert torch.equal(candidate.output.bias, reference.output.bias)
        if scale != 'default':
            for target, base in zip(candidate.hidden, reference.hidden):
                assert torch.equal(target.weight, base.weight * scale)
                assert torch.count_nonzero(target.bias) == 0
    # Reconstruye el orden original de las capas para contrastar los defaults.
    torch.manual_seed(seed)
    original = []
    in_size = 784
    for _ in range(depth):
        original.append(nn.Linear(in_size, width))
        in_size = width
    nn.Linear(width, 10)
    for restored, layer in zip(default.hidden, original):
        assert torch.equal(restored.weight, layer.weight)
        assert torch.equal(restored.bias, layer.bias)


@torch.no_grad()
def evaluate(model):
    model.eval()
    logits = model(valid_x)
    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())}


records = []
for seed in seeds:
    check_initialization(seed)
    batch_rng = torch.Generator().manual_seed(seed + 900)
    batches = torch.randint(train_size, (steps, batch_size), generator=batch_rng)
    for scale in scales:
        model = Network(seed, scale).to(device)
        optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
        initial = evaluate(model)
        points = [{'step': 0, **initial}] if initial else []
        gradient_points = []
        status = 'complete' if initial is not None else 'nonfinite_initial'
        for step in range(1, steps + 1):
            if status != 'complete':
                break
            model.train()
            idx = batches[step - 1].to(device)
            optimizer.zero_grad(set_to_none=True)
            loss = nn.functional.cross_entropy(model(train_x[idx]), train_y[idx])
            if not torch.isfinite(loss):
                status = 'nonfinite_loss'
                break
            loss.backward()
            gradients = [layer.weight.grad for layer in model.hidden]
            if not all(p.grad is None or torch.isfinite(p.grad).all() for p in model.parameters()):
                status = 'nonfinite_gradient'
                break
            first_grad = float(gradients[0].double().norm().item())
            last_grad = float(gradients[-1].double().norm().item())
            if not math.isfinite(first_grad) or not math.isfinite(last_grad):
                status = 'nonfinite_gradient_norm'
                break
            gradient_points.append({'step': step, 'first': first_grad, 'last': last_grad})
            optimizer.step()
            if step == 1 or step % eval_every == 0 or step == steps:
                validation = evaluate(model)
                if validation is None:
                    status = 'nonfinite_validation'
                    break
                points.append({'step': step, **validation,
                               'train_batch_loss_before_update': float(loss.item()),
                               'first_hidden_gradient_norm': first_grad,
                               'last_hidden_gradient_norm': last_grad})
        records.append({'seed': seed, 'scale': scale, 'status': status,
                        'last_attempted_step': step if initial is not None else 0,
                        'points': points, 'gradient_points': gradient_points})
        print(f'seed={seed} scale={scale} status={status} step={records[-1]["last_attempted_step"]} '
              f'initial={initial} final={points[-1] if points else None}', flush=True)
        del model, optimizer
        if device.type == 'cuda':
            torch.cuda.empty_cache()

output = {
    'source': 'https://github.com/zalandoresearch/fashion-mnist',
    'mode': 'short' if short else 'reader', 'device': str(device),
    'torch': torch.__version__, 'split_seed': 14140,
    'train_examples': train_size, 'validation_examples': valid_size,
    'batch_size': batch_size, 'steps': steps, 'depth': depth, 'width': width,
    'optimizer': 'SGD', 'learning_rate': learning_rate,
    'scales': list(scales), 'seeds': list(seeds),
    'split_policy': 'disjuntos de train oficial; test oficial sin consultar',
    'batches': 'con reemplazo, semilla de lote = semilla de pesos + 900; secuencia común por escala',
    'init': 'ocultas por defecto de nn.Linear o He normal multiplicada por escala; salida Xavier normal común y bias de salida cero',
    'records': records,
}
target = Path(os.getenv('ORYON_INIT_OUTPUT', 'fashion-init.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)
del train_x, train_y, valid_x, valid_y
if device.type == 'cuda':
    torch.cuda.empty_cache()

# Cada curva termina en su último valor finito; no se interpolan ni conectan
# ejecuciones distintas y no se representa log(0).
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

colors = {'default': 'tab:gray', 0.5: 'tab:blue', 1.0: 'tab:green', 2.0: 'tab:red'}
line_styles = {seed: style for seed, style in zip(seeds, ('-', '--', ':'))}
fig, axes = plt.subplots(1, 3, figsize=(16, 4.8), constrained_layout=True)
for record in records:
    label = f"{record['scale']}, semilla {record['seed']}"
    if record['status'] != 'complete':
        label += f" (detenido en {record['last_attempted_step']})"
    kwargs = {'color': colors[record['scale']], 'linestyle': line_styles[record['seed']], 'linewidth': 1.5, 'label': label}
    validation = [(p['step'], p['loss']) for p in record['points'] if math.isfinite(p['loss']) and p['loss'] > 0]
    if validation:
        axes[0].plot([p[0] for p in validation], [p[1] for p in validation], marker='.', **kwargs)
        if record['status'] != 'complete':
            axes[0].plot(validation[-1][0], validation[-1][1], marker='x', color=colors[record['scale']], markersize=7)
    for axis, name in zip(axes[1:], ('first', 'last')):
        values = [(p['step'], p[name] if math.isfinite(p[name]) and p[name] > 0 else float('nan'))
                  for p in record['gradient_points']]
        if any(math.isfinite(value) for _, value in values):
            axis.plot([p[0] for p in values], [p[1] for p in values], **kwargs)
for ax, title in zip(axes, ('Pérdida de validación', 'Norma gradiente: primera capa', 'Norma gradiente: última capa oculta')):
    ax.set_title(title)
    ax.set_xlabel('Paso')
    ax.set_yscale('log')
    ax.grid(alpha=0.25)
axes[0].set_ylabel('Valor, escala logarítmica')
axes[0].legend(title='Inicialización y semilla', fontsize=7, loc='best')
fig.suptitle('Fashion-MNIST: inicialización y estabilidad (' + ('ensayo corto' if short else 'entrenamiento del lector') + '); gradientes antes del paso')
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.

Exercises

In the last question, the self-normalizing network of Klambauer and colleagues uses architectural and distributional assumptions. The PyTorch initialization documentation distinguishes the default SELU gain from the variance reproducing that fixed point.

ProofSecond moment and He scale
Prove: Derive a condition preserving preactivation variance between two ReLU layers.
0
Let z be a symmetric preactivation with zero mean and finite variance q, and h=ReLU(z). The next layer has n inputs hᵢ with second moment q/2; weights wᵢ have zero mean, variance σ², are independent of each other and of the input vector, and bias is zero. Require q>0.

Step 1 of 3. What is the second moment of h?

ProofWhen symmetry persists
Prove: Prove that two indistinguishable hidden neurons remain equal under deterministic gradient descent.
0
For one example, f(x)=v₁φ(w₁·x+b₁)+v₂φ(w₂·x+b₂)+b₀. Loss depends on f and the label. Assume w₁=w₂, b₁=b₂ and v₁=v₂ initially, the same minibatch and rate for all. Use a well-defined φ derivative or the same deterministic convention at the ReLU kink.

Step 1 of 3. How do the hidden activations compare?

NumericHe normal standard deviation
For ReLU and fan_in=512, calculate the standard deviation of He normal initialization.
NumericXavier for a rectangular layer
A dense layer has fan_in=512 and fan_out=256. Calculate the positive Xavier uniform limit a with gain=1.
CodeRectangular orthogonal initialization
Implement orthogonal_init(shape, gain=1.0, rng=None). shape contains two positive integers (rows, columns), and gain is finite and nonnegative. Use rng.standard_normal for a Gaussian matrix and np.linalg.qr(..., mode='reduced'); correct each column of Q using the sign of the corresponding diagonal of R, treating zero as +1. If rows≥columns, return gain·Q with orthonormal columns; if rows<columns, generate the transposed matrix and return gain·Q.T with orthonormal rows. If rng is None, create np.random.default_rng(). Reject invalid shapes or gain with ValueError.
import numpy as np

def orthogonal_init(shape, gain=1.0, rng=None):
  pass
Shift+Enter to run
QuizActivation and initialization
You want a starting point for dense layers with different activations. Which proposal best respects each rule's assumptions and limits?