Signal propagation in deep networks: mean field, the edge of chaos and dynamical isometry
Derive deterministic recursions for signal variance and correlation in infinitely wide random networks. Analyze the ordered and chaotic phases and their boundary, study Jacobian spectra and dynamical isometry, and quantify finite-width deviations with the depth-to-width ratio. Finish with kernel shaping for training deep networks without residual connections or normalization.
After this lesson you can
- Derive pre-activation variance and correlation recursions and compute their fixed points for tanh and ReLU.
- Compute χ₁, locate the edge of chaos in the (σ_w², σ_b²) plane, and predict signal and gradient propagation depth scales.
- Distinguish mean gradient-norm preservation under He or Xavier initialization from dynamical isometry, and explain why ReLU cannot obtain the latter in this setting.
- Verify mean-field predictions on a GPU and measure deviations as a function of L/n.
- Read work on signal propagation and kernel shaping critically, distinguishing infinite-width proofs from finite-width observations.
Before you start
- 15Variance propagationHe/Kaiming initializationXavier/Glorot initializationOrthogonal initializationSpectrum of the Jacobian productVanishing gradientsExploding gradientsTanh activation
- 04Central limit theorem
- 09Gauss-Hermite quadrature for Gaussian expectationsFixed-point iteration
- 14Gaussian processWeight-space and function-space dualityNeural network Gaussian process limit
- 13Generalization in the kernel regime
- 02Singular value decompositionOrthogonal matrix
How many layers can a difference travel through?
Take two similar images and pass them through the same random network. As depth grows, their representations may become nearly indistinguishable or move apart. If all pairs eventually coincide, the final layers receive little information about which input arrived. If small differences are rapidly amplified, the representation and gradients can be very sensitive. This phenomenon appears before the first optimization step.
This lesson studies a random MLP without residual connections or normalization. Mean-field signal propagation describes the infinite-width limit at fixed depth; we will then check what changes for finite matrices. The model does not claim that a critical configuration generalizes well or maintains its spectrum during training. The question is narrower: what information and gradients reach each layer at initialization?
A recurrence for length
At layer write
Matrices and biases are independent across layers, and inputs are normalized so their second moment has a finite limit. The values and are variances, not standard deviations. Each neuron sums many contributions; in the width limit, the preactivation distribution approaches a zero-mean Gaussian with second moment . Conditioning on the previous layer and averaging over weights,
Independence of preactivations across neurons is an asymptotic property under these assumptions, not a claim of exact independence at finite width. The same recurrence appears in the NNGP kernel: here we interpret its diagonal as a dynamical system with depth as its clock.
A fixed length satisfies . For ReLU, by Gaussian symmetry, . Without bias, . If , every is fixed; the recurrence does not select a unique . Without bias, with the length converges to zero and with it grows without bound. For tanh and positive bias the fixed point must be solved numerically; saturation affects the value obtained.
Two inputs and the edge of chaos
For two inputs with equal length and correlation , use and , with independent Gaussians . Both inputs pass through the same weights and biases; therefore the bias contributes to their covariance too. If , the correlation map is
For different lengths both diagonals must evolve and be normalized by the square root of their product: the formula above cannot be used unchanged. Differentiating the Gaussian expectation and taking , provided regularity conditions hold,
If , coincidence is locally attractive. If , a small separation is locally amplified and is repulsive; when another stable fixed point exists, correlation can converge to it. The boundary is called the edge of chaos. Here “chaos” characterizes sensitivity of random functions at increasing depth, not a prediction that every training trajectory diverges. Poole and colleagues study this transition; Schoenholz and colleagues relate its depth scales to propagation and trainability in the models they analyze.
At a stable fixed point with derivative such that , a small perturbation initially behaves like and its scale is . For correlations in the ordered phase, near . In the chaotic phase, convergence to the stable fixed point uses , not the derivative at the unstable point . When , this exponential approximation loses resolution and its scale diverges: this does not mean correlation remains exactly constant.
Length has a different derivative. For a sufficiently smooth activation,
Therefore and need not coincide. In particular, the relaxation scale of need not diverge at every boundary. The cell calculates a tanh counterexample. This distinction matters: you can preserve differences across more layers while length still stabilizes quickly.
Gradients: an average is not a spectrum
Backpropagating through random weights, a mean-field approximation under the analysis’s independence assumptions relates the average ratio of gradient second moments to . That expression is evaluated at the stationary preactivation distribution; a real input may start at another length, and the first layers undergo a transient. There one must track and use each layer’s factor, so a single power of is only an approximation. For ReLU and , the derivative is one on the positive half of a Gaussian and zero on the negative half. Thus,
This is the He scale for weights with variance . It preserves a second moment under the model; it does not guarantee that each gradient preserves its norm. Nor is it enough to conclude that the network can be trained on a particular problem. Real loss gradients depend on data, weights and architecture, and their dependencies during backward can invalidate a naive application of the formula.
Let be the square output-to-input Jacobian, with singular values . The average only summarizes the spectrum. It can equal one when some directions vanish and others are amplified. For a rectangular Jacobian, specify which dimension normalizes the sum and how many singular values are included. Dynamical isometry demands a much stronger property: all singular values close to one.
An orthogonal matrix preserves lengths before activation. Afterward, the ReLU derivative zeros inactive coordinates: if the mask has zeros, the square Jacobian loses rank and is not isometric. With tanh near its linear region and appropriate orthogonal initialization, the spectrum can be much more concentrated, but choosing tanh and an arbitrary critical scale is not enough by itself. Pennington and colleagues analyze the spectrum of these families and their later work studies limiting distributions and universality under specific assumptions.
When width is finite
A single initialization is not its expectation. At finite width, lengths, active masks and singular values fluctuate; uncertainty accumulates when multiplying many layers. The depth-to-width ratio helps organize certain corrections, but does not replace assumptions about architecture, distribution and the quantity measured.
In the ReLU family studied by Hanin and Nica, the NTK standard deviation scales exponentially with the depth-to-width ratio. This result does not prove every statistic of every network is solely a function of . The expansion approach of Roberts, Yaida and Hanin makes clear why the order of limits matters: with fixed and jointly are not the same experiment. If a gradient vanishes exactly, its logarithm is not finite: record the proportion of extinctions and clarify whether logarithm statistics exclude those cases.
Design the kernel, not just a variance
Local criticality near does not describe the full shape of . Deep Kernel Shaping, or DKS, transforms activations and adjusts initialization and architecture to control signal maps and the initial kernel. Martens and colleagues compare deep networks without normalization: on ImageNet, their competitive results without skip connections use K-FAC or Shampoo, while the SGD comparison in the abstract uses residual networks. This is not evidence that any network without skips trained with SGD matches a ResNet.
Tailored Activation Transformations, or TAT, adapts the approach to Leaky ReLU variants; Zhang and colleagues report accuracy competitive with ResNets of the same depth and width in their experiments. Separately, Xiao and colleagues trained convolutional networks without residual connections of up to 10,000 layers using delta-orthogonal initialization: in that configuration they report 99% test accuracy on MNIST and 82% on CIFAR-10. This is a different study from DKS, with a different architecture and initialization; it does not guarantee the same results for this lesson’s MLP.
The kernel regime and initial propagation share infinite-width tools, but are not identical claims. The network can move away from initialization during training. Residual connections and normalization change the equations; when moving to convolutions, recurrence or transformers, the corresponding model must be derived. In the next lesson you will return to how parameterization and width affect training.
Labs
This first cell implements the recurrences with Gauss-Hermite quadrature, checks ReLU against its analytical solution and locates the tanh critical point with positive bias. It compares length and correlation derivatives; a comparison with a finite network is added to the output. One realization need not match its limit exactly.
import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial.hermite import hermgauss
from scipy.optimize import brentq
from scipy.special import ndtr
# Gauss-Hermite para Z normal estándar, calculada una sola vez.
z, w = hermgauss(64)
z, w = np.sqrt(2)*z, w/np.sqrt(np.pi)
def phi(x, name):
if name == 'tanh': return np.tanh(x)
if name == 'relu': return np.maximum(x,0)
if name == 'gelu': return x*ndtr(x)
raise ValueError(name)
def qmap(q, sw2, sb2, name):
return sw2*np.dot(w,phi(np.sqrt(q)*z,name)**2)+sb2
def corrmap(c,q,sw2,sb2,name):
if not -1 <= c <= 1 or q <= 0: raise ValueError('c o q fuera del dominio')
u=np.sqrt(q)*z[:,None]
v=np.sqrt(q)*(c*z[:,None]+np.sqrt(max(0.,1-c*c))*z[None,:])
return (sw2*np.sum(w[:,None]*w[None,:]*phi(u,name)*phi(v,name))+sb2)/q
def qfixed(sw2,sb2):
if sb2<=0: raise ValueError('Usa sesgo positivo en este solucionador')
return brentq(lambda q:qmap(q,sw2,sb2,'tanh')-q,0.,sw2+sb2+1.)
def chi(q,sw2):
return sw2*np.dot(w,(1-np.tanh(np.sqrt(q)*z)**2)**2)
sb2=.05
sw2=brentq(lambda s:chi(qfixed(s,sb2),s)-1,.2,5.)
qstar=qfixed(sw2,sb2)
delta=1e-5
qprime=(qmap(qstar+delta,sw2,sb2,'tanh')-qmap(qstar-delta,sw2,sb2,'tanh'))/(2*delta)
print('tanh: sw2 crítico, q*, chi1, Q\'(q*):',sw2,qstar,chi(qstar,sw2),qprime)
print('xi_q finita:',-1/np.log(abs(qprime)))
assert abs(chi(qstar,sw2)-1)<1e-10 and abs(qprime-.51818648)<1e-5
assert abs(corrmap(1,qstar,sw2,sb2,'tanh')-1)<1e-10
for c in (-1.,0.,.5,1.):
analytic=(np.sqrt(1-c*c)+(np.pi-np.arccos(c))*c)/np.pi
numerical=corrmap(c,1,2,0,'relu')
assert abs(analytic-numerical)<.01
print('GELU: Q(1) con sw2=1 y sb2=0:',qmap(1,1,0,'gelu'))
# Diagrama tanh: sesgo positivo evita el punto degenerado q*=0.
# xi_c se muestra solo en fase ordenada, donde c*=1 es estable.
weight_grid=np.linspace(.7,2.5,25)
bias_grid=np.linspace(.01,.1,16)
chi_grid=np.empty((len(bias_grid),len(weight_grid)))
xi_c_grid=np.full_like(chi_grid,np.nan)
xi_q_grid=np.full_like(chi_grid,np.nan)
for i,bias2 in enumerate(bias_grid):
for j,weight2 in enumerate(weight_grid):
fixed=qfixed(weight2,bias2)
chi_grid[i,j]=chi(fixed,weight2)
if 0<chi_grid[i,j]<1:
xi_c_grid[i,j]=-1/np.log(chi_grid[i,j])
values=np.tanh(np.sqrt(fixed)*z)
sech2=1-values**2
qder=weight2*np.dot(w,sech2**2-2*values**2*sech2)
if 0<abs(qder)<1:
xi_q_grid[i,j]=-1/np.log(abs(qder))
fig,axes=plt.subplots(2,2,figsize=(10,7),constrained_layout=True)
for ax,data,title in [(axes[0,0],chi_grid,'χ₁'),
(axes[0,1],np.log10(xi_c_grid),'log₁₀ ξc, solo fase ordenada'),
(axes[1,0],np.log10(xi_q_grid),'log₁₀ ξq')]:
image=ax.pcolormesh(weight_grid,bias_grid,data,shading='auto')
ax.contour(weight_grid,bias_grid,chi_grid,levels=[1],colors='white',linewidths=1)
ax.set(xlabel='Varianza de pesos σw²',ylabel='Varianza de sesgos σb²',title=title)
fig.colorbar(image,ax=ax)
# Comparar el mapa normalizado de activaciones con q=1 y sesgo cero.
# Cada cociente usa Q(1) de esa activación; q=1 no tiene que ser fijo.
correlations=np.linspace(0,1,31)
for name in ('tanh','relu','gelu'):
qnext=qmap(1,1,0,name)
mapped=[corrmap(float(c),1,1,0,name)/qnext for c in correlations]
axes[1,1].plot(correlations,mapped,label=f'{name}; Q(1)={qnext:.3f}')
axes[1,1].plot(correlations,correlations,'k:',label='Identidad')
axes[1,1].set(xlabel='Correlación inicial',ylabel='Correlación siguiente',
title='Una capa, q=1 y sesgo cero')
axes[1,1].legend(fontsize=8)
plt.show()
print('Mapa: línea blanca χ1=1; ξc omitida en fase caótica y ξq en puntos no estables.')
# Una red finita: misma matriz y sesgo para ambas entradas.
generator=np.random.default_rng(21)
n=128
a=generator.normal(size=n);a*=np.sqrt(n)/np.linalg.norm(a)
b=generator.normal(size=n);b-=np.dot(a,b)/np.dot(a,a)*a
b*=np.sqrt(n)/np.linalg.norm(b)
x=a.copy();y=.5*a+np.sqrt(.75)*b
q,c=1.,.5
print('capa | q teoría, q empírico | c teoría, c empírico')
for layer in range(1,9):
matrix=generator.normal(0,np.sqrt(sw2/n),(n,n))
bias=generator.normal(0,np.sqrt(sb2),n)
[email protected](x)+bias;[email protected](y)+bias
cnext=corrmap(c,q,sw2,sb2,'tanh')*q/qmap(q,sw2,sb2,'tanh')
q=qmap(q,sw2,sb2,'tanh');c=cnext
qsample=float(np.dot(x,x)/n)
csample=float(np.dot(x,y)/np.sqrt(np.dot(x,x)*np.dot(y,y)))
print(layer,round(q,4),round(qsample,4),round(c,4),round(csample,4))
assert np.isfinite(q) and -1<=c<=1Two of the following labs can use a local GPU: one compares training, Jacobian spectra and propagation for a grid of scales; another measures fluctuations and extinctions across depths and widths. The first plots the decrease in cross-entropy on the same training set and validation accuracy separately against . An unresolved scale is not replaced by zero or shown as a point. Save configuration, seeds and metrics, and compare predictions with results without assuming one run determines a universal law.
The next cell also reproduces the models and data of the phase, digit and spectrum interactives with their explicit seeds; it writes results to a local directory.
"""Datos reproducibles para fases, dos dígitos y espectros finitos.
Sin GPU ni entrenamiento. Los pesos, entradas y jacobianos están definidos aquí;
los valores son mediciones o cuadratura Gauss-Hermite, no ejemplos elegidos.
"""
import json
import math
import os
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
from pathlib import Path
import numpy as np
from scipy.optimize import brentq
from scipy.special import ndtr
from sklearn.datasets import load_digits
target=Path(os.environ.get('ORYON_FIGURES_OUTPUT','signal-figures'))
target.mkdir(parents=True,exist_ok=True)
z,w=np.polynomial.hermite.hermgauss(64);z=z*np.sqrt(2);w=w/np.sqrt(np.pi)
sw_values=np.round(np.linspace(.5,3,26),6)
sb_values=np.round(np.linspace(0,.25,11),6)
def qmap(q,sw,sb):return sw*np.dot(w,np.tanh(np.sqrt(q)*z)**2)+sb
phase=[]
for sb in sb_values:
row=[]
for sw in sw_values:
if sb==0 and sw<=1:
q=0.;chi=float(sw);status='degenerate'
elif sb==0:
q=brentq(lambda q:qmap(q,sw,sb)-q,1e-12,sw+1)
chi=float(sw*np.dot(w,(1-np.tanh(np.sqrt(q)*z)**2)**2));status='positive'
else:
q=brentq(lambda q:qmap(q,sw,sb)-q,0,sw+sb+1)
chi=float(sw*np.dot(w,(1-np.tanh(np.sqrt(q)*z)**2)**2));status='positive'
row.append({'q':float(q),'chi':chi,'status':status})
phase.append(row)
phase_output={'sw2':sw_values.tolist(),'sb2':sb_values.tolist(),'gauss_nodes':z.tolist(),'gauss_weights':w.tolist(),
'quadrature_order':64,'model':'tanh, pesos iid N(0,σw²/n), bias iid N(0,σb²)', 'rows':phase}
(target/'phase-map.json').write_text(json.dumps(phase_output,ensure_ascii=False,indent=2),encoding='utf-8')
digits=load_digits()
ids=np.flatnonzero(digits.target==3)[:2]
raw=digits.images[ids]/16.
inputs=raw.reshape(2,64).copy()
inputs*=8/np.linalg.norm(inputs,axis=1,keepdims=True)
cases=[]
def activate(x,activation):
if activation=='tanh':return np.tanh(x)
if activation=='relu':return np.maximum(x,0)
if activation=='gelu':return x*ndtr(x)
raise ValueError(activation)
settings=[('tanh',1.,.05),('tanh',1.76,.05),('tanh',3.,.05),('relu',2.,0.),('gelu',1.76,.05)]
for activation,sw,sb in settings:
random=np.random.default_rng(21210)
a=inputs.copy();records=[]
for layer in range(1,51):
matrix=random.normal(size=(64,64))*np.sqrt(sw/64)
bias=random.normal(size=64)*np.sqrt(sb)
[email protected]+bias
q=(pre*pre).mean(axis=1)
norms=np.linalg.norm(pre,axis=1)
cosine=float(pre[0]@pre[1]/(norms[0]*norms[1])) if np.all(norms>0) else None
a=activate(pre,activation)
records.append({'layer':layer,'q':q.tolist(),'preactivation_cosine':cosine,
'activations':a.tolist() if layer in (1,5,10,20,30,40,50) else None})
if activation=='relu':q_star=1. # q es fijo para cualquier q>0 en ReLU crítica.
else:
q_star=brentq(lambda q:sw*np.dot(w,activate(np.sqrt(q)*z,activation)**2)+sb-q,0,sw+sb+1)
cases.append({'activation':activation,'sw2':sw,'sb2':sb,'q_star':float(q_star),'seed':21210,'records':records})
digit_output={'dataset':'sklearn load_digits','class':3,'indices':ids.tolist(),'pixels':raw.tolist(),
'normalization':'cada imagen se escala a norma 8; pesos y bias compartidos por ambas entradas',
'width':64,'depth':50,'cases':cases}
(target/'digit-propagation.json').write_text(json.dumps(digit_output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
spectra=[]
for activation in ('tanh','relu'):
for family in ('gaussian','orthogonal'):
for seed in (2111,2112,2113,2114):
rng=np.random.default_rng(seed)
x=rng.normal(size=64)*(0.01 if activation=='tanh' else 1.)
jac=np.eye(64)
scale=1. if activation=='tanh' else np.sqrt(2)
for depth in range(1,21):
if family=='gaussian':matrix=rng.normal(size=(64,64))*(scale/8)
else:
q,r=np.linalg.qr(rng.normal(size=(64,64)))
signs=np.where(np.diag(r)<0,-1.,1.)
matrix=q*signs[None,:]*scale
pre=matrix@x
if activation=='tanh':x=np.tanh(pre); derivative=1-x*x
else:x=np.maximum(pre,0); derivative=(pre>0).astype(float)
jac=derivative[:,None]*(matrix@jac)
if depth in (1,5,10,20):
values=np.linalg.svd(jac,compute_uv=False)
spectra.append({'activation':activation,'family':family,'seed':seed,'depth':depth,
'singular_values':values.tolist(),'rms':float(np.sqrt(np.mean(values**2))),
'near_zero_fraction':float(np.mean(values<1e-8))})
spectrum_output={'width':64,'depths':[1,5,10,20],'seeds':[2111,2112,2113,2114],
'model':'tanh: entrada 0,01·N(0,I), σw²=1; ReLU: N(0,I), σw²=2; bias cero',
'zero_threshold':1e-8,'records':spectra}
(target/'jacobian-spectrum.json').write_text(json.dumps(spectrum_output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
print('Fases',len(phase)*len(sw_values),'celdas; digitos',ids.tolist(),'casos',len(cases),'espectros',len(spectra))npm run lab and open the connection link."""MLP tanh profundo en Fashion-MNIST: campo medio y entrenamiento real.
ORYON_VERIFY_SHORT=1 reduce profundidad, datos y pasos. Por defecto se exploran
profundidades 50, 100 y 200, para el lector. Solo se divide el train oficial;
la validación es disjunta y el test no se consulta. El JSON y PNG salen junto a
ORYON_EDGE_OUTPUT o, por defecto, fashion-edge.json en el directorio actual.
"""
import json
import math
import os
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter
import numpy as np
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_size,valid_size=(512,256) if short else (5000,1000)
width,depths,steps,batch=(64,[8,20],30,64) if short else (128,[50,100,200],300,64)
weight_variances=[1.,1.76,3.]
bias_variances=[0.,.05]
families=['gaussian','orthogonal']
seeds=[2101,2102]
learning_rate=.003
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(2100))
train_ids,valid_ids=split[:train_size],split[train_size:train_size+valid_size]
assert not set(train_ids.tolist()).intersection(valid_ids.tolist())
train_x=dataset.data[train_ids].reshape(train_size,-1).float().div_(255).sub_(.5).to(device)
valid_x=dataset.data[valid_ids].reshape(valid_size,-1).float().div_(255).sub_(.5).to(device)
train_y=dataset.targets[train_ids].to(device);valid_y=dataset.targets[valid_ids].to(device)
del dataset
batch_rng=torch.Generator().manual_seed(2103)
batches=torch.randint(train_size,(steps,batch),generator=batch_rng)
nodes,weights=np.polynomial.hermite.hermgauss(60)
nodes=nodes*np.sqrt(2);weights=weights/np.sqrt(np.pi)
def mean_field(sw2,sb2):
"""Punto fijo y escala de correlación en el atractor, no en c=1 inestable."""
if sb2==0 and sw2<=1:
return {'q_star':0.,'chi_one':sw2,'c_star':None,'xi_c':None,'status':'degenerate_q'}
q=1.
q_converged=False
for iteration in range(10000):
new=sw2*np.dot(weights,np.tanh(np.sqrt(q)*nodes)**2)+sb2
if abs(new-q)<1e-12:q=float(new);q_converged=True;break
q=float(new)
if not q_converged:return {'q_star':q,'chi_one':None,'c_star':None,'xi_c':None,'status':'q_not_converged'}
if q<1e-12:return {'q_star':q,'chi_one':None,'c_star':None,'xi_c':None,'status':'degenerate_q'}
z1=np.sqrt(q)*nodes[:,None]
chi_one=float(sw2*np.dot(weights,(1-np.tanh(np.sqrt(q)*nodes)**2)**2))
c=.5
c_converged=False
for _ in range(10000):
z2=np.sqrt(q)*(c*nodes[:,None]+np.sqrt(max(0,1-c*c))*nodes[None,:])
new=float((sw2*np.sum(weights[:,None]*weights[None,:]*np.tanh(z1)*np.tanh(z2))+sb2)/q)
new=min(1.,max(-1.,new))
if abs(new-c)<1e-10:c=new;c_converged=True;break
c=new
z2=np.sqrt(q)*(c*nodes[:,None]+np.sqrt(max(0,1-c*c))*nodes[None,:])
derivative=float(sw2*np.sum(weights[:,None]*weights[None,:]*(1-np.tanh(z1)**2)*(1-np.tanh(z2)**2)))
xi=-1/math.log(derivative) if c_converged and 0<derivative<1 else None
return {'q_star':q,'chi_one':chi_one,'c_star':c,'c_derivative':derivative,'xi_c':xi,
'status':'finite' if xi is not None else ('c_not_converged' if not c_converged else 'no_finite_exponential_scale')}
class MLP(nn.Module):
def __init__(self,depth,sw2,sb2,family,seed):
super().__init__()
torch.manual_seed(seed)
dims=[784]+[width]*depth
self.hidden=nn.ModuleList(nn.Linear(a,b) for a,b in zip(dims[:-1],dims[1:]))
self.output=nn.Linear(width,10)
with torch.no_grad():
for layer in self.hidden:
if family=='gaussian': nn.init.normal_(layer.weight,0.,math.sqrt(sw2/layer.in_features))
else: nn.init.orthogonal_(layer.weight,gain=math.sqrt(sw2))
nn.init.normal_(layer.bias,0.,math.sqrt(sb2))
nn.init.normal_(self.output.weight,0.,math.sqrt(1/width));nn.init.zeros_(self.output.bias)
def forward(self,x):
for layer in self.hidden:x=torch.tanh(layer(x))
return self.output(x)
@torch.no_grad()
def measure(model,x,y):
model.eval(); logits=model(x)
if not bool(torch.isfinite(logits).all()): return None
loss=nn.functional.cross_entropy(logits,y)
if not bool(torch.isfinite(loss)): return None
return {'loss':float(loss),'accuracy':float((logits.argmax(1)==y).float().mean())}
def jacobian_spectrum(model,x):
model.eval()
jac=torch.func.jacrev(lambda vector:model(vector.unsqueeze(0)).squeeze(0))(x).detach()
if not bool(torch.isfinite(jac).all()): return None
try: values=torch.linalg.svdvals(jac)
except RuntimeError: return None
if not bool(torch.isfinite(values).all()):return None
return {'shape':list(jac.shape),'singular_values':values.detach().cpu().tolist(),
'rms':float(values.square().mean().sqrt()),'max':float(values.max()),'min':float(values.min())}
def run(depth,sw2,sb2,family,seed):
model=MLP(depth,sw2,sb2,family,seed).to(device)
initial_spectrum=jacobian_spectrum(model,valid_x[0])
initial=measure(model,valid_x,valid_y)
initial_training=measure(model,train_x,train_y)
optimizer=torch.optim.Adam(model.parameters(),lr=learning_rate)
history=[];status='complete'
for step in range(steps):
model.train(); ids=batches[step].to(device)
optimizer.zero_grad(set_to_none=True)
logits=model(train_x[ids]);loss=nn.functional.cross_entropy(logits,train_y[ids])
if not bool(torch.isfinite(loss)):status='nonfinite_loss';break
loss.backward()
if any(p.grad is not None and not bool(torch.isfinite(p.grad).all()) for p in model.parameters()):status='nonfinite_gradient';break
if step in (0,steps-1):
first=model.hidden[0].weight.grad
first_norm=float(first.norm()) if first is not None else None
history.append({'step':step,'train_loss':float(loss.detach()),
'first_weight_gradient_norm':first_norm if first_norm is not None and math.isfinite(first_norm) else None})
optimizer.step()
if any(not bool(torch.isfinite(p).all()) for p in model.parameters()):status='nonfinite_parameters';break
final=measure(model,valid_x,valid_y) if status=='complete' else None
final_training=measure(model,train_x,train_y) if status=='complete' else None
final_spectrum=jacobian_spectrum(model,valid_x[0]) if status=='complete' else None
if status=='complete' and final is None:status='nonfinite_validation'
if status=='complete' and (initial_training is None or final_training is None):status='nonfinite_training_measure'
del model,optimizer
return {'depth':depth,'weight_variance':sw2,'bias_variance':sb2,'family':family,'seed':seed,
'status':status,'initial_validation':initial,'final_validation':final,
'initial_training':initial_training,'final_training':final_training,'history':history,
'initial_jacobian':initial_spectrum,'final_jacobian':final_spectrum}
theory=[{'weight_variance':sw2,'bias_variance':sb2,**mean_field(sw2,sb2)} for sw2 in weight_variances for sb2 in bias_variances]
records=[run(depth,sw2,sb2,family,seed) for depth in depths for sw2 in weight_variances
for sb2 in bias_variances for family in families for seed in seeds]
output={'dataset':'Fashion-MNIST train oficial; validación disjunta','mode':'short' if short else 'full','device':str(device),
'train_size':train_size,'validation_size':valid_size,'width':width,'depths':depths,'steps':steps,'batch':batch,
'seeds':seeds,'split_seed':2100,'batch_seed':2103,'learning_rate':learning_rate,'theory':theory,'records':records,
'protocol':'Una única división e índices de lotes comunes; bias aleatorio por capa compartido entre ejemplos. q y xi son predicciones de campo medio i.i.d. gaussianas, no exactas para pesos ortogonales ni garantía de entrenabilidad. Jacobiano rectangular logits-entrada 10×784 para una imagen.'}
target=Path(os.environ.get('ORYON_EDGE_OUTPUT','fashion-edge.json'));target.parent.mkdir(parents=True,exist_ok=True)
target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
fig,axes=plt.subplots(1,len(depths),figsize=(6*len(depths),4),constrained_layout=True)
for ax,depth in zip(np.atleast_1d(axes),depths):
for family in families:
for sb2 in bias_variances:
xs,ys=[],[]
for sw2 in weight_variances:
values=[r['final_validation']['accuracy'] for r in records if r['depth']==depth and r['weight_variance']==sw2 and r['bias_variance']==sb2 and r['family']==family and r['final_validation'] is not None]
xs.append(sw2);ys.append(np.mean(values) if values else np.nan)
ax.plot(xs,ys,marker='o',label=f'{family}, sesgo²={sb2}')
ax.set_title(f'Profundidad {depth}');ax.set_xlabel('Varianza de peso');ax.set_ylabel('Precisión validación');ax.set_ylim(0,1);ax.legend(fontsize=7)
fig.savefig(target.with_suffix('.png'),dpi=120);plt.close(fig)
# Relaciona la profundidad con la escala del atractor solo cuando esta se ha
# resuelto. No sustituye una escala desconocida por cero ni infinito.
theory_by={(t['weight_variance'],t['bias_variance']):t for t in theory}
fig,axes=plt.subplots(1,2,figsize=(12,4),constrained_layout=True)
print('Comparación individual L/xi_c, variación de CE train, precisión y estado de la teoría:')
for family,marker in [('gaussian','o'),('orthogonal','s')]:
for bias2,color in [(0.,'tab:blue'),(.05,'tab:orange')]:
xs_val=[];ys_val=[];xs_train=[];ys_train=[]
for r in records:
if r['family']!=family or r['bias_variance']!=bias2:continue
t=theory_by[(r['weight_variance'],r['bias_variance'])]
xi=t['xi_c']
ratio=r['depth']/xi if xi is not None and math.isfinite(xi) and xi>0 else None
accuracy=r['final_validation']['accuracy'] if r['final_validation'] is not None else None
before=r['initial_training']['loss'] if r['initial_training'] is not None else None
after=r['final_training']['loss'] if r['final_training'] is not None else None
decrease=before-after if before is not None and after is not None else None
print('L',r['depth'],'sw2',r['weight_variance'],'sb2',bias2,
'familia',family,'semilla',r['seed'],'L/xi_c',ratio,
'bajada_CE_train',decrease,'precision_val',accuracy,'teoria',t['status'],'corrida',r['status'])
if ratio is not None and accuracy is not None:
xs_val.append(ratio);ys_val.append(accuracy)
if ratio is not None and decrease is not None:
xs_train.append(ratio);ys_train.append(decrease)
if xs_val:axes[0].scatter(xs_val,ys_val,marker=marker,color=color,label=f'{family}, sesgo²={bias2}')
if xs_train:axes[1].scatter(xs_train,ys_train,marker=marker,color=color,label=f'{family}, sesgo²={bias2}')
for ax in axes:
if ax.collections:
ax.set_xscale('log')
ax.xaxis.set_major_locator(LogLocator(base=10,subs=(1.,2.,5.),numticks=12))
ax.xaxis.set_major_formatter(FuncFormatter(lambda value,_:f'{value:g}'))
ax.xaxis.set_minor_formatter(NullFormatter())
else:
ax.text(.5,.5,'Sin escalas resueltas y resultados finitos',ha='center',va='center',transform=ax.transAxes)
ax.set_xlabel('L/ξc, teoría gaussiana de anchura infinita')
axes[0].set(ylabel='Precisión de validación',ylim=(0,1),title='Validación')
if axes[0].collections:axes[0].legend(fontsize=7)
axes[1].axhline(0,color='black',linestyle=':',linewidth=0.8)
axes[1].set(ylabel='CE train inicial − CE train final',title='Progreso en entrenamiento')
fig.suptitle('Cada punto es una corrida; se omiten escalas no resueltas')
fig.savefig(target.with_name(target.stem+'-depth-scale.png'),dpi=120);plt.close(fig)
for row in theory:print('Teoria',row)
for row in records:print(row['depth'],row['weight_variance'],row['bias_variance'],row['family'],row['seed'],row['status'],row['final_validation'])
if device.type=='cuda':torch.cuda.empty_cache()npm run lab and open the connection link."""Fluctuaciones y extinciones de MLP ReLU en función de L/n.
ORYON_VERIFY_SHORT=1 usa 24 semillas y redes más pequeñas; por defecto se
usan 200 inicializaciones por configuración. ORYON_WIDTH_OUTPUT elige el JSON
y el PNG, que por defecto son finite-width.json y finite-width.png.
"""
import json
import math
import os
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import torch
torch.set_num_threads(1)
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
widths=[16,32,64] if short else [32,64,128,256]
depths=[16,32,64] if short else [16,32,64,128]
seeds=list(range(21000,21024 if short else 21200))
chunk_size=6 if short else 8
def simulate(width,depth,seed_chunk):
"""Dos entradas, pesos compartidos, sesgo cero y una pérdida por red."""
generators=[torch.Generator(device=device).manual_seed(seed) for seed in seed_chunk]
inputs=torch.stack([torch.randn((2,width),generator=g,device=device) for g in generators]).requires_grad_(True)
h=inputs
for _ in range(depth):
weights=torch.stack([torch.randn((width,width),generator=g,device=device) for g in generators])*math.sqrt(2/width)
h=torch.relu(torch.bmm(h,weights))
first=h[:,0,:]
# Pérdidas independientes; la suma conserva gradientes por inicialización.
loss=.5*first.square().sum()/width
gradient=torch.autograd.grad(loss,inputs)[0][:,0,:]
# Reducir en float64 evita declarar extinción por subdesbordamiento solo
# al elevar al cuadrado; las activaciones y gradientes siguen en float32.
h64=h.detach().double();gradient64=gradient.detach().double()
output_norm=h64[:,0,:].norm(dim=1);grad_norm=gradient64.norm(dim=1)
norm0=h64[:,0,:].norm(dim=1);norm1=h64[:,1,:].norm(dim=1)
dot=(h64[:,0,:]*h64[:,1,:]).sum(dim=1)
result=[]
for i,seed in enumerate(seed_chunk):
o,g,n0,n1,d=(float(v[i].detach()) for v in (output_norm,grad_norm,norm0,norm1,dot))
finite=all(math.isfinite(v) for v in (o,g,n0,n1,d))
output_zero=math.isfinite(o) and o==0
gradient_zero=math.isfinite(g) and g==0
status='nonfinite' if not finite else 'zero_output' if output_zero else 'zero_gradient' if gradient_zero else 'finite'
result.append({'seed':seed,'status':status,'output_zero':output_zero,'gradient_zero':gradient_zero,
'output_norm':o if math.isfinite(o) else None,'gradient_norm':g if math.isfinite(g) else None,
'log_output_norm':math.log(o) if math.isfinite(o) and o>0 else None,
'log_gradient_norm':math.log(g) if math.isfinite(g) and g>0 else None,
'activation_cosine':d/(n0*n1) if finite and n0>0 and n1>0 else None})
return result
def summarize(width,depth):
trials=[]
for start in range(0,len(seeds),chunk_size):trials.extend(simulate(width,depth,seeds[start:start+chunk_size]))
output_logs=[r['log_output_norm'] for r in trials if r['log_output_norm'] is not None]
grad_logs=[r['log_gradient_norm'] for r in trials if r['log_gradient_norm'] is not None]
return {'width':width,'depth':depth,'depth_over_width':depth/width,'n':len(trials),
'extinct_count':sum(r['output_zero'] for r in trials),
'zero_gradient_count':sum(r['gradient_zero'] for r in trials),
'nonfinite_count':sum(r['status']=='nonfinite' for r in trials),
'surviving_output_logs':len(output_logs),'surviving_gradient_logs':len(grad_logs),
'variance_log_output':float(np.var(output_logs,ddof=1)) if len(output_logs)>1 else None,
'variance_log_gradient':float(np.var(grad_logs,ddof=1)) if len(grad_logs)>1 else None,
'trials':trials}
records=[summarize(width,depth) for width in widths for depth in depths]
output={'mode':'short' if short else 'full','device':str(device),'dtype':'float32',
'widths':widths,'depths':depths,'seeds':seeds,'chunk_size':chunk_size,
'distribution':'Pesos i.i.d. N(0,2/n); sesgo cero; dos entradas normales independientes comparten pesos.',
'loss':'L=||h_L(x_1)||²/(2n); norma del gradiente respecto a x_1.',
'protocol':'Varianza muestral ddof=1 de log normas positivas; salida cero, gradiente cero y no finitos por separado. Un gradiente cero puede deberse a aritmética finita y no demuestra extinción estructural. El coseno corresponde a activaciones de salida, no preactivaciones.',
'records':records}
target=Path(os.environ.get('ORYON_WIDTH_OUTPUT','finite-width.json'));target.parent.mkdir(parents=True,exist_ok=True)
target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
fig,axes=plt.subplots(1,2,figsize=(10,4),constrained_layout=True)
for width in widths:
rows=[r for r in records if r['width']==width]
for ax,key,label in [(axes[0],'variance_log_gradient','Varianza log gradiente'),(axes[1],'variance_log_output','Varianza log salida')]:
ax.scatter([r['depth_over_width'] for r in rows],[r[key] if r[key] is not None else np.nan for r in rows],label=f'n={width}')
ax.set_xlabel('L/n');ax.set_ylabel(label)
axes[0].legend(fontsize=7)
fig.savefig(target.with_suffix('.png'),dpi=120);plt.close(fig)
for r in records:print('L',r['depth'],'n',r['width'],'L/n',r['depth_over_width'],'var log grad',r['variance_log_gradient'],'salida cero',r['extinct_count'],'gradiente cero',r['zero_gradient_count'],'no finitos',r['nonfinite_count'])
if device.type=='cuda':torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 2. Conditioning on previous activations, what is the variance of a preactivation?
Step 1 of 2. What is the expectation of the square of the ReLU derivative?
import numpy as np
from scipy.optimize import brentq
def correlation_map(c, q, sw2, sb2, phi):
pass
def critical_tanh(sb2):
passReferences
- Poole and colleagues, Exponential expressivity in deep neural networks through transient chaos, 2016.
- Schoenholz and colleagues, Deep Information Propagation, 2017.
- Pennington and colleagues, Resurrecting the sigmoid through dynamical isometry, 2017.
- Pennington and colleagues, The Emergence of Spectral Universality in Deep Networks, 2018.
- Xiao and colleagues, Dynamical Isometry and a Mean Field Theory of CNNs, 2018.
- Hayou and colleagues, On the Impact of the Activation Function on Deep Neural Networks Training, 2019.
- Hanin and Nica, Finite Depth and Width Corrections to the Neural Tangent Kernel, 2019.
- Roberts, Yaida and Hanin, The Principles of Deep Learning Theory, 2021.
- Martens and colleagues, Deep Kernel Shaping, 2021.
- Zhang, Botev and Martens, Shaping the Kernel with Tailored Rectifiers, 2022.