The kernel regime: the NTK as a lens on the generalization of wide networks
A very wide network whose parameters barely move can behave like its linearization, giving regression with the neural tangent kernel (NTK). Use the NTK to analyze data-dependent bounds, spectral learning and alignment with the target. Then compare the fixed-kernel regime with finite networks that learn features.
After this lesson you can
- Linearize a network around initialization, define the empirical NTK, and solve the linearized gradient flow as kernel regression.
- Derive and compute the two-layer data-dependent bound and explain how label randomization changes it.
- Explain spectral bias as learning along eigendirections and predict learning curves from the kernel spectrum and target alignment.
- State separation results for fixed kernels and feature-learning networks and construct a task that fixed kernels struggle to learn.
- Measure empirical NTK drift and alignment in finite networks, then compare the network with regression using its initial and final kernels.
Before you start
- 13Rademacher complexity of RKHS ballsRepresenter theoremSpectral risk of kernel ridge regressionEffective dimensionMinimum-norm interpolatorEarly stopping as regularizationRandom features modelRandom label memorization
- 15Multilayer perceptronBackpropagationXavier/Glorot initialization
- 03Multivariable Taylor theoremLinear ODE systemsMatrix exponential
Does a wide network behave like a kernel method?
The previous lesson ended with a puzzle. Overparameterized networks can memorize random labels, making bounds that depend only on their function class vacuous. Yet those same networks generalize on real labels. A complexity measure for this phenomenon must account for data and the training algorithm.
Kernel methods already have such a theory. Earlier lessons studied the Rademacher complexity of an RKHS ball, the representer theorem, kernel ridge risk in the spectral basis, and effective dimension. Jacot, Gabriel and Hongler (2018) observed that in a suitable limit, gradient descent on a network is regression with a fixed kernel, the neural tangent kernel (NTK). Kernel results can then describe a network close to that limit.
This lesson uses the NTK to study generalization. The derivation of the infinite-width limit and the required parameterization is in the neural networks module’s abc parameterizations lesson. The related Bayesian kernel in the NNGP limit describes an infinite-width network with only its final layer trained. Here, linearization is enough. It gives a bound that distinguishes real and random labels, explains why models learn smooth functions first, and connects learning curves to the spectrum. Theoretical separations and the GPU experiments then show where fixed-kernel behavior departs from feature-learning networks.
The neural tangent kernel
Linearizing around initialization
Let be a network with parameters initialized at . Its first-order Taylor expansion at gives the linearized model
The model is linear in parameters and can be nonlinear in inputs. Its features are fixed by the architecture and initialization. A linear model in fixed features is a kernel method with the kernel induced by those features.
The NTK measures how the prediction at moves under a gradient step correcting the prediction at . A step changes by . The similarity comes from the gradient updates.
Gradient flow of the linearized model gives kernel regression
Train with squared loss and gradient flow , the continuous-time limit of gradient descent with step . Applying the chain rule to the original network gives
In function space the network’s descent follows the NTK at time . For the linearized model, the Jacobian is fixed. Its dynamics form a linear ODE with constant coefficients.
Proof
(1) With , the equation with fixed becomes . Its unique solution is , using the matrix exponential.
(2) , so by and the fact that commutes with its exponential. Substituting and yields the formula.
(3) is positive definite, so . The limit lies in the row space of and solves the system. The same Pythagorean argument as for least squares gives the minimum-norm interpolator.
∎If also , as with an antisymmetric initialization or by subtracting in the experiments, the limit is . This is ridgeless regression with the NTK. The representer theorem identifies it as the interpolator of minimum norm in the RKHS of , with norm , which the exercises prove. Part (2) also shows that at finite time the model acts as a spectral filter on the data.
The derivation is exact for the linearized model. For the original network, we need throughout training. This is the kernel regime, also called the lazy regime.
Output scale and lazy training
Chizat, Oyallon and Bach (2019) showed how output scaling can induce lazy behavior. Take any model and define the centered and scaled model
Its NTK is , and the preceding equation gives . At , the dynamics in function space are independent of . Parameter movement changes because is times as sensitive to , so a displacement suffices. If is -Lipschitz, the Jacobian’s relative change is at most . With large the model stays in a neighborhood where its linearization is accurate. Chizat et al. bound the gap between the trajectories as a function of .
For a two-layer network, is the mean-field parameterization. The NTK parameterization is exactly with . In this parameterization width scales the output and induces lazy training. Chizat et al. also find that deep convolutional classifiers perform worse when constrained to the lazy regime. The later widget visualizes the effect of changing .
Generalization in the kernel regime
The two-layer NTK of Arora et al.
Arora, Du, Hu, Li and Wang (2019) study the network
with inputs of norm . Only the first layer is trained and remains fixed. The gradient with respect to is . Since ,
The probability is independent of because the indicators are scale invariant. Project onto the span of and . The projection is isotropic Gaussian in this plane and has uniform direction. Directions making an acute angle with both vectors form a sector of width , with . The probability is and
which is times half the zero-order arc-cosine kernel of Cho and Saul, . Its diagonal is , so . Du, Zhai, Póczos and Singh (2019) proved if no two inputs are parallel, an assumption in Arora et al. The first cell compares the formula with a finite network’s empirical NTK.
import numpy as np
def ntk_relu_two_layer(X1, X2):
"""NTK H∞ de la red ReLU de dos capas (solo se entrena la primera capa): u (π − arccos u)/(2π)."""
U = np.clip(X1 @ X2.T, -1.0, 1.0)
return U * (np.pi - np.arccos(U)) / (2 * np.pi)
def empirical_ntk_first_layer(X1, X2, W, a):
"""NTK empírico de f(x) = (1/√m) Σ_r a_r relu(w_rᵀx) respecto de W:
(1/m) Σ_r a_r² 1{w_rᵀx ≥ 0} 1{w_rᵀx' ≥ 0} xᵀx'."""
m = W.shape[0]
A1 = (X1 @ W.T >= 0) * a # n1 × m, en coma flotante
A2 = (X2 @ W.T >= 0) * a
return (A1 @ A2.T) / m * (X1 @ X2.T)
rng = np.random.default_rng(0)
X = rng.normal(size=(30, 3))
X /= np.linalg.norm(X, axis=1, keepdims=True)
H = ntk_relu_two_layer(X, X)
print(f"diagonal de H∞: {H[0, 0]:.4f}; autovalores extremos: {np.linalg.eigvalsh(H)[[0, -1]].round(4)}")
print(" m máx |Θ_m − H∞| × √m")
for m in [100, 1_000, 10_000, 100_000]:
W = rng.normal(size=(m, 3))
a = rng.choice([-1.0, 1.0], size=m)
err = np.abs(empirical_ntk_first_layer(X, X, W, a) - H).max()
print(f"{m:7d} {err:.4f} {err * np.sqrt(m):.2f}")The maximum error between the NTK of a network with neurons and falls from at to at . Column stays near 1. This illustrates concentration around the limit, with fluctuations of order . The same scale helps assess when a finite network is wide enough for the approximation.
The data-dependent bound
The step is the one in Theorem 4.1, whose assumptions Theorem 5.1 inherits. For classification with , Corollary 5.2 gives the same bound for classification error . The bound is independent of once the network is wide enough to behave like its linearization.
The optimization part of the proof shows that the network stays close to its linearization and travels a distance satisfying up to small terms (Lemma 5.3). For generalization, the Rademacher complexity of networks with is, up to terms vanishing with , (Lemma 5.4). The factor 2 in the generalization inequality turns into . The kernel argument follows the same structure, which the exercises develop:
- The interpolator has RKHS norm .
- The ball has empirical Rademacher complexity . With a Lipschitz loss, the Rademacher bound gives for every in the ball.
- Choosing from the data requires accounting for that choice. Use a grid of radii and a union bound with , adding a term of order .
- interpolates and , so . With the leading term is .
Real and random labels have different spectral alignment. Diagonalize :
Structured labels concentrate energy in large-eigenvalue directions, the smooth functions favored by the kernel, making the sum small. Random labels spread energy evenly. If are independent uniform signs, the arithmetic–harmonic mean inequality gives , so . In practice small eigenvalues dominate the sum and make it much larger. The hypothesis class is identical in both cases. Arora et al. show that the quantity rises with label randomization on MNIST and CIFAR-10.
Start with and lower it to . The boundary becomes cleaner and the bound falls. As increases, the quantity falls for real labels and rises for random labels. The next cell reproduces the result in NumPy.
def moons(n, noise, rng):
"""Dos lunas con etiquetas ±1 (la mitad en cada clase), ángulo uniforme en [0, π]."""
t = np.pi * rng.random(n)
cls = np.arange(n) % 2
z = np.where(cls[:, None] == 0, np.c_[np.cos(t), np.sin(t)], np.c_[1 - np.cos(t), 0.5 - np.sin(t)])
return z + noise * rng.normal(size=(n, 2)), np.where(cls == 0, -1.0, 1.0)
def embed(z):
"""(z₁ − 0.5, z₂ − 0.25, 1) / norma: puntos de la esfera unidad de R³."""
A = np.c_[z[:, 0] - 0.5, z[:, 1] - 0.25, np.ones(len(z))]
return A / np.linalg.norm(A, axis=1, keepdims=True)
def data_dependent_bound(H, y):
return np.sqrt(2 * y @ np.linalg.solve(H, y) / len(y))
def randomize(y, p, rng):
"""Cada etiqueta se sustituye, con probabilidad p, por un signo uniforme."""
y = y.copy()
mask = rng.random(len(y)) < p
y[mask] = rng.choice([-1.0, 1.0], size=mask.sum())
return y
rng = np.random.default_rng(1)
z_te, y_te = moons(1000, 0.1, rng)
X_te = embed(z_te)
print(" n p √(2yᵀH⁻¹y/n) error test (D_p) error frente a limpias")
for n, ps in [(200, [0.0, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0]), (100, [0.0, 1.0]), (400, [0.0, 1.0])]:
z, y = moons(n, 0.1, rng)
X = embed(z)
Hn = ntk_relu_two_layer(X, X)
K_te = ntk_relu_two_layer(X_te, X)
for p in ps:
b, e1, e2 = [], [], []
for s in range(5):
r = np.random.default_rng(100 + s)
yp, ytp = randomize(y, p, r), randomize(y_te, p, r)
pred = np.sign(K_te @ np.linalg.solve(Hn, yp))
b.append(data_dependent_bound(Hn, yp))
e1.append(np.mean(pred != ytp))
e2.append(np.mean(pred != y_te))
print(f"{n:4d} {p:4.1f} {np.mean(b):6.2f} {np.mean(e1):.3f} {np.mean(e2):.3f}")
if n == 200:
lam = np.linalg.eigvalsh(Hn)
print(f" λ_min(H∞) = {lam[0]:.2e}; para signos uniformes, E[2yᵀH⁻¹y/n] = 2 tr(H⁻¹)/n = {2 * np.sum(1 / lam) / n:.1f}")
from sklearn.kernel_ridge import KernelRidge
kr = KernelRidge(alpha=1e-10, kernel='precomputed').fit(Hn, y)
print(f"KernelRidge de scikit-learn frente a la solución directa: máx. diferencia {np.abs(kr.predict(K_te) - K_te @ np.linalg.solve(Hn, y)).max():.1e}")With , the quantity rises from on real labels to with 10% randomized and with all labels randomized. Test error rises from % to %, in the same order. With real labels it falls from () to and (). With random labels it rises from to . Under random labels expectation is for the squared quantity, and matches the measured . This is almost a hundred times the guaranteed 4 because tiny eigenvalues dominate (), and random labels put energy in those directions. Even with real labels the quantity exceeds 1, so it is vacuous as a bound on a loss in . Its value here is the ranking and dependence on .
Spectral dynamics and spectral bias
Residuals decay along eigendirections
Return to part (1) of the linearized dynamics theorem with . In the eigenbasis ,
Each component of the residual decays independently at rate with half-life . Discrete gradient descent with step replaces the exponential by . Arora et al., Theorem 4.1, show that wide networks follow this rule up to a small error. Random labels train more slowly because their energy extends into directions with small .
Rahaman et al. (2019) describe this effect using the Fourier spectrum of ReLU networks during training. Low frequencies are learned before high frequencies. The NTK gives a quantitative prediction. On a circle with evenly spaced points , a kernel depending only on gives a circulant Gram matrix. The eigenvectors are the Fourier modes and with eigenvalue . For with augmented input , mimicking a network with bias, eigenvalues decrease with frequency. Fourier features help coordinate networks represent fine details that otherwise lie in the spectral tail.
Removing the constant coordinate has a stronger effect. Since , the kernel is and is even in . With , even powers of contain only even frequencies, while the term contains only frequency 1. Odd frequencies have eigenvalue exactly zero. A bias-free two-layer network in the kernel regime cannot learn on the circle regardless of training time.
Early stopping acts as a spectral filter
With , part (1) gives on the training data. Each component is multiplied by . Kernel ridge with parameter and estimator multiplies it by . With and , the two filters are and , and
The left inequality is . The right is equivalent to . This is immediate for . For , function satisfies and . Stopping at is equivalent up to a factor of two per eigendirection to ridge with . This is early stopping as regularization from lesson 15 in the NTK basis. Directions with are already learned and those with have hardly moved. The widget displays the equivalent ridge setting.
The next cell checks this prediction in a finite network. It uses gradient descent on Arora et al.’s model with neurons and antisymmetric initialization: every appears twice, with and , so exactly. It trains on 64 circle points with target and projects the residual into the Fourier basis.
n = 64
phi = 2 * np.pi * np.arange(n) / n
Xc = np.c_[np.cos(phi), np.sin(phi), np.ones(n)] / np.sqrt(2)
lam = np.real(np.fft.rfft(ntk_relu_two_layer(Xc, Xc)[0])) # Gram circulante: λ_k = DFT de la primera fila
X2 = np.c_[np.cos(phi), np.sin(phi)]
lam_nobias = np.real(np.fft.rfft(ntk_relu_two_layer(X2, X2)[0]))
print("k :", np.arange(8))
print("con sesgo :", lam[:8].round(4))
print("sin sesgo :", np.abs(lam_nobias[:8]).round(4))
print(f"sin sesgo, máx |λ_k| con k impar ≥ 3: {np.abs(lam_nobias[3::2]).max():.1e}")
y = np.cos(phi) + np.sin(3 * phi)
m, eta, steps = 4000, 0.1, 300
r = np.random.default_rng(3)
W = r.normal(size=(m // 2, 3))
W = np.r_[W, W] # inicialización antisimétrica: f₀ = 0
a = np.r_[np.ones(m // 2), -np.ones(m // 2)]
W0 = W.copy()
def mode_energy(res, k):
"""Energía de la frecuencia k (coseno más seno) en Σ_j res_j²."""
return 2 * np.abs(np.fft.rfft(res)[k]) ** 2 / n
print("\n t frec. 1: medida predicha frec. 3: medida predicha")
for t in range(steps + 1):
act = (Xc @ W.T >= 0) # n × m
res = (act * (Xc @ W.T)) @ a / np.sqrt(m) - y
if t in (0, 10, 30, 100, 300):
p1 = mode_energy(-y, 1) * (1 - eta * lam[1]) ** (2 * t)
p3 = mode_energy(-y, 3) * (1 - eta * lam[3]) ** (2 * t)
print(f"{t:4d} {mode_energy(res, 1):.2e} {p1:.2e} {mode_energy(res, 3):.2e} {p3:.2e}")
W -= eta * ((act * res[:, None]).T @ Xc) * a[:, None] / np.sqrt(m)
A0 = (Xc @ W0.T >= 0).astype(float)
A1 = (Xc @ W.T >= 0).astype(float)
T0, T1 = A0 @ A0.T / m * (Xc @ Xc.T), A1 @ A1.T / m * (Xc @ Xc.T)
Hc = ntk_relu_two_layer(Xc, Xc)
print(f"\n‖W − W₀‖_F = {np.linalg.norm(W - W0):.2f} frente a √(yᵀH⁻¹y) = {np.sqrt(y @ np.linalg.solve(Hc, y)):.2f} "
f"(‖W₀‖_F = {np.linalg.norm(W0):.1f}); deriva del NTK ‖Θ_t − Θ_0‖_F / ‖Θ_0‖_F = {np.linalg.norm(T1 - T0) / np.linalg.norm(T0):.3f}")
y6 = np.cos(phi) + np.sin(6 * phi)
print(f"con sen 6φ en lugar de sen 3φ: √(yᵀH⁻¹y) = {np.sqrt(y6 @ np.linalg.solve(Hc, y6)):.2f}")The eigenvalues are and with bias, and up to rounding without bias, as parity predicts. The network tracks kernel dynamics. Frequency 1 disappears within 10 steps, leaving energy from the mismatch between and . Frequency 3 drops from 32 to 17.6 at and to 5.9 at , compared with predictions 17.3 and 5.1. The approximation worsens when less than 1% of the initial residual remains (). Differences between finite width 4000 and the limit then matter more, and the empirical NTK has changed by 2% over training. The last line illustrates Arora et al.’s lemma. The network moved by , 10% of , close to . With its movement would be because is more than four times smaller than . Harder labels can require greater movement from initialization and an earlier exit from the kernel regime. Try varying the target in the cell.
Spectral learning curves
Spectral bias describes training dynamics. Sample efficiency also depends on the spectrum. Take a kernel with Mercer decomposition relative to the input distribution, with eigenfunctions orthonormal in , and expand the target as . Canatar, Bordelon and Pehlevan (2021) compute generalization error for kernel regression with examples, ridge parameter and estimator , and noise variance :
This resembles kernel ridge in the spectral basis, with an effective ridge induced by the problem even if . The quantity is the learned fraction of mode . It is near 1 if and near 0 if . With examples, roughly the modes with largest eigenvalues are learned. Multiplying the equation by , the equation for becomes . With the learned fractions sum to exactly . The derivation uses the nonrigorous replica method from statistical physics and describes typical behavior when and the number of relevant modes are large. The cell compares this theory with independent Gaussian features of the same spectrum and with the actual data.
Canatar et al. use alignment to explain why the two-layer NTK needs fewer MNIST examples to distinguish zeros from ones than to distinguish eights from nines (Figure 1). More of the first target’s energy lies in early modes. The widget uses the explicit periodic Laplace kernel on the circle. Its eigenfunctions for uniform inputs are , and , with eigenvalues . The cell verifies this Fourier series of the hyperbolic cosine. Bandwidth controls how fast the eigenvalues decay.
def laplace_spec(ell, K=1000):
"""Autovalores c_k (k = 0..K) del kernel periódico de Laplace normalizado (k(0) = 1)."""
k = np.arange(K + 1)
return 1 / (1 + (ell * k) ** 2) / ((np.pi / ell) / np.tanh(np.pi / ell))
def laplace_kernel(D, ell):
"""cosh((π − |Δ|)/ℓ) / cosh(π/ℓ), escrito de forma estable."""
D = np.abs((D + np.pi) % (2 * np.pi) - np.pi)
return np.exp(-D / ell) * (1 + np.exp(-2 * (np.pi - D) / ell)) / (1 + np.exp(-2 * np.pi / ell))
def modes(c, rho, K):
"""Autovalores con multiplicidad (k ≥ 1: coseno y seno) y energía del objetivo en cada modo."""
eta = np.r_[c[0], np.repeat(c[1:], 2)]
v2 = np.zeros_like(eta)
v2[1] = 1 - rho
v2[2 * K - 1] += rho
return eta, v2
def canatar_eg(n, eta, v2, lam=1e-4, sigma2=0.0):
"""Ecuación (4) de Canatar et al.: κ por bisección en escala logarítmica."""
lo, hi = np.log(1e-16), np.log(1e3)
for _ in range(90):
kap = np.exp((lo + hi) / 2)
if kap - lam - kap * np.sum(eta / (kap + n * eta)) > 0:
hi = np.log(kap)
else:
lo = np.log(kap)
kap = np.exp((lo + hi) / 2)
gam = np.sum(n * eta ** 2 / (kap + n * eta) ** 2)
return (np.sum(v2 * (kap / (kap + n * eta)) ** 2) + sigma2 * gam) / (1 - gam)
D = np.linspace(-np.pi, np.pi, 7)
cf = laplace_spec(0.5, 20000)
serie = cf[0] + 2 * np.cos(np.outer(D, np.arange(1, 20001))) @ cf[1:]
print(f"kernel cerrado frente a su serie de Fourier truncada en k = 20000: máx. dif. {np.abs(laplace_kernel(D, 0.5) - serie).max():.1e}")
ell, K = 0.3, 8
c = laplace_spec(ell)
r = np.random.default_rng(0)
grid = np.linspace(0, 2 * np.pi, 256, endpoint=False)
print(" ρ n teoría circunferencia rasgos gaussianos")
for rho in [0.0, 1.0]:
eta_, v2 = modes(c, rho, K)
fs = lambda t: np.sqrt(2 * (1 - rho)) * np.cos(t) + np.sqrt(2 * rho) * np.cos(K * t)
eg, vg = modes(laplace_spec(ell, 300), rho, K)
for n in [8, 32, 128]:
ec = []
for s in range(20):
x = r.uniform(0, 2 * np.pi, n)
al = np.linalg.solve(laplace_kernel(x[:, None] - x[None], ell) + 1e-4 * np.eye(n), fs(x))
ec.append(np.mean((laplace_kernel(grid[:, None] - x[None], ell) @ al - fs(grid)) ** 2))
eG = []
for s in range(10):
Z = r.normal(size=(n, len(eg))) # rasgos gaussianos con el mismo espectro
al = np.linalg.solve((Z * eg) @ Z.T + 1e-4 * np.eye(n), Z @ np.sqrt(vg))
eG.append(np.sum((eg * (Z.T @ al) - np.sqrt(vg)) ** 2))
print(f"{rho:3.0f} {n:4d} {canatar_eg(n, eta_, v2):.2e} {np.mean(ec):.2e} {np.mean(eG):.2e}")For with the aligned target (), theory predicts error at 32 examples and at 128. For the misaligned target (, with all energy in frequency 8), it predicts and , between 17 and 36 times more error for the same data. Gaussian-feature simulations match (, , and ). Circle simulations preserve the shape and ordering but predictably differ in the transition region, up to sixfold at and (). They use the same spectrum and target, but a different feature distribution. The Gaussian-feature assumption fails for and on one dimension. Alignment has a similar effect in both simulations.
Limits of the kernel regime
The barrier for inner-product kernels
The limits become prominent in high dimension. Ghorbani, Mei, Misiakiewicz and Montanari (2021) study inputs uniform on the sphere in with radius and a rotation-invariant kernel . This includes the NTK and random-feature kernel of a fully connected network at infinite width. The eigenfunctions are spherical harmonics grouped by polynomial degree. There are on the order of harmonics of degree , and rotation invariance gives all of them the same eigenvalue. With examples kernel regression learns only degrees containing fewer than modes.
The kernel treats all degree-1 directions alike and all degree-2 directions alike, and so on. A single-index target depends on only one direction, but the kernel treats its degree- component as a generic polynomial. The following cell expands the experiment’s target in Hermite polynomials.
from math import factorial
from numpy.polynomial.hermite_e import hermegauss, hermeval
zq, wq = hermegauss(200)
wq = wq / wq.sum() # cuadratura para z ~ N(0, 1)
g = (np.abs(zq) - np.sqrt(2 / np.pi)) / np.sqrt(1 - 2 / np.pi)
print(f"varianza de g (cuadratura): {np.sum(wq * g ** 2):.3f}")
for k in range(7):
ck = np.zeros(k + 1); ck[k] = 1
print(f"grado {k}: energía {np.sum(wq * g * hermeval(zq, ck)) ** 2 / factorial(k):.4f}")
d = 20
dims = [1, d, d * (d + 1) // 2 - 1, (d + 2) * (d + 1) * d // 6 - d] # C(d+k−1, k) − C(d+k−3, k−2)
print(f"armónicos esféricos en d = {d}: grado 0..3 → {dims}; acumulado hasta grado 2: {sum(dims[:3])}")is even, so it has no degree-1 component. Degree 2 accounts for 87% of its variance, degree 4 for 7%, and higher degrees for the rest. In there are 209 degree-2 harmonics. With examples, the kernel is near the degree-2 threshold and learns little of the target. A network that identifies direction only needs to fit a one-variable function.
Separations from feature-learning networks
Two results formalize this intuition.
- Wei, Lee, Liu and Ma (2019) construct a simple distribution in dimensions. A network with optimal regularization learns with examples, while its NTK requires . Regularization takes the network out of the kernel regime and changes sample complexity.
- Damian, Lee and Soltanolkotabi (2022) study targets with and , where is a polynomial of degree . A kernel needs examples. Gradient descent on a two-layer network outside the kernel regime succeeds with because its first layer learns a representation of the relevant directions.
The widget uses the same network on one such task in both regimes and varies only Chizat et al.’s output scale .
With , the network learns the direction. The fraction of energy along rises from to almost half. The kernel changes by several times its initial norm and test error falls to one tenth of kernel regression’s. With the network still fits the training data, neurons barely move, the NTK changes by 3%, and predictions match kernel regression. The GPU lab repeats the experiment with three seeds. Test error goes from () to () and (), exactly the of regression with the initial kernel. Drift falls from to , and energy in falls from to .
How the empirical kernel changes
An evolving NTK can describe networks outside the fixed-kernel regime. Measure how much it changes with and in which direction with Cristianini et al.’s kernel–target alignment,
the cosine between and viewed as matrices. When the kernel concentrates energy along the labels, rises and the target becomes easier in the sense of the preceding section.
Fort, Dziugaite, Paul, Kharaghani, Roy and Ganguli (2020) measured NTK evolution in deep networks. They found a short initial phase of two or three epochs in which the NTK learns useful features and improves over initialization by roughly a factor of three. It then changes at a steadier rate. Kernel regression with the partially trained NTK matches the full network after 15% to 45% of training. Atanasov, Bordelon and Pehlevan (2022) describe silent alignment in homogeneous networks with small initialization and whitened inputs. The NTK changes its eigenspaces while small, before the loss drops much, and then mainly grows in scale. The resulting function is kernel regression with the final NTK. The effect weakens on unwhitened inputs.
The network can learn a task-specific kernel and then behave largely like regression with that kernel. Open problems include predicting the amount and direction of kernel drift in deep networks under SGD with large steps, scaling networks so that all layers continue to adapt as width grows (motivating μP and the spectral condition), and explaining which properties of real data make a learned kernel generalize. A fixed-kernel regime lacks the representation learning that would change those features.
GPU implementation: empirical NTK with torch.func
The empirical NTK of a network with parameters on points is with . A backward pass per example takes passes, and storing all of takes values. With and , that is 8 GB in float32, the whole memory of an RTX 4060. torch.func addresses both. vmap(jacrev(f)) computes a block of Jacobians in a vectorized pass, so storage is limited to one block plus the Gram matrix. For larger networks the NTK tutorial in torch.func shows Jacobian-vector-product alternatives with jvp and vjp that avoid materializing . For infinite-width kernels there are specialized libraries such as Neural Tangents (Novak et al.) in JAX.
The lab has two parts. The first repeats the last widget with the same mean-field network and three seeds. It checks the widget’s closed-form kernel using torch.func. The second uses NTK parameterization with . Training uses full-batch gradient descent (torch.optim.SGD, all examples at once, 3000 steps), with the same step size for all widths , on two tasks. MNIST even-versus-odd uses 500 training images downsampled to and 2000 test images. The single-index task uses 200 training and 2000 test points. For each network, the lab measures NTK drift, alignment with labels, and test error of the network and kernel regression with its initial and final kernels. For the single-index task it also adds a width-1024 network with in the rich regime. The run takes about a minute on the GPU and uses under 1.5 GB of memory in the original setup.
"""Régimen de kernel en la GPU: NTK empírico con torch.func, deriva, alineamiento y kernel final.
Parte 1: escala de salida α (Chizat, Oyallon y Bach) en el modelo de índice único del interactivo.
Parte 2: anchura 64 a 4096 en parametrización NTK, sobre MNIST par/impar y sobre el modelo de índice único.
"""
import math, os
import numpy as np
import torch
from torch.func import functional_call, vmap, jacrev
from torchvision import datasets
dev = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cuda.matmul.allow_tf32 = False # NTK y sistemas lineales en float32 completo
# ------------------------------------------------------------------ NTK empírico
def empirical_ntk(model, params, XA, XB, chunk=128):
"""Θ(XA, XB) = J(XA) J(XB)ᵀ, con el jacobiano por ejemplo vía vmap(jacrev), en bloques de `chunk` ejemplos."""
def f1(p, x):
return functional_call(model, p, (x.unsqueeze(0),)).squeeze(0)
jac = vmap(jacrev(f1), (None, 0))
def J(X):
return torch.cat([j.reshape(len(X), -1) for j in jac(params, X).values()], 1)
JB = torch.cat([J(XB[i:i + chunk]) for i in range(0, len(XB), chunk)])
out = torch.cat([J(XA[i:i + chunk]) @ JB.T for i in range(0, len(XA), chunk)])
del JB
return out
def krr_predict(K_tr, K_te, y, rel_ridge=1e-6):
"""Regresión kernel casi sin ridge (λ = 1e-6 · traza/n, solo por estabilidad numérica)."""
lam = rel_ridge * K_tr.diagonal().mean()
return K_te @ torch.linalg.solve(K_tr + lam * torch.eye(len(y), device=K_tr.device), y)
def rel_drift(K, K0):
return ((K - K0).norm() / K0.norm()).item()
def kernel_alignment(K, y):
"""A(K, yyᵀ) = yᵀKy / (‖K‖_F ‖y‖²): el coseno entre K e yyᵀ como matrices."""
return (y @ K @ y / (K.norm() * (y @ y))).item()
# ------------------------------------------------------------------ datos
gen = np.random.default_rng(0)
D_IDX = 20
def sphere(n):
X = gen.normal(size=(n, D_IDX))
return X * math.sqrt(D_IDX) / np.linalg.norm(X, axis=1, keepdims=True)
g_abs = lambda z: (np.abs(z) - math.sqrt(2 / math.pi)) / math.sqrt(1 - 2 / math.pi)
def to_t(a):
return torch.tensor(a, dtype=torch.float32, device=dev)
# ================================================================== Parte 1
print('Parte 1: escala de salida α, red de campo medio con m = 64 (el modelo del interactivo)')
class MeanField(torch.nn.Module):
def __init__(self, m, d):
super().__init__()
self.W = torch.nn.Parameter(torch.randn(m, d) / math.sqrt(d))
self.a = torch.nn.Parameter(torch.randn(m))
def forward(self, x):
return torch.relu(x @ self.W.T) @ self.a / self.a.numel()
ALPHAS = [1, 10 ** 0.5, 10, 10 ** 1.5, 100, 1000]
res1 = {a: [] for a in ALPHAS}
ker1 = []
for seed in range(3):
Xtr, Xte = sphere(200), sphere(1000)
ytr, yte = to_t(g_abs(Xtr[:, 0])), to_t(g_abs(Xte[:, 0]))
Xtr, Xte = to_t(Xtr), to_t(Xte)
torch.manual_seed(seed)
base = MeanField(64, D_IDX).to(dev)
p0 = {k: v.detach().clone() for k, v in base.named_parameters()}
K0 = empirical_ntk(base, p0, Xtr, Xtr)
if seed == 0: # comprobación: la fórmula cerrada del NTK (la que usa el interactivo) frente a torch.func
U = Xtr @ p0['W'].T
Kc = (torch.relu(U) @ torch.relu(U).T + ((U > 0) * p0['a'] ** 2) @ (U > 0).float().T * (Xtr @ Xtr.T)) / 64 ** 2
print(f' NTK con torch.func frente a la fórmula cerrada: diferencia relativa {((K0 - Kc).norm() / Kc.norm()).item():.1e}')
ker1.append(((krr_predict(K0, empirical_ntk(base, p0, Xte, Xtr), ytr) - yte) ** 2).mean().item())
h0tr, h0te = base(Xtr).detach(), base(Xte).detach()
for alpha in ALPHAS:
net = MeanField(64, D_IDX).to(dev)
net.load_state_dict(base.state_dict())
opt = torch.optim.SGD(net.parameters(), lr=64.0) # paso η = m
for it in range(1500):
opt.zero_grad()
loss = 0.5 * ((alpha * (net(Xtr) - h0tr) - ytr) ** 2).mean() / alpha ** 2
loss.backward()
opt.step()
p1 = {k: v.detach() for k, v in net.named_parameters()}
W = p1['W']
res1[alpha].append((((alpha * (net(Xte) - h0te) - yte) ** 2).mean().item(),
rel_drift(empirical_ntk(net, p1, Xtr, Xtr), K0),
((W[:, 0] ** 2).sum() / (W ** 2).sum()).item()))
print(f' regresión kernel con el NTK inicial (sin ridge): error de test {np.mean(ker1):.3f} (semillas: {", ".join(f"{e:.3f}" for e in ker1)})')
print(' α test red deriva NTK energía en e1 (media de 3 semillas; al inicio la energía es ~1/d = 0.05)')
for a in ALPHAS:
r = np.array(res1[a]).mean(0)
print(f' {a:7.1f} {r[0]:.3f} {r[1]:.3f} {r[2]:.3f}')
# ================================================================== Parte 2
print()
print('Parte 2: parametrización NTK, f(x) = vᵀ relu(Wx/√d)/√w con W, v ~ N(0, 1) y GD de paso 1')
class NTKNet(torch.nn.Module):
def __init__(self, w, d):
super().__init__()
self.W = torch.nn.Parameter(torch.randn(w, d))
self.v = torch.nn.Parameter(torch.randn(w))
self.d, self.w = d, w
def forward(self, x):
return torch.relu(x @ self.W.T / math.sqrt(self.d)) @ self.v / math.sqrt(self.w)
root = os.path.join(os.path.expanduser('~'), '.cache', 'atlas-data') # MNIST se descarga la primera vez (unos 11 MB)
tr = datasets.MNIST(root, train=True, download=True)
te = datasets.MNIST(root, train=False, download=True)
def prep(ds, idx):
X = ds.data[idx].float() / 255
X = torch.nn.functional.avg_pool2d(X[:, None], 2).flatten(1) # 14 × 14 = 196 píxeles
X = X - X.mean(1, keepdim=True)
X = X / X.norm(dim=1, keepdim=True) * math.sqrt(X.shape[1]) # norma √d
y = (ds.targets[idx] % 2 == 0).float() * 2 - 1 # par: +1, impar: −1
return X.to(dev), y.to(dev)
tasks = {}
tasks['MNIST par/impar'] = (*prep(tr, torch.tensor(gen.choice(60000, 500, replace=False))),
*prep(te, torch.tensor(gen.choice(10000, 2000, replace=False))), 'clas')
Xi, Xit = sphere(200), sphere(2000)
tasks['índice único |z|'] = (to_t(Xi), to_t(g_abs(Xi[:, 0])), to_t(Xit), to_t(g_abs(Xit[:, 0])), 'reg')
WIDTHS = [64, 256, 1024, 4096]
CHECK = [10, 30, 100, 300, 1000]
for name, (Xtr, ytr, Xte, yte, kind) in tasks.items():
d = Xtr.shape[1]
if kind == 'clas':
metric = lambda f: (torch.sign(f) != yte).float().mean().item()
else:
metric = lambda f: ((f - yte) ** 2).mean().item()
print(f'\n {name}: n = {len(ytr)}, test = {len(yte)}, d = {d}; ' + ('error 0-1' if kind == 'clas' else 'error cuadrático') + ' en test')
print(' anchura α red K_0 K_final deriva A(K_0) A(K_final) deriva en t = 10, 30, 100, 300, 1000 / deriva final')
runs = [(w, 1.0, 3000) for w in WIDTHS] + ([(1024, 0.03, 6000)] if kind == 'reg' else [])
for w, alpha, steps in runs:
torch.manual_seed(1)
net = NTKNet(w, d).to(dev)
p0 = {k: v.detach().clone() for k, v in net.named_parameters()}
f0tr, f0te = net(Xtr).detach(), net(Xte).detach()
K0, K0te = empirical_ntk(net, p0, Xtr, Xtr), empirical_ntk(net, p0, Xte, Xtr)
opt = torch.optim.SGD(net.parameters(), lr=1.0)
drifts = {}
for it in range(steps):
if it in CHECK:
drifts[it] = rel_drift(empirical_ntk(net, {k: v.detach() for k, v in net.named_parameters()}, Xtr, Xtr), K0)
opt.zero_grad()
loss = 0.5 * ((alpha * (net(Xtr) - f0tr) - ytr) ** 2).mean() / alpha ** 2
loss.backward()
opt.step()
p1 = {k: v.detach() for k, v in net.named_parameters()}
K1, K1te = empirical_ntk(net, p1, Xtr, Xtr), empirical_ntk(net, p1, Xte, Xtr)
e_net = metric(alpha * (net(Xte) - f0te).detach())
e_k0, e_k1 = metric(krr_predict(K0, K0te, ytr)), metric(krr_predict(K1, K1te, ytr))
dfin = rel_drift(K1, K0)
frac = ', '.join(f'{drifts[c] / dfin:.2f}' for c in CHECK)
print(f' {w:6d} {alpha:5.2f} {e_net:.3f} {e_k0:.3f} {e_k1:.3f} {dfin:.3f} {kernel_alignment(K0, ytr):.3f} {kernel_alignment(K1, ytr):.3f} {frac}')
del K0, K0te, K1, K1te, net
if dev.type == 'cuda':
torch.cuda.empty_cache()npm run lab and open the connection link.The recorded results show three patterns:
- Drift falls with width. On MNIST it goes from () to , and (). On the single-index task it goes from to . Quadrupling width divides drift by factors between 2 and 3.6. Jacot et al.’s theory guarantees convergence to zero, while the width needed for negligible drift depends on the task.
- The final kernel improves on initialization. On the single-index task with , test error is with the final NTK versus with the initial NTK, and for the network. Alignment rises from to . With the three errors nearly coincide (, and ), reflecting lazy training. On MNIST the improvement is smaller, % with the initial NTK versus % with the final one at . The initial kernel already suits this task. Feature learning helps more when the fixed kernel is a poor fit.
- The rich regime learns the kernel early. With and , test errors are for the network and for the final NTK, versus initially. Alignment reaches , and the first 100 of 6000 steps produce 94% of final drift. In NTK parameterization with the change is more gradual. On MNIST, 1000 steps, one third of the run, account for 52% to 61% of final drift. Fort et al.’s fast early phase appears in deep networks trained with SGD. The full-batch runs with one hidden layer here lack that phase.
Common mistakes
Exercises
Step 1 of 4. Which equation does satisfy?
Step 1 of 4. What is ?
ntk_relu_two_layer(X1, X2) to return the matrix with for unit rows. Clip to before taking arccos. Implement data_dependent_bound(H, y) to return without explicitly inverting . Tests compare your kernel to the empirical NTK of a -neuron network and check that the bound rises with the fraction of randomized labels.import numpy as np
def ntk_relu_two_layer(X1, X2):
"""H∞ entre las filas (de norma 1) de X1 y de X2."""
U = X1 @ X2.T
return U / 2 # sustituye por la fórmula arcocoseno
def data_dependent_bound(H, y):
"""√(2 yᵀ H⁻¹ y / n)."""
return 0.0Summary
- The empirical NTK governs gradient descent in function space. The linearized model obeys and converges to the minimum-norm interpolator in the NTK RKHS.
- Lazy training can arise from scale (Chizat et al.). With output , parameter displacement is . The NTK parameterization is mean-field with .
- For two-layer ReLU, and the Arora et al. bound is , twice the Rademacher complexity bound for the smallest RKHS ball containing the interpolator. On two moons it rises from 1.77 for real labels to 19.0 for random labels.
- Each residual mode decays as . Early stopping at gives a similar filter to ridge with , up to a factor of two. The bias-free two-layer ReLU NTK misses odd frequencies on the circle.
- Kernel learning curves depend on target alignment with the spectrum (Canatar et al.). With examples, the learned modes have .
- Inner-product kernels require examples for degree (Ghorbani et al.). Feature-learning networks exploit low-dimensional structure with fewer examples (Wei et al.: versus ; Damian et al.: versus ).
- In finite networks, the NTK can change and align with target labels. The final NTK may predict considerably better than the initial one (Fort et al. and Atanasov et al.).