Double descent and the interpolation regime
Reproduce double descent with random features, derive ridgeless risk in the proportional regime, explain the interpolation peak, assess optimal regularization, and study deep model-, epoch- and sample-wise variants.
After this lesson you can
- Reproduce double descent with random features and the minimum-norm interpolator.
- Calculate Gaussian-design least-squares variance and explain the peak through the smallest singular value of X.
- State the Hastie, Montanari, Rosset and Tibshirani asymptotic risk as p/n approaches γ and use it to predict curves.
- Demonstrate experimentally that optimal ridge regularization removes the peak.
- Describe model-, epoch- and sample-wise deep double descent and effective model complexity.
- Critique the parameter-count axis using effective parameters.
Before you start
- 13Minimum-norm interpolatorRandom features modelClassical U-shaped risk curveBias-variance decompositionEffective dimensionImplicit regularization (implicit bias)
- 02Singular value decompositionCondition number of a matrix
- 04Multivariate Gaussian distributionCovariance matrix
- 06Stochastic gradient descentAdam
Motivation: models larger than their data
The classical U-curve summarizes prior lessons on capacity: with few parameters a model cannot represent the signal (high bias), with too many it learns sample noise (high variance), and test error is smallest between them. VC and Rademacher bounds say something similar: the generalization gap grows with class capacity.
Modern practice has contradicted this for years. ResNet18 has about 11 million parameters and trains on 50,000 CIFAR-10 examples; language models have billions. Such models can memorize random labels, so their class can interpolate anything, yet they generalize, often better when larger. Belkin, Hsu, Ma and Mandal (2019) proposed reconciling the pictures: increasing capacity beyond training-data interpolation makes test error fall again after a peak. The U-curve is only the first half of a curve with two descents.
This lesson makes the phenomenon calculable. Reproduce it in the browser with random features; see that the peak is a conditioning problem (the design matrix’s smallest singular value collapses when parameter and data counts coincide); derive exact risk for the Gaussian linear model and its asymptotic limit; prove optimal regularization removes the peak; and study deep versions before questioning the horizontal axis itself: what does “number of parameters” mean?
The Belkin et al. experiment
Start with the random-features model: draw vectors once, fix them and fit only the output layer,
This is a two-layer network with frozen first layer; least-squares fitting is linear regression on feature matrix . While , system is overdetermined and its least-squares solution is unique (if has rank ). When and has rank , infinitely many solutions interpolate, and Belkin et al. choose the minimum-norm one,
the minimum-norm interpolator, also the ridge limit as and the point reached by gradient descent initialized at zero (the previous lesson’s implicit regularization). With , converges to the kernel and fit approaches the minimum-norm RKHS interpolator.
Their main experiment used Fourier features with on an MNIST subset of images and 10 classes, with from 0 to features (paper figure 2). Test error first traces the classical U, peaks at and falls afterward; coefficient norm peaks at the same point and falls to the right. The same shape appears in a fully connected one-hidden-layer network on MNIST images, peaking where parameter count reaches (figure 4), in random forests and in -boosting.
Being a phenomenon rather than a theorem matters: the second descent need not always go below the first minimum, nor must a peak always exist. You will see both shortly.
The experiment from scratch
The next cell is the figure’s model in NumPy (different seeds, so figures differ somewhat). Minimum-norm fit comes from singular-value decomposition : , discarding numerically zero singular values, and ridge replaces with (ridge shrinkage in the SVD basis). Bias and variance average over seeds: variance is sample variance of predictions across seeds, and bias² is the corrected squared distance between mean prediction and (explained below).
import numpy as np
n, d, n_test, S = 40, 8, 200, 16
beta = np.random.default_rng(7).normal(size=d)
beta /= np.linalg.norm(beta)
def f_star(X):
z = X @ beta
return z + 0.5 * np.sin(2 * z)
X_test = np.random.default_rng(12345).normal(size=(n_test, d))
f_test = f_star(X_test)
def features(X, W, b, kind):
Z = X @ W
p = W.shape[1]
return np.cos(Z + b) * np.sqrt(2 / p) if kind == 'fourier' else np.maximum(Z, 0) / np.sqrt(p)
def ridge_svd(F, y, lam=0.0):
"""Ridge por SVD; con lam = 0 es el interpolador de mínima norma F⁺y."""
U, s, Vt = np.linalg.svd(F, full_matrices=False)
keep = s > 1e-10 * s[0]
U, s, Vt = U[:, keep], s[keep], Vt[keep]
k = 1 / s if lam == 0 else s / (s**2 + lam)
return Vt.T @ (k * (U.T @ y))
def draw(seed, p, sigma, kind):
r = np.random.default_rng(1000 + seed)
X = r.normal(size=(n, d))
y = f_star(X) + sigma * r.normal(size=n)
W = r.normal(size=(d, p)) / np.sqrt(d)
b = r.uniform(0, 2 * np.pi, p)
return features(X, W, b, kind), y, features(X_test, W, b, kind)
def experiment(kind, sigma, p_list, lam=0.0):
rows = []
for p in p_list:
preds, train = [], []
for s in range(S):
F, y, Ft = draw(s, p, sigma, kind)
w = ridge_svd(F, y, lam)
preds.append(Ft @ w)
train.append(np.mean((F @ w - y) ** 2))
P = np.array(preds)
var = P.var(axis=0, ddof=1).mean()
bias2 = np.mean((P.mean(axis=0) - f_test) ** 2) - var / S # quita el Var/S de promediar S semillas
rows.append((p, np.mean(train), np.mean((P - f_test) ** 2), bias2, var))
return rows
p_list = [2, 5, 10, 15, 20, 25, 30, 35, 38, 40, 42, 45, 50, 60, 80, 120, 160]
res = experiment('fourier', 0.2, p_list)
print(' p train test sesgo² varianza')
for p, tr, te, b2, v in res:
print(f'{p:4d} {tr:.4f} {te:9.3f} {b2:7.3f} {v:9.3f}')
best = min((r for r in res if r[0] < n), key=lambda r: r[2])
print(f'mínimo clásico: p = {best[0]}, test {best[2]:.3f}; p = 4n: test {res[-1][2]:.3f}')Read the table top to bottom. Through it is the classical U: training error falls, bias² drops from to and variance rises slowly; the classical minimum is at . Between and training error approaches zero and variance shoots up. At training is exactly zero and mean test error exceeds . Beyond that everything falls: at , at and at , less than half the classical minimum. Bias² barely changes in the overparameterized regime (around ); variance is what falls.
The mean at is enormous because the worst-conditioned seed dominates it: the next section shows that in the Gaussian linear model expected error at is literally infinite. This is not an artifact to hide; it is the phenomenon.
The second cell switches to ReLU features and varies noise.
for sigma in [0.0, 0.2, 0.5]:
r = experiment('relu', sigma, [20, 40, 160])
print(f'ReLU, σ = {sigma}: ' + ', '.join(f'p = {p}: {te:.3g}' for p, _, te, _, _ in r))Three observations. First, without label noise () a peak remains ( at ): target is not a finite linear combination of random ReLUs, and the part the model cannot represent acts as noise. Second, peak grows with noise: , and . Third, at the second descent does not compensate: error at () is worse than the classical minimum ( at ). A second descent does not guarantee the larger model wins.
Why there is a peak: the smallest singular value collapses
Elementary linear algebra explains the peak, most clearly in the simplest model: linear regression with isotropic Gaussian covariates. Take (the multivariate Gaussian with identity covariance), with independent mean-zero of variance , and . Since , excess risk of any estimator is
Write the SVD with and all (almost surely). The least-squares estimator, or minimum-norm estimator when , is in both cases (the pseudoinverse), and since projects orthogonally onto the row space,
The two terms are orthogonal (the second lies in row space, the first in its complement), so
If , and bias is zero; if , the estimator cannot see the component of orthogonal to the rows, which becomes bias. Variance explains the peak: it is times the sum of inverse squared singular values, and one small suffices to blow it up. This is pure ill conditioning: noise is divided by .
The exact value
With Gaussian design everything is calculable at finite .
Proof
Part 1 is the final proof exercise: and follows Wishart distribution , whose inverse has mean when .
Part 2. Bias: for every orthogonal matrix , has the same distribution as (each isotropic Gaussian row is rotation invariant), and its projector is . Thus for every , forcing ; taking traces gives . Therefore . Variance: , and , with columns of , is Wishart ; its inverse has mean if , yielding .
Part 3: the inverse of Wishart has finite mean only if ; at , and this condition fails (with and ) and .
∎Both formulas diverge as , one from each side, at rate . For fixed and , part 1 yields , the usual parametric rate; the peak is an effect of comparable and .
The spectrum edge
Why does the smallest singular value approach zero exactly at ? For matrices with iid mean-zero, variance-one entries and finite fourth moment, with , Bai and Yin’s theorem (1993) says almost surely and (the extreme singular values). Transposing, for the edges are , so in both regimes
The lower edge touches zero exactly at . For square Gaussian matrices, Edelman (1988) showed is order versus order for the others: a single term, of order , dominates the variance sum.
The cell checks both with : smallest singular value against edge and sum against the exact formula.
rng = np.random.default_rng(0)
n0 = 50
print(' p s_min/√n borde |1-√γ| Σ1/s² (media) fórmula exacta')
for p in [25, 40, 45, 49, 50, 51, 55, 60, 100]:
smins, sums = [], []
for _ in range(100):
s = np.linalg.svd(rng.normal(size=(n0, p)), compute_uv=False)
smins.append(s.min() / np.sqrt(n0))
sums.append(np.sum(1 / s**2))
g = p / n0
formula = p / (n0 - p - 1) if p <= n0 - 2 else (n0 / (p - n0 - 1) if p >= n0 + 2 else np.inf)
print(f'{p:4d} {np.mean(smins):8.4f} {abs(1 - np.sqrt(g)):10.4f} {np.mean(sums):12.3f} {formula:8.3f}')Away from , the mean of 100 matrices matches the exact formula to two or three digits ( versus at ; versus at ). Measured smallest singular value is somewhat above the asymptotic edge (at edge fluctuations are order and non-negligible). At , and expectation is infinite, and what you see is a 100-sample mean of a variable without a mean: at it is order ; another seed would give something very different.
Proportional regime: asymptotic minimum-norm risk
Exact formulas rely on Gaussian design. Hastie, Montanari, Rosset and Tibshirani (2022) obtained universal behavior in the proportional regime with , where the spectrum of matters.
The continuous part has mass ; the atom at zero captures the zero eigenvalues when . This is the Marchenko-Pastur law from probability; the previous figure’s density is that of under normalized . One integral is key: for ,
This is asymptotic minimum-norm risk, also called ridgeless. Variance follows from the prior integral: for , , where are eigenvalues of . For apply the same to , whose ratio is : . A rigor detail: is unbounded, so weak convergence of the spectral distribution is insufficient; the smallest eigenvalue must also stay away from zero, exactly what Bai and Yin provide when . Bias is the limit of . Compare with the exact theorem: for Gaussian design, and are the finite- versions of the two variances.
What the formula says
Write and note that the zero estimator has risk . Hastie et al. derive these consequences:
- On risk grows with and beats zero if and only if .
- On , if , risk falls but always remains worse than zero, approaching it from above.
- On , if , risk beats zero if and only if , has a local minimum at
and approaches zero-estimator risk from below as .
Differentiating point 3 takes one line: vanishes when .
Enthusiasm for double descent often misses an observation. In this model the global minimum is at , where risk tends to zero: with fixed , far more data than parameters is always best. The second descent gives only a local minimum. A global minimum in the overparameterized regime needs additional structure. Hastie et al. add it using a misspecified model (section 5): observed features capture only fraction of signal, with the rest acting as extra training noise and irreducible test bias (Theorem 4). If grows with , for example (their equation 22), each new feature brings signal, and for small and the global minimum moves to . Mei and Montanari (2019) reached the same conclusion for random-feature regression on the sphere without ad hoc misspecification: above a critical signal-to-noise ratio, extremely overparameterized interpolators obtain lowest test error.
The cell compares , and , i.e. .
def hastie(g, r2, s2):
return s2 * g / (1 - g) if g < 1 else r2 * (1 - 1 / g) + s2 / (g - 1)
def exact(nn, p, r2, s2):
return s2 * p / (nn - p - 1) if p < nn else r2 * (1 - nn / p) + s2 * nn / (p - nn - 1)
def simulate(nn, p, r2, s2, reps, rng):
w = np.zeros(p)
w[0] = np.sqrt(r2)
err = []
for _ in range(reps):
X = rng.normal(size=(nn, p))
y = X @ w + np.sqrt(s2) * rng.normal(size=nn)
wh = np.linalg.solve(X.T @ X, X.T @ y) if p < nn else X.T @ np.linalg.solve(X @ X.T, y)
err.append(np.sum((wh - w) ** 2))
return np.mean(err), np.std(err) / np.sqrt(reps)
rng = np.random.default_rng(1)
r2, s2, nn = 1.0, 0.25, 50
print(' gamma simulación (±ee) exacta n=50 asintótica')
for g in [0.2, 0.5, 0.8, 1.5, 2, 4, 8]:
p = int(round(g * nn))
m, se = simulate(nn, p, r2, s2, 300, rng)
print(f'{g:5.1f} {m:7.3f} ± {se:.3f} {exact(nn, p, r2, s2):7.3f} {hastie(g, r2, s2):7.3f}')
snr = r2 / s2
gs = np.sqrt(snr) / (np.sqrt(snr) - 1)
print(f'SNR = {snr:.0f}: mínimo local γ* = {gs:.2f}, riesgo {hastie(gs, r2, s2):.3f}; riesgo nulo {r2}')Simulation and exact formula agree in every row within about one standard error, and asymptotics are already close at except near the peak: at exact gives and asymptotic , because with and still feels in the denominator. With the local minimum is with risk , below zero-estimator risk ; but risk at () is much lower: as stated, the global minimum is on the left.
Bias and variance in the two descents
In the classical bias-variance decomposition, the peak is variance, as the linear model makes clear: for bias is zero and the whole curve is growing variance; for bias grows and variance falls. The second descent is variance falling faster than bias rises. An immediate consequence: without noise there is no peak. With risk is 0 for and for , a monotone curve. Initial random features had a peak at because the unrepresentable part of acts as noise.
Simulation bias measurement has a trap. With seeds, mean prediction averages predictors, and
Near the threshold variance is so large that dominates and naively calculated “bias” has a spurious peak. The cell and figure therefore subtract sample variance divided by . Even corrected, estimated bias is very noisy at (subtracting two enormous numbers); elsewhere the table shows bias² falling from to around and staying there.
A finer decomposition
Random-feature models have three randomness sources: features (“initialization,” ), input data () and label noise (). Total variance mixes them and total-variance decomposition depends on conditioning order. Adlam and Pennington (2020) propose a symmetric ANOVA-style decomposition: with ,
where is variance explained only jointly by features and data. In asymptotic random-feature regression they calculate terms and find bias decreases monotonically with width; variance terms are nonmonotone and can diverge at the threshold even without label noise; divergence comes from sampling-initialization interaction; and it therefore disappears when averaging samples (bagging) or features (ensembles). Label noise exacerbates but does not cause the peak.
The cell estimates these three terms with a two-factor design: 8 feature draws crossed with 8 data draws, 64 fits per , and unbiased two-factor ANOVA estimators with one observation per cell.
def fine_grained(p, kind='fourier', sigma=0.2, K=8):
"""Y[i, j] = predicción en test con las características i y los datos (X, ε) j."""
feats = []
for i in range(K):
r = np.random.default_rng(50 + i)
feats.append((r.normal(size=(d, p)) / np.sqrt(d), r.uniform(0, 2 * np.pi, p)))
data = []
for j in range(K):
r = np.random.default_rng(900 + j)
X = r.normal(size=(n, d))
data.append((X, f_star(X) + sigma * r.normal(size=n)))
Y = np.empty((K, K, n_test))
for i, (W, b) in enumerate(feats):
Ft = features(X_test, W, b, kind)
for j, (X, y) in enumerate(data):
Y[i, j] = Ft @ ridge_svd(features(X, W, b, kind), y)
mu = Y.mean(axis=(0, 1))
rows, cols = Y.mean(axis=1), Y.mean(axis=0)
resid = Y - rows[:, None] - cols[None, :] + mu
V_PD = (resid**2).sum(axis=(0, 1)).mean() / (K - 1) ** 2 # interacción características × datos
V_P = rows.var(axis=0, ddof=1).mean() - V_PD / K # varianza de E[ŷ | características]
V_D = cols.var(axis=0, ddof=1).mean() - V_PD / K # varianza de E[ŷ | datos]
bias2 = np.mean((mu - f_test) ** 2) - (V_P + V_D) / K - V_PD / K**2
return bias2, V_P, V_D, V_PD
print(' p sesgo² V_P V_D V_PD (interacción)')
for p in [20, 36, 44, 160]:
b2, vp, vd, vpd = fine_grained(p)
print(f'{p:4d} {b2:7.3f} {vp:7.3f} {vd:7.3f} {vpd:10.3f}')Results match Adlam and Pennington. On either side of the peak ( and ), interaction is and , while and stay below : nearly all peak variance is interaction. Away from the threshold interaction is comparable to other terms ( at ). We omit : tails there are so heavy that 64 fits estimate nothing reliably (unbiased estimators can even give negative variance). Practical implication: averaging predictions over many feature draws, which in the limit leaves only variance and removes and , attacks the peak at its source; model averaging reduces variance where it is greatest.
Optimal regularization: the peak disappears
If the peak is variance from small singular values, the classical remedy is ridge: replaces with , bounded by . Nakkiran, Venkat, Kakade and Ma (2020) turn this into a theorem.
Let be eigenvalues of (including zeros if ) and . Error is , and with isotropic Gaussian matrix is uniform over rotations and independent of , giving . Averaging (paper Lemma 1),
Each term is a function of with derivative : all are minimized at the same point,
which does not depend on (Lemma 2). It is the Bayesian estimator with prior , hence optimal for all eigenvalues at once.
Proof
Couple samples: is with an extra row . Then , and since is positive semidefinite, Weyl’s theorem (or Courant-Fischer) gives for each with sorted eigenvalues. Each term decreases in and does not change with , so the sum and its expectation cannot increase.
∎The proof shows why the unregularized estimator lacks this property: at terms are over nonzero eigenvalues, and going from to introduces a new positive but tiny eigenvalue, adding a huge term. More data can worsen the model: sample-wise nonmonotonicity is the same phenomenon. An interpolator’s learning curve, error versus , need not be monotone, and a validation-curve maximum need not mark the end of improvement when the model can interpolate.
The cell calculates by averaging the lemma’s formula over actual Gaussian matrices, with , and , and checks the lemma against an actual ridge fit.
def ridge_risk_mc(nn, p, r2, s2, lam, reps, rng):
"""E‖ŵ_λ − w‖² con la fórmula espectral del lema 1, promediada sobre matrices X gaussianas."""
out = []
for _ in range(reps):
mu = np.linalg.svd(rng.normal(size=(nn, p)), compute_uv=False) ** 2
mu = np.concatenate([mu, np.zeros(max(p - nn, 0))]) # los p autovalores de XᵀX
out.append(np.sum((lam**2 * r2 / p + s2 * mu) / (mu + lam) ** 2))
return np.mean(out)
rng = np.random.default_rng(3)
p, r2, s2 = 50, 1.0, 0.25
lam_star = p * s2 / r2
print(f'λ* = pσ²/r² = {lam_star}')
print(' n mínima norma (exacta) ridge λ = 1 ridge λ*')
for nn in [10, 25, 40, 48, 52, 60, 75, 100, 150]:
if nn > p + 1:
mn_ = s2 * p / (nn - p - 1)
elif nn < p - 1:
mn_ = r2 * (1 - nn / p) + s2 * nn / (p - nn - 1)
else:
mn_ = np.inf
print(f'{nn:4d} {mn_:12.3f} {ridge_risk_mc(nn, p, r2, s2, 1.0, 40, rng):9.3f} {ridge_risk_mc(nn, p, r2, s2, lam_star, 40, rng):8.3f}')
# comprobación directa: ridge de verdad con X, w y ruido nuevos en cada repetición (n = 40)
errs = []
for _ in range(300):
X = rng.normal(size=(40, p))
w = rng.normal(size=p)
w *= np.sqrt(r2) / np.linalg.norm(w)
wh = np.linalg.solve(X.T @ X + lam_star * np.eye(p), X.T @ (X @ w + np.sqrt(s2) * rng.normal(size=40)))
errs.append(np.sum((wh - w) ** 2))
print(f'n = 40, ridge λ* simulado: {np.mean(errs):.3f} ± {np.std(errs) / np.sqrt(300):.3f}')The minimum-norm column rises from at to at and at : doubling data multiplied error by 16. With (little regularization for this problem) the hump remains, flattened: , , . With the column falls continuously from at to at . Direct fit with gives , agreeing with the lemma’s .
In the random-features model
The theorem does not apply literally to random features, but its idea does, and in practice is chosen using validation rather than test data. The cell holds out 20 extra validation examples, selects among 15 values with them and measures test error.
lams = np.logspace(-6, 1, 15)
def ridge_validated(kind, sigma, p_list, n_val=20):
out = []
for p in p_list:
errs = []
for s in range(S):
r = np.random.default_rng(1000 + s)
X = r.normal(size=(n + n_val, d))
y = f_star(X) + sigma * r.normal(size=n + n_val)
W = r.normal(size=(d, p)) / np.sqrt(d)
b = r.uniform(0, 2 * np.pi, p)
F = features(X, W, b, kind)
Ftr, Fva, ytr, yva = F[:n], F[n:], y[:n], y[n:]
U, sv, Vt = np.linalg.svd(Ftr, full_matrices=False)
uy = U.T @ ytr
ws = [Vt.T @ (sv / (sv**2 + lam) * uy) for lam in lams]
best = min(ws, key=lambda w: np.mean((Fva @ w - yva) ** 2))
errs.append(np.mean((features(X_test, W, b, kind) @ best - f_test) ** 2))
out.append((p, np.mean(errs)))
return out
pv = [10, 20, 30, 38, 40, 42, 50, 80, 160]
mn = {p: te for p, _, te, _, _ in experiment('fourier', 0.2, pv)}
for p, e in ridge_validated('fourier', 0.2, pv):
print(f'p = {p:3d} mínima norma {mn[p]:9.3f} ridge validado {e:.3f}')With validated , error falls monotonically across the grid: at , at (where minimum norm exceeded ) and at . At each validated ridge also improves on minimum norm, including ( versus ): interpolation is not optimal here even though the interpolator generalizes reasonably. Validated ridge uses 20 more labeled examples; the fair comparison is with minimum norm’s classical minimum, which it also comfortably beats.
The 2020 paper extends the result in two directions. Model size: with isotropic covariates in a high-dimensional ambient space and a model using an -size projection, optimally tuned ridge has risk monotone in (Theorem 3). Empirically, random ReLU features on Fashion-MNIST and five-layer CNNs on CIFAR-100 in the next section show double descent unregularized or weakly regularized, while optimally regularized models are “largely monotone,” with optimal changing with size. It also marks limits: a non-Gaussian, heteroscedastic-noise counterexample makes optimal ridge nonmonotone in , and for nonisotropic Gaussian covariates monotonicity with standard ridge remains a conjecture.
Deep double descent
Nakkiran, Kaplun, Bansal, Yang, Barak and Sutskever (2019) showed the phenomenon in real deep networks in three variants.
Model-wise. Families of ResNet18 with four stage widths ( is standard ResNet18) and five-layer CNNs: four Conv-BatchNorm-ReLU-MaxPool blocks of widths with max pooling and a final linear layer (at it has parameters). In paper figure 1, ResNet18 on CIFAR-10 with 15% noisy labels, trained with Adam at rate for 4000 epochs, has test error versus rising near zero training error then falling again. “Label noise ” means each example retains its label with probability and otherwise gets a uniformly sampled wrong label, drawn once. Noise emphasizes the peak; more data moves the threshold right (the model needs more capacity to interpolate); and peaks occur without added noise, for example CNN on CIFAR-100.
Epoch-wise. With a fixed large model, test error versus training time falls, rises and falls again (figures 9 and 10, ResNet18 on CIFAR-10 with 20% noise). Small models that never interpolate improve monotonically; medium ones that barely interpolate at the end trace a U where early stopping helps; large ones pass the threshold mid-training and leave it. With 10% noise, final error can be lower than the first minimum.
Sample-wise. In IWSLT’14 German-English translation with Transformers, multiplying training data by 4.5 (4000 to 18,000 sentences) worsens the model over a size range (figure 3): more data shift the threshold right and a formerly comfortably overparameterized model enters the critical regime. For CNNs on CIFAR-10 there is a width range where quadrupling data does not improve error (figure 11a).
To unify them they define a complexity measure depending on the full procedure, not architecture alone.
The informal generalized double-descent hypothesis (Hypothesis 1) says: if , any change increasing effective complexity reduces test error; if , likewise; if , it may increase or decrease it. The three variants move through the same critical regime differently: enlarging the model or training longer increases EMC; adding data increases . Deep double descent comprises these three phenomena in networks trained with SGD or Adam, explained by EMC relative to . The appendix adds a fourth axis: for ResNet18 on CIFAR-10 (20% noise, SGD) and weight decay from 0 to 0.1, error versus regularization traces the same shape because greater decay means lower EMC.
Two qualifications from the paper prevent misunderstanding. First, its appendix E.2.3 title is literal: optimally chosen early stopping has no double descent, and with it more samples always help in their translation experiments. Second, epoch-wise double descent is not simply “late overfitting” fixed by stopping early: stopping at the first minimum can leave a model worse than the final trained model.
Lab: deep double descent on your GPU
The lab reproduces a reduced protocol: five-layer CNN with variable width , CIFAR-10 subset with 20% noisy labels, no augmentation, Adam at rate and batches of 128 as in the paper, but fewer data and epochs to fit an 8 GB GPU. It records training error against noisy labels and test error against clean labels at logarithmically spaced epochs, test error at the epoch selected by early stopping on noisy validation, and repeats selected widths with decoupled weight decay (AdamW). Data come from the pinned Hugging Face CIFAR-10 copy (uoft-cs/cifar10), downloaded once and cached.
The full configuration (, 16 widths, 1000 epochs) is for you to run; ORYON_VERIFY_SHORT=1 runs a short end-to-end flow check. Due to duration the cell is excluded from automatic checks.
"""Double descent profundo: protocolo reducido de Nakkiran et al. (2019) para una GPU de 8 GB.
CNN de cinco capas [k, 2k, 4k, 8k] (Conv-BN-ReLU-MaxPool con pools [1, 2, 2, 8] y una lineal final),
subconjunto de CIFAR-10 con un 20 % de etiquetas ruidosas (una etiqueta incorrecta uniforme, sorteada una vez),
sin aumento de datos, Adam con lr = 1e-4 y lotes de 128. Se registran, para cada anchura k y a lo largo de las
épocas, el error de entrenamiento (respecto a las etiquetas ruidosas) y el error de test (respecto a las limpias).
Variantes: parada temprana con un conjunto de validación ruidoso y decaimiento de pesos.
ORYON_VERIFY_SHORT=1 ejecuta una versión corta (menos datos, anchuras y épocas) que comprueba el flujo.
"""
import json
import math
import os
import time
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import io as _io
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cudnn.benchmark = True
if SHORT:
N_TRAIN, N_VAL, N_TEST = 4000, 1000, 5000
WIDTHS = [2, 3, 4, 5, 6, 8, 10, 12, 16, 24, 32]
EPOCHS = 150
WD_WIDTHS = [4, 6, 8, 12]
else:
N_TRAIN, N_VAL, N_TEST = 10000, 2000, 10000
WIDTHS = [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64]
EPOCHS = 1000
WD_WIDTHS = [4, 6, 8, 10, 12, 16, 24, 32, 64]
NOISE, LR, BATCH, WD = 0.2, 1e-4, 128, 1.0 # WD: decaimiento desacoplado de AdamW
LOG_EPOCHS = sorted({int(round(x)) for x in np.geomspace(1, EPOCHS, 40)})
OUT = Path(os.environ.get('ORYON_DD_OUTPUT', 'deep-double-descent.json'))
# ---------------------------------------------------------------- datos
def load_cifar(split, rows):
"""CIFAR-10 desde la caché de Hugging Face (uoft-cs/cifar10): solo se decodifican las filas pedidas."""
path = hf_hub_download('uoft-cs/cifar10', f'plain_text/{split}-00000-of-00001.parquet', repo_type='dataset',
revision='0b2714987fa478483af9968de7c934580d0bb9a2') # versión fijada
t = pq.read_table(path)
imgs = t.column('img').take(rows).to_pylist()
X = np.stack([np.array(Image.open(_io.BytesIO(d['bytes'])).convert('RGB')) for d in imgs])
return torch.tensor(X).permute(0, 3, 1, 2).float() / 255, torch.tensor(t.column('label').take(rows).to_numpy())
gen = np.random.default_rng(0)
idx = gen.permutation(50000)[: N_TRAIN + N_VAL]
X, y_clean = load_cifar('train', idx)
mean, std = X[:N_TRAIN].mean((0, 2, 3), keepdim=True), X[:N_TRAIN].std((0, 2, 3), keepdim=True)
X = (X - mean) / std
# ruido de etiquetas: con probabilidad NOISE, una etiqueta incorrecta uniforme (fija para todo el entrenamiento)
flip = torch.tensor(gen.random(len(idx)) < NOISE)
shift = torch.tensor(gen.integers(1, 10, len(idx)))
y_noisy = torch.where(flip, (y_clean + shift) % 10, y_clean)
Xtr, ytr = X[:N_TRAIN].to(device), y_noisy[:N_TRAIN].to(device)
Xva, yva = X[N_TRAIN:].to(device), y_noisy[N_TRAIN:].to(device)
tidx = gen.permutation(10000)[:N_TEST]
Xte_raw, yte = load_cifar('test', tidx)
Xte, yte = ((Xte_raw - mean) / std).to(device), yte.to(device)
print(f'n = {N_TRAIN}, etiquetas cambiadas: {flip[:N_TRAIN].float().mean():.3f}, test limpio: {N_TEST}')
# ---------------------------------------------------------------- modelo
def make_cnn(k: int) -> nn.Module:
layers, c_in = [], 3
for c_out, pool in zip([k, 2 * k, 4 * k, 8 * k], [1, 2, 2, 8]):
layers += [nn.Conv2d(c_in, c_out, 3, padding=1), nn.BatchNorm2d(c_out), nn.ReLU()]
if pool > 1:
layers.append(nn.MaxPool2d(pool))
c_in = c_out
return nn.Sequential(*layers, nn.Flatten(), nn.Linear(8 * k, 10))
print('parámetros con k = 64:', sum(p.numel() for p in make_cnn(64).parameters()))
@torch.no_grad()
def error(model, Xs, ys):
model.eval()
wrong = 0
for i in range(0, len(Xs), 1000):
with torch.autocast('cuda', dtype=torch.bfloat16, enabled=device.type == 'cuda'):
wrong += (model(Xs[i:i + 1000]).argmax(1) != ys[i:i + 1000]).sum().item()
model.train()
return wrong / len(Xs)
def train(k: int, wd: float = 0.0, seed: int = 0):
torch.manual_seed(seed)
model = make_cnn(k).to(device).to(memory_format=torch.channels_last)
opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=wd) if wd > 0 else torch.optim.Adam(model.parameters(), lr=LR)
g = torch.Generator(device=device).manual_seed(seed)
hist = []
for ep in range(1, EPOCHS + 1):
perm = torch.randperm(N_TRAIN, device=device, generator=g)
for i in range(0, N_TRAIN, BATCH):
b = perm[i:i + BATCH]
with torch.autocast('cuda', dtype=torch.bfloat16, enabled=device.type == 'cuda'):
loss = F.cross_entropy(model(Xtr[b]), ytr[b])
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
if ep in LOG_EPOCHS:
hist.append({'epoch': ep, 'train': error(model, Xtr, ytr), 'val': error(model, Xva, yva), 'test': error(model, Xte, yte)})
del model, opt
if device.type == 'cuda':
torch.cuda.empty_cache()
return hist
results = {'config': {'n_train': N_TRAIN, 'n_val': N_VAL, 'n_test': N_TEST, 'noise': NOISE, 'lr': LR,
'batch': BATCH, 'epochs': EPOCHS, 'wd': WD, 'short': SHORT}, 'runs': []}
t0 = time.time()
for k in WIDTHS:
h = train(k)
params = sum(p.numel() for p in make_cnn(k).parameters())
best = min(h, key=lambda r: r['val'])
results['runs'].append({'k': k, 'wd': 0.0, 'params': params, 'history': h})
print(f"k={k:3d} params={params:8d} final: train {h[-1]['train']:.3f} test {h[-1]['test']:.3f}"
f" | parada temprana (época {best['epoch']}): test {best['test']:.3f} [{time.time() - t0:.0f} s]")
for k in WD_WIDTHS:
h = train(k, wd=WD)
results['runs'].append({'k': k, 'wd': WD, 'params': None, 'history': h})
print(f"k={k:3d} wd={WD} final: train {h[-1]['train']:.3f} test {h[-1]['test']:.3f} [{time.time() - t0:.0f} s]")
OUT.write_text(json.dumps(results), encoding='utf-8')
print('guardado en', OUT)npm run lab and open the connection link.Before launching, check architecture: at the code prints parameters, exactly the paper’s figure. The interactive shows the short verification run (, 150 epochs, one seed, 5000 clean test images). It is small and should be read as such.
The results, with numbers. Model-wise, final test error falls from at to at , is nearly flat between and (, , , and ) while training error falls from to , then clearly falls again beyond the threshold: at , at and at . There is no sharp peak: one-point increases at and are within one-seed standard error (about 0.7 points). The hypothesis pattern does appear: while EMC is below , extra capacity barely helps because it is spent memorizing roughly 790 changed labels; once comfortably above, it helps again. Epoch-wise, critical widths show a U: at test is minimal at epoch 61 () and worsens to at the end, when training error reaches ; wide models barely move after interpolation ( ends at , minimum ). Thus early stopping with noisy validation gains 2.5 points at ( versus ) and almost nothing at and . Weight decay (AdamW with decoupled coefficient 1.0, repeated at four widths) helps where the problem lies: versus at , versus at , versus at and versus at .
Why does the paper’s peak not appear? The short run cuts precisely what produces it. In Nakkiran et al. each model trains 4000 epochs, so all reach their final state and critical models barely end up interpolating noise; with 150 epochs threshold widths are still midway ( has final training error ), and threshold movement with training time is epoch-wise double descent. One seed and 4000 images add noise. The full lab configuration trains 1000 epochs on with 16 widths; according to the paper, training to completion with 20% noise gives a test-error maximum near the interpolating width (figure 12 shows this ridge for five-layer CNNs on CIFAR-10 with 20% noise over the model-size and sample-count plane). Run it and repeat with another seed before interpreting one-point differences.
How many parameters does a model have?
Everything above places parameter count on the horizontal axis. Curth, Jeffares and van der Schaar (2023) argue that axis creates the apparent mystery. Reanalyzing Belkin et al., they show that in all three nonparametric cases (trees, boosting and Fourier-feature regression) the axis combines two distinct mechanisms applied sequentially:
- For trees, first increase maximum leaf count of one tree; once it cannot grow further, increase ensemble tree count . Separately, error is U-shaped (or L-shaped) in and L-shaped in ; double descent appears only when curves are joined.
- For boosting, first boosting rounds and then ensemble size, with the same conclusion.
- In random-feature regression the second mechanism is hidden. Their Proposition 1: with , the minimum-norm interpolator is equivalent to building a basis of vectors from right singular vectors of without using labels, then fitting ordinary least squares in that basis. Beyond the model still fits coefficients; increasing improves the basis without supervision. They separate axes with principal-component regression: number of components used gives a classical U, and number of remaining features gives a decreasing curve.
To measure complexity without parameter counting, they use that all these methods are smoothers: prediction is , with weights on training labels (for ridge, ). If noise is homoscedastic, , leading to their effective parameter count on an input set :
On training inputs this is the classical variance degrees-of-freedom measure in terms of smoother eigenvalues , exactly for least squares with and related to ridge effective dimension . But with and it stays forever, since each training point predicts its own label. The key is measuring on new inputs: . They find effective test complexity never increases beyond the threshold, although raw parameter count does. The second descent is decreasing complexity, and plotting error against recovers classical shapes.
In the isotropic linear model one calculation shows this: and . That is, , and estimator variance is exactly . The variance peak is an effective-parameter peak, and its subsequent decline causes the second descent.
def effective_params(kind, sigma, p_list, lam=0.0):
rows = []
for p in p_list:
pt, ptr, te = [], [], []
for s in range(S):
F, y, Ft = draw(s, p, sigma, kind)
U, sv, Vt = np.linalg.svd(F, full_matrices=False)
keep = sv > 1e-10 * sv[0]
U, sv, Vt = U[:, keep], sv[keep], Vt[keep]
k = 1 / sv if lam == 0 else sv / (sv**2 + lam)
Smat = (Ft @ Vt.T) * k @ U.T # fila j: pesos ŝ(x_j) del suavizador en el punto de test j
h = sv * k # autovalores del suavizador en entrenamiento
pt.append(n * np.mean(np.sum(Smat**2, axis=1)))
ptr.append(np.sum(h**2))
te.append(np.mean((Smat @ y - f_test) ** 2))
rows.append((p, np.mean(ptr), np.mean(pt), np.mean(te)))
return rows
print(' p p̂ train p̂ test test')
for p, a, b_, c in effective_params('fourier', 0.2, [5, 10, 20, 30, 36, 40, 44, 50, 80, 160]):
print(f'{p:4d} {a:7.1f} {b_:10.1f} {c:9.3f}')is through and remains . rises from at to at , at , over at , then falls: at , at , at . Test-error column matches the first cell at common values (same seeds) and follows the same pattern. At the model has 160 raw and about 97 effective test parameters; at , 30 raw and about 202 effective: the larger model is simpler by this measure.
The critique does not say double descent is false; it says “parameter count” should not replace norms, effective parameters or EMC as a capacity measure, and apparent contradictions of the classical U-curve challenge a poorly chosen complexity measure. Norm-based bounds (studied with benign interpolation next lesson) and EMC itself are attempts in that direction.
The library version
In scikit-learn, RBFSampler produces random Fourier features for Gaussian kernel by sampling frequencies from ; at these are the same used here. LinearRegression solves least squares with lstsq, returning the minimum-norm solution in the underdetermined case, and RidgeCV efficiently chooses by leave-one-out cross-validation.
from sklearn.kernel_approximation import RBFSampler
from sklearn.linear_model import LinearRegression, RidgeCV
rng = np.random.default_rng(11)
X_tr = rng.normal(size=(n, d))
y_tr = f_star(X_tr) + 0.2 * rng.normal(size=n)
print(' p mínima norma RidgeCV (LOO)')
for p in [20, 40, 160]:
mn_err, rd_err = [], []
for s in range(8):
rff = RBFSampler(gamma=0.5 / d, n_components=p, random_state=s).fit(X_tr)
F, Ft = rff.transform(X_tr), rff.transform(X_test)
lin = LinearRegression(fit_intercept=False).fit(F, y_tr) # lstsq: solución de mínima norma
rcv = RidgeCV(alphas=np.logspace(-6, 1, 15), fit_intercept=False).fit(F, y_tr)
mn_err.append(np.mean((lin.predict(Ft) - f_test) ** 2))
rd_err.append(np.mean((rcv.predict(Ft) - f_test) ** 2))
print(f'{p:4d} {np.mean(mn_err):10.3f} {np.mean(rd_err):10.3f}')With one training set and 8 feature draws, the pattern is the same: minimum norm goes from at to at and at ; RidgeCV gives , and without a peak. The much lower value at than in the first cell is not a contradiction: it averages 8 samples of a heavy-tailed variable and depends on how close the worst smallest singular value is to zero.
Common mistakes
Exercises
Step 1 of 4. What is ?
More than one answer may be correct.
min_norm_rf_risk(n, p_list, d, noise, seeds, rng) returning an array of mean minimum-norm-interpolator test error for each in p_list. Model: inputs , target , labels with ; ReLU features with entries ; fit ; test error on 500 test points. For each of seeds repetitions, draw new data and, for each , new features; use only rng (a np.random.Generator) for randomness. Tests check that the maximum is at and error at is below .import numpy as np
def min_norm_rf_risk(n, p_list, d, noise, seeds, rng):
"""Error de test medio del interpolador de mínima norma con p características ReLU, para cada p."""
risks = np.zeros(len(p_list))
# tu código: conjunto de test, bucle de semillas (datos nuevos), bucle de p (características nuevas),
# ajuste con la pseudoinversa y error frente a f* en test
return risksSummary
- The interpolation threshold is the smallest capacity with zero training error; for least squares with features, . Belkin et al. (2019) showed test error peaks there and falls to the right with random features, networks, forests and boosting.
- With isotropic Gaussian design, exact risk is for and for ; at it is infinite. Asymptotically (Hastie et al.), and .
- The peak is variance; without noise and misspecification there is no peak. In random features, peak variance is mostly feature-data interaction (Adlam and Pennington), addressed by model averaging.
- In the well-specified isotropic model the global minimum is at ; an overparameterized global minimum requires new features to bring signal (misspecification, random features).
- Ridge with makes risk monotone in ; validated also removes the random-feature peak.
- Deep networks show model-wise, epoch-wise and sample-wise double descent, unified by training procedure effective complexity (EMC).
- Parameter count is a poor complexity axis: measured on new points, effective complexity falls beyond the threshold (Curth et al.), so the second descent decreases complexity.