Module contents
Lesson 17 of 20Research 120 min

Benign overfitting and the puzzle of deep generalization

Deep networks can fit random labels and still generalize from real labels. This rules out explanations that depend only on the hypothesis class. Reproduce the random-label experiment, study effective ranks and benign interpolation in linear regression, classify benign, tempered, and catastrophic interpolation, and examine spectral margin bounds and the limits of uniform convergence.

After this lesson you can

  • Reproduce the random-label experiment and explain which explanations it rules out.
  • State the effective-rank conditions for benign linear interpolation and explain how the covariance separates signal from a tail that absorbs noise.
  • Classify interpolation by nearest neighbors, singular-kernel Nadaraya–Watson, unregularized kernels, and neural networks as benign, tempered, or catastrophic.
  • Compute a spectrally normalized margin bound and compare it with a trained network’s observed error.
  • Explain Nagarajan and Kolter’s argument about the limits of uniform convergence.
  • Compare empirical measures of generalization examined by Jiang et al. and Dziugaite et al.

Before you start

The experiment that made theorists rethink generalization

In 2017, Zhang, Bengio, Hardt, Recht and Vinyals published a straightforward experiment. Take a network that works well on CIFAR-10, replace the training labels with random ones, and train with the same architecture, optimizer and hyperparameters. Training error reaches zero. Test error is about 90%, the chance rate for ten classes, because training labels tell the model nothing about the images.

Table 1 gives the numbers. A reduced Inception network with 1 649 4021\,649\,402 parameters reaches 100 %100\,\% training accuracy on both real and random labels. Test accuracy is 85.75 %85.75\,\% with real labels, without data augmentation or weight decay, and 9.78 %9.78\,\% with random labels. AlexNet, with 1 387 7861\,387\,786 parameters, achieves 76.07 %76.07\,\% versus 9.86 %9.86\,\%. An MLP with three 512-unit hidden layers and 1 735 1781\,735\,178 parameters achieves 52.39 %52.39\,\% versus 10.48 %10.48\,\%. On ImageNet, with a million random labels spread across a thousand classes, Inception V3 reaches 95.20 %95.20\,\% top-1 training accuracy with unchanged hyperparameters. Networks also fit when the inputs are Gaussian noise or each image’s pixels have been randomly permuted.

Three observations matter:

  1. These networks have enough effective capacity to memorize the entire training set.
  2. Random labels remain easy to optimize. Training time increases by only a small constant factor in Figure 1b.
  3. Randomization changes the data while holding the model, algorithm and parameter count fixed.

The same procedure generalizes on one dataset and fails to generalize on another. An explanation must distinguish the two cases, so it must depend on the data. This lesson first establishes what the experiment rules out. It then analyzes overparameterized linear regression, where interpolating noise can be harmless, and classifies interpolating methods by what happens to their noise. Finally it studies norm- and margin-based neural network bounds and Nagarajan and Kolter’s argument about the limits of uniform convergence.

Run the race in your browser

InteractiveReal labels versus random labels
Orange network’s decision regions: red for class 1 and blue for class 0. The dashed curve is the true boundary.
20 %
The orange network sees 0 wrong labels among 100 points (outlined). Only replacements that differ from the true label count, roughly p/2p/2 of the total. Test error uses clean labels. Chance error is 50%.
Three identical MLPs (two hidden layers of 48 ReLUs, the same initialization, full-batch Adam with learning rate 0.01) train in parallel on the same 100 points in [−1,1]2[-1, 1]^2, with true class x2>0.5sin⁡(πx1)x_2 > 0.5\sin(\pi x_1). Only the fraction pp of labels replaced by a uniform draw varies: p=0p = 0 (teal), the chosen pp (orange), and p=1p = 1 (purple). At right, training error (solid, against each network’s labels) and test error (dashed, on 600 clean-label points) versus Adam steps. Each network stops 300 steps after fitting. At left, the orange model’s decision regions and data, with rings around incorrect labels. All three reach zero training error. Noisy labels take much longer to fit, and test error rises with pp, reaching chance at p=1p = 1.

For p=0.2p = 0.2 the orange network reaches zero training error by drawing islands around incorrect labels. Between the islands the decision boundary stays near the true boundary. Increase pp and the islands take over the plane. Compare the steps at which each network fits. Isolating a few wrong labels inside the opposite class region can take as many steps as fitting entirely unstructured labels, or more. The picture suggests that the model learns signal globally and noise locally. Benign interpolation theory formalizes this intuition for linear models. In practice, memorized noise can leave neural networks with residual test error even as the dataset grows.

With KK classes and replacement probability pp, the expected fraction of incorrect labels is p(1−1/K)p(1 - 1/K). A replacement matches the true class with probability 1/K1/K. In the two-class widget the fraction is p/2p/2. For CIFAR-10 with p=0.2p = 0.2, it is 18 %18\,\%.

Fitting arbitrary labels takes a shallow network

It is unsurprising that a network with millions of parameters can fit 50 00050\,000 labels. Zhang et al. make the expressiveness claim precise with an explicit construction.

Proof

Consider c(z)=∑j=1nwjmax⁡{⟨a,z⟩−bj,0}c(\vb{z}) = \sum_{j=1}^n w_j \max\{\inner{\vb{a}}{\vb{z}} - b_j, 0\}, with a∈Rd\vb{a} \in \R^d and b,w∈Rn\vb{b}, \vb{w} \in \R^n. Its single hidden layer has nn units with shared direction a\vb{a} and different thresholds, for 2n+d2n + d weights in total. The zi\vb{z}_i are distinct, so directions a\vb{a} with ⟨a,zi⟩=⟨a,zj⟩\inner{\vb{a}}{\vb{z}_i} = \inner{\vb{a}}{\vb{z}_j} for some i≠ji \ne j form a finite union of measure-zero hyperplanes. There is therefore a direction a\vb{a} with distinct projections xi=⟨a,zi⟩x_i = \inner{\vb{a}}{\vb{z}_i}. Reorder the points so x1<⋯<xnx_1 < \dots < x_n and choose interleaved thresholds b1<x1<b2<x2<⋯<bn<xnb_1 < x_1 < b_2 < x_2 < \dots < b_n < x_n. Matrix Aij=max⁡{xi−bj,0}\mat{A}_{ij} = \max\{x_i - b_j, 0\} is lower triangular because i<ji < j implies xi<bjx_i < b_j. Its diagonal xi−bix_i - b_i is positive, which makes it invertible. The system Aw=y\mat{A}\vb{w} = \vb{y} has a solution, so c(zi)=(Aw)i=yic(\vb{z}_i) = (\mat{A}\vb{w})_i = y_i.

∎

The construction reduces to a linear solve. The cell uses n=200n = 200 points in dimension 30723072, the size of a CIFAR-10 image, and random labels.

[ ]Zhang et al.’s network fits random labelsBrowser
import numpy as np
rng = np.random.default_rng(0)
n, d = 200, 3072                              # tantos píxeles como una imagen de CIFAR-10
Z = rng.standard_normal((n, d))
y = rng.integers(0, 10, n).astype(float)      # etiquetas aleatorias (como números reales)

a = rng.standard_normal(d)                    # dirección genérica: las proyecciones son distintas
x = Z @ a
order = np.argsort(x); xs = x[order]
b = np.empty(n)                               # umbrales intercalados: b_1 < x_1 < b_2 < x_2 < ...
b[0] = xs[0] - 1.0
b[1:] = (xs[:-1] + xs[1:]) / 2
A = np.maximum(xs[:, None] - b[None, :], 0)   # A_ij = max(x_i - b_j, 0): triangular inferior
w = np.linalg.solve(A, y[order])

pred = np.maximum((Z @ a)[:, None] - b[None, :], 0) @ w   # la red c(z) = sum_j w_j relu(<a, z> - b_j)
print('parámetros: n + n + d =', 2 * n + d)
print('¿A triangular inferior?', np.allclose(A, np.tril(A)), '  menor elemento de su diagonal: %.3g' % np.diag(A).min())
print('error máximo de ajuste: %.2e' % np.abs(pred - y).max())
print('norma de w: %.3g' % np.linalg.norm(w))

The fit is exact up to rounding. The norm of w\vb{w} is on the order of 10410^4 because the thresholds are close together and the system is poorly conditioned. This suggests examining data-dependent quantities such as norms and margins to distinguish memorization from generalization.

What the experiment rules out

Recall the empirical Rademacher complexity of a class H\Hyp of functions valued in {−1,1}\{-1, 1\} on the sample:

R^S(H)=Eσ[sup⁡h∈H1n∑i=1nσih(xi)],\hat{\mathfrak{R}}_S(\Hyp) = \E_{\vb{\sigma}}\Big[\sup_{h \in \Hyp} \frac{1}{n}\sum_{i=1}^n \sigma_i h(\vb{x}_i)\Big],

where σi\sigma_i are independent uniform signs. It measures how well H\Hyp can fit random labels. If for each assignment of signs some h∈Hh \in \Hyp gives h(xi)=σih(\vb{x}_i) = \sigma_i, the supremum is 1, so R^S(H)=1\hat{\mathfrak{R}}_S(\Hyp) = 1 attains its maximum. For 0–1 loss, the Rademacher bound gives, with probability at least 1−δ1 - \delta, R(h)≤R^(h)+R^S(H)+3log⁡(2/δ)/(2n)R(h) \le \hat{R}(h) + \hat{\mathfrak{R}}_S(\Hyp) + 3\sqrt{\log(2/\delta)/(2n)} for all h∈Hh \in \Hyp. It becomes vacuous with R^S(H)=1\hat{\mathfrak{R}}_S(\Hyp) = 1. The same problem arises with VC dimension, which must be at least nn.

The experiment supports a more general argument.

Proof

The bound must hold under D1\mathcal{D}_1. If B(H,n,δ)<gB(\Hyp, n, \delta) < g, the event that A\mathcal{A} returns an hh with gap at least gg has probability greater than δ\delta, and the bound fails on that event. This is a contradiction. Because BB is distribution-free, the same number is the guarantee under the real distribution.

∎

On CIFAR-10, g≈0.9g \approx 0.9. Such a bound can at best guarantee test error 90 %90\,\% for a network whose actual accuracy is 86 %86\,\%. The same reasoning applies to an algorithm-wide bound. A bound depending only on A\mathcal{A} and nn, such as one based on uniform stability, must also cover training with random labels, as Zhang et al. point out.

Several explanations remain possible:

  • Bounds that depend on the learned predictor and therefore on the data. Its margin, norms, distance from initialization or local loss flatness can differ between real and random labels. A bound can be small in one case and vacuous in the other.
  • The algorithm’s implicit bias. Gradient descent selects a particular interpolator, such as a minimum-norm solution for linear models or a maximum-margin classifier under suitable conditions. See implicit regularization. The relevant class can be the predictors the algorithm produces on data like these.
  • PAC-Bayes bounds with data-dependent posteriors. Dziugaite and Roy (2017) obtained nonvacuous bounds for neural networks on MNIST by optimizing the posterior in a PAC-Bayes bound.

Removing data augmentation and weight decay drops Inception test accuracy from 89.0589.05 to 85.75 %85.75\,\% in Table 1. The effect is appreciable, but random labels reduce it to 9.78 %9.78\,\%. The paper argues that explicit regularizers help while leaving the main explanation of generalization open.

Benign interpolation in linear regression

Overparameterized linear regression with the minimum-norm interpolator gives a complete answer in one setting. Gradient descent from zero converges to this solution. The double descent lesson computed its risk in the isotropic proportional regime. Here the question is which covariance structures make interpolating noise harmless, with risk converging to the optimum.

The model

We follow the Gaussian version of Bartlett, Long, Lugosi and Tsigler (2020). Inputs are x=Σ1/2z\vb{x} = \mat{\Sigma}^{1/2}\vb{z} with z∼N(0,I)\vb{z} \sim \Normal(\vb{0}, \mat{I}), hence x∼N(0,Σ)\vb{x} \sim \Normal(\vb{0}, \mat{\Sigma}). This is a multivariate Gaussian obtained by an affine transformation of a standard Gaussian, in finite dimension pp or a separable Hilbert space. Responses are y=x⊤θ∗+εy = \vb{x}\T\vb{\theta}^* + \eps, with ε∼N(0,σ2)\eps \sim \Normal(0, \sigma^2) independent of x\vb{x}. The eigenvalues of Σ\mat{\Sigma} are λ1≥λ2≥…\lambda_1 \ge \lambda_2 \ge \dots, with ∑iλi<∞\sum_i \lambda_i < \infty. The paper allows the components of z\vb{z} to be independent and sub-Gaussian, and noise conditional on x\vb{x} to be sub-Gaussian with conditional variance at least σ2\sigma^2. Gaussian noise suffices to illustrate the argument.

With nn observations stored as rows of X∈Rn×p\mat{X} \in \R^{n\times p} and rank⁡(Σ)>n\rank(\mat{\Sigma}) > n, matrix XX⊤\mat{X}\mat{X}\T is invertible almost surely. The minimum-norm interpolator is

θ^=X⊤(XX⊤)−1y.\hat{\vb{\theta}} = \mat{X}\T(\mat{X}\mat{X}\T)\inv\vb{y}.

Its excess risk is R(θ^)=Ex,y[(y−x⊤θ^)2]−E[(y−x⊤θ∗)2]=(θ^−θ∗)⊤Σ(θ^−θ∗)R(\hat{\vb{\theta}}) = \E_{\vb{x}, y}[(y - \vb{x}\T\hat{\vb{\theta}})^2] - \E[(y - \vb{x}\T\vb{\theta}^*)^2] = (\hat{\vb{\theta}} - \vb{\theta}^*)\T\mat{\Sigma}(\hat{\vb{\theta}} - \vb{\theta}^*).

The first exercise proves this in four algebraic steps. Bias comes from the component of θ∗\vb{\theta}^* orthogonal to the row space. Variance comes from noise ε\vb{\eps}, which the interpolator fits exactly into θ^\hat{\vb{\theta}} and carries into predictions on new x\vb{x}. Two notions of dimension explain when tr⁡(C)\tr(\mat{C}) is small.

Effective ranks

Both quantify how many directions contribute significantly in the tail {λi}i>k\{\lambda_i\}_{i>k}. When the tail contains mm equal eigenvalues, rk=Rk=mr_k = R_k = m. If one eigenvalue dominates, both ranks approach 1. They are related to the effective dimension of kernel ridge regression. rkr_k compares tail mass with its largest eigenvalue, while RkR_k is the reciprocal of its purity, ∑λi2/(∑λi)2\sum\lambda_i^2/(\sum\lambda_i)^2.

Proof

Write s1=∑i>kλis_1 = \sum_{i>k}\lambda_i and s2=∑i>kλi2s_2 = \sum_{i>k}\lambda_i^2. Since λk+1\lambda_{k+1} is the largest tail eigenvalue, s1≥λk+1s_1 \ge \lambda_{k+1}. This gives rk≥1r_k \ge 1 and s2=∑i>kλi⋅λi≤λk+1s1s_2 = \sum_{i>k}\lambda_i\cdot\lambda_i \le \lambda_{k+1}s_1, hence Rk=s12/s2≥s1/λk+1=rkR_k = s_1^2/s_2 \ge s_1/\lambda_{k+1} = r_k. Finally, s2≥λk+12s_2 \ge \lambda_{k+1}^2 gives Rk≤s12/λk+12=rk2R_k \le s_1^2/\lambda_{k+1}^2 = r_k^2.

∎

The theorem

Here σy2\sigma_y^2 is the sub-Gaussian constant of the noise, equal to σ2\sigma^2 in the Gaussian case. Matching upper and lower orders characterize the variance. The bias bound is upper-only, and the paper adds a lower bound that makes it necessary in the worst case over θ∗\vb{\theta}^*. Interpolation is near optimal when r0(Σ)r_0(\mat{\Sigma}) is small relative to nn, k∗k^* is small relative to nn, and Rk∗(Σ)R_{k^*}(\mat{\Sigma}) is large relative to nn.

Proof sketch

Focus on the variance. Write Σ=∑iλivivi⊤\mat{\Sigma} = \sum_i \lambda_i\vb{v}_i\vb{v}_i\T and zi=Xvi/λi∈Rn\vb{z}_i = \mat{X}\vb{v}_i/\sqrt{\lambda_i} \in \R^n for the normalized columns of X\mat{X} in the covariance eigenbasis. They are independent N(0,In)\Normal(\vb{0}, \mat{I}_n) vectors. Then A:=XX⊤=∑iλizizi⊤\mat{A} := \mat{X}\mat{X}\T = \sum_i \lambda_i\vb{z}_i\vb{z}_i\T and by Lemma 8,

tr⁡(C)=∑iλi2 zi⊤A−2zi.\tr(\mat{C}) = \sum_i \lambda_i^2\,\vb{z}_i\T\mat{A}^{-2}\vb{z}_i.

Split the sum into the first kk directions and the tail. Let Ak=∑i>kλizizi⊤\mat{A}_k = \sum_{i>k}\lambda_i\vb{z}_i\vb{z}_i\T be the tail contribution to the Gram matrix.

Step 1. The tail Gram matrix is nearly a scalar multiple of the identity. By Lemma 9, with probability at least 1−2e−n/c1 - 2e^{-n/c}, every eigenvalue of Ak\mat{A}_k lies between 1c∑i>kλi−cλk+1n\frac{1}{c}\sum_{i>k}\lambda_i - c\lambda_{k+1}n and c(∑i>kλi+λk+1n)c\big(\sum_{i>k}\lambda_i + \lambda_{k+1}n\big). When rk≥bnr_k \ge bn, the term λk+1n\lambda_{k+1}n is a small fraction of ∑i>kλi\sum_{i>k}\lambda_i, and Ak≈s In\mat{A}_k \approx s\,\mat{I}_n with s=∑i>kλis = \sum_{i>k}\lambda_i, up to constants. The intuition is a law of large numbers. Ak\mat{A}_k adds many small rank-one matrices in random directions, and no single direction dominates. This is precisely the condition rk≥bnr_k \ge bn. Tail mass divided by the largest tail eigenvalue must exceed nn.

Step 2. The tail absorbs label noise. If A≈sIn\mat{A} \approx s\mat{I}_n along the tail directions, each contribution i>ki > k is approximately λi2∥zi∥2/s2≈nλi2/s2\lambda_i^2\norm{\vb{z}_i}^2/s^2 \approx n\lambda_i^2/s^2, giving the sum

∑i>knλi2s2=n ∑i>kλi2(∑i>kλi)2=nRk(Σ).\sum_{i>k}\frac{n\lambda_i^2}{s^2} = n\,\frac{\sum_{i>k}\lambda_i^2}{\big(\sum_{i>k}\lambda_i\big)^2} = \frac{n}{R_k(\mat{\Sigma})}.

Step 3. The signal directions behave like ridge regression. For i≤ki \le k, the Sherman–Morrison identity with A−i=A−λizizi⊤\mat{A}_{-i} = \mat{A} - \lambda_i\vb{z}_i\vb{z}_i\T gives

λi2zi⊤A−2zi=λi2zi⊤A−i−2zi(1+λizi⊤A−i−1zi)2≈λi2n/s2(1+λin/s)2≈1nsi λin≫s,\lambda_i^2\vb{z}_i\T\mat{A}^{-2}\vb{z}_i = \frac{\lambda_i^2\vb{z}_i\T\mat{A}_{-i}^{-2}\vb{z}_i}{(1 + \lambda_i\vb{z}_i\T\mat{A}_{-i}\inv\vb{z}_i)^2} \approx \frac{\lambda_i^2 n/s^2}{(1 + \lambda_i n/s)^2} \approx \frac{1}{n} \quad\text{si } \lambda_i n \gg s,

This is the variance per coordinate of ordinary least squares. The first kk directions sum to k/nk/n. Together the two parts give tr⁡(C)≈k/n+n/Rk\tr(\mat{C}) \approx k/n + n/R_k. Lemma 17 shows that the best kk, up to constants, is the smallest one satisfying rk≥bnr_k \ge bn, namely k∗k^*.

Step 4. Bound the bias. The tail imposes an effective ridge penalty of size ss on the signal directions. The interpolator shrinks each signal coordinate by a factor on the order of s/(nλi+s)s/(n\lambda_i + s). When ss is comparable to nλ1n\lambda_1, this suppresses the signal. A small r0(Σ)/n=tr⁡(Σ)/(n∥Σ∥)r_0(\mat{\Sigma})/n = \tr(\mat{\Sigma})/(n\norm{\mat{\Sigma}}) ensures this implicit regularization preserves it. See Appendices J and K.

The first k∗k^* signal directions behave like least squares regularized by the tail. Noise spreads over many directions of very small variance, with total cost n/Rk∗n/R_{k^*}.

Which spectra are benign?

The paper’s Theorem 6 treats two families:

  1. Infinite dimension with fixed covariance. If λk=k−αln⁡−β(k+1)\lambda_k = k^{-\alpha}\ln^{-\beta}(k + 1), the covariance is benign exactly when α=1\alpha = 1 and β>1\beta > 1. Eigenvalues must decay fast enough to be summable, with finite r0r_0, but an overly fast decay can fail. With λk=k−2\lambda_k = k^{-2}, for example, ∑i>kλi≈1/k\sum_{i>k}\lambda_i \approx 1/k and λk+1≈1/k2\lambda_{k+1} \approx 1/k^2, so rkr_k grows only like kk, k∗k^* is on the order of bnbn, and k∗/nk^*/n does not vanish.
  2. Finite dimension with an isotropic floor. If λk,n=γk+εn\lambda_{k,n} = \gamma_k + \eps_n for k≤pnk \le p_n and 00 afterward, with γk=Θ(e−k/τ)\gamma_k = \Theta(e^{-k/\tau}), the sequence is benign exactly when pn=ω(n)p_n = \omega(n) and ne−o(n)=εnpn=o(n)n e^{-o(n)} = \eps_n p_n = o(n). Dimension grows faster than nn. Total isotropic tail mass grows more slowly than nn, without becoming exponentially small.

The second case gives a general picture of signal in a few directions and a nearly flat tail in dimension much larger than nn. Bartlett et al. conclude that overparameterization is essential to benign interpolation in this model.

Lab: reproduce the theorem’s predictions

The lab generates Gaussian observations with specified spectra, computes the minimum-norm interpolator and its exact risk conditional on X\mat{X}, then averages the bias θ∗TBθ∗\vb{\theta}^{*\mathsf{T}}\mat{B}\vb{\theta}^* and variance σ2tr⁡(C)\sigma^2\tr(\mat{C}) over four design matrices. It compares them with the theorem’s terms using b=1b = 1 to calculate k∗k^*. The theorem leaves the constants unspecified, so compare orders of magnitude and patterns.

[ ]Benign interpolation with four spectraBrowser
import numpy as np

def tail_spectrum(k, p_t, mass, alpha):
    """k autovalores de señal iguales a 1 y una cola de p_t autovalores con perfil i^(-alpha) y suma `mass`."""
    t = np.arange(1, p_t + 1) ** (-float(alpha))
    return np.concatenate([np.ones(k), mass * t / t.sum()])

def ranks(lam, n, b=1.0):
    """r_0, k* = min{k : r_k >= b n} y los rangos efectivos r_{k*}, R_{k*} (lam en orden decreciente)."""
    s1 = np.cumsum(lam[::-1])[::-1]          # s1[k] = suma de los autovalores de índice > k (desde 0)
    s2 = np.cumsum((lam ** 2)[::-1])[::-1]
    r = s1 / lam                              # r[k] = r_k(Sigma)
    ok = np.nonzero(r >= b * n)[0]
    if len(ok) == 0:
        return r[0], None, None, None
    k = ok[0]
    return r[0], k, r[k], s1[k] ** 2 / s2[k]

def min_norm_risk(lam, theta, n, reps, rng):
    """Sesgo theta^T B theta y tr(C) del interpolador de mínima norma, promediados en `reps` diseños."""
    bias, trC = 0.0, 0.0
    for _ in range(reps):
        X = rng.standard_normal((n, len(lam))) * np.sqrt(lam)   # filas x_i ~ N(0, Sigma)
        Gi = np.linalg.inv(X @ X.T)
        XS = X * lam                                            # X Sigma
        trC += np.trace(Gi @ (XS @ X.T) @ Gi) / reps            # tr((XX^T)^-1 X Sigma X^T (XX^T)^-1)
        u = theta - X.T @ (Gi @ (X @ theta))                    # (I - P) theta
        bias += np.sum(lam * u * u) / reps
    return bias, trC

rng = np.random.default_rng(0)
n, k, sigma = 50, 5, 0.5
presets = {'benigno': (100 * n, 0.1 * n, 0.0), 'cola corta': (int(1.5 * n), 0.1 * n, 0.0),
           'cola pesada': (100 * n, 3 * n, 0.0), 'cola empinada': (100 * n, 0.1 * n, 1.5)}
print(f'n = {n}, k = {k}, sigma^2 = {sigma**2}')
print(f"{'espectro':>14} {'r0/n':>6} {'k*':>4} {'R_k*/n':>7} {'sesgo':>7} {'varianza':>9} {'teoría':>8} {'exceso/s2':>9}")
for name, (p_t, mass, alpha) in presets.items():
    lam = tail_spectrum(k, p_t, mass, alpha)
    theta = np.zeros(len(lam)); theta[:k] = 1 / np.sqrt(k)
    r0, ks, rk, Rk = ranks(lam, n)
    b, tC = min_norm_risk(lam, theta, n, 4, rng)
    th = sigma**2 * (ks / n + n / Rk) if ks is not None else float('nan')
    print(f'{name:>14} {r0/n:6.3f} {str(ks):>4} {Rk/n if Rk else float("nan"):7.2f} {b:7.4f} {sigma**2*tC:9.4f} {th:8.4f} {(b+sigma**2*tC)/sigma**2:9.3f}')

The recorded run uses n=50n = 50, five signal directions of eigenvalue 1, and a unit-norm θ∗\vb{\theta}^* spread across those directions. Always predicting zero gives risk 1 in these units.

  • Benign: the flat tail has 5000=100n5000 = 100n eigenvalues of total mass 5=0.1n5 = 0.1n. The run gives k∗=5k^* = 5, Rk∗=100nR_{k^*} = 100n, variance 0.02670.0267 versus prediction σ2(k∗/n+n/Rk∗)=0.0275\sigma^2(k^*/n + n/R_{k^*}) = 0.0275, and bias 0.01240.0124. Excess risk is 16 %16\,\% of σ2\sigma^2, even after fitting all 50 labels with noise standard deviation 0.50.5.
  • Short tail: the same mass is spread over only 75=1.5n75 = 1.5n eigenvalues. Now Rk∗/n=1.5R_{k^*}/n = 1.5 and variance rises to 0.4640.464, nearly twice σ2\sigma^2. The prediction is 0.190.19. The factor of 2.4 is within the scale left open by the constants. The setup is also close to the interpolation threshold, p=80p = 80 versus n=50n = 50, where the previous lesson showed a variance spike.
  • Heavy tail: tail mass is 150=3n150 = 3n. This gives r0/n=3.1r_0/n = 3.1 and k∗=0k^* = 0 because the tail alone satisfies r0≥nr_0 \ge n. Variance is only 0.0040.004, and bias is 0.5760.576. The tail acts like a ridge penalty of size 150 against nλ1=50n\lambda_1 = 50 and suppresses the signal.
  • Steep tail: with profile i−1.5i^{-1.5} the tail is uneven. rkr_k exceeds nn only at k∗=31k^* = 31, comparable to nn. Variance is 0.170.17, or 69 %69\,\% of σ2\sigma^2.

The second experiment increases nn with a spectrum of the form in Theorem 6.2. It uses five signal directions and a flat tail with pn=n2/4p_n = n^2/4 eigenvalues and total mass n\sqrt{n}, so pn=ω(n)p_n = \omega(n) and εnpn=n=o(n)\eps_n p_n = \sqrt{n} = o(n).

[ ]Excess risk tends to zeroBrowser
rng = np.random.default_rng(1)
sigma, k = 0.5, 5
print(f"{'n':>4} {'p':>6} {'r0/n':>6} {'k*':>3} {'R_k*/n':>7} {'sesgo':>7} {'varianza':>8} {'teoría':>7} {'exceso/s2':>9}")
for n in [16, 32, 64, 128]:
    p_t = n * n // 4                       # p_n = n^2/4, mucho mayor que n
    mass = np.sqrt(n)                      # eps_n p_n = sqrt(n) = o(n)
    lam = tail_spectrum(k, p_t, mass, 0.0)
    theta = np.zeros(len(lam)); theta[:k] = 1 / np.sqrt(k)
    r0, ks, rk, Rk = ranks(lam, n)
    b, tC = min_norm_risk(lam, theta, n, 4, rng)
    print(f'{n:4d} {len(lam):6d} {r0/n:6.3f} {ks:3d} {Rk/n:7.2f} {b:7.4f} {sigma**2*tC:8.4f} {sigma**2*(ks/n+n/Rk):7.4f} {(b+sigma**2*tC)/sigma**2:9.3f}')

Excess risk in units of σ2\sigma^2 falls from 0.9210.921 with n=16n = 16 to 0.3730.373, 0.1790.179 and 0.1020.102 with n=128n = 128. Simulated variance matches the prediction σ2(k∗/n+n/Rk∗)\sigma^2(k^*/n + n/R_{k^*}) within 10 %10\,\% in every row and roughly halves as nn doubles, as k∗/n+4/nk^*/n + 4/n predicts. Bias falls with r0/nr_0/n. Every model interpolates its noisy labels, yet its risk approaches Bayes risk.

For a library implementation, np.linalg.lstsq and np.linalg.pinv return the minimum-norm solution to an underdetermined system. sklearn.linear_model.LinearRegression(fit_intercept=False) uses scipy.linalg.lstsq underneath and gives the same solution.

[ ]The same solve with librariesBrowser
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(2)
lam = tail_spectrum(5, 2000, 2.0, 0.0)
X = rng.standard_normal((40, len(lam))) * np.sqrt(lam)
y = X[:, :5].sum(1) / np.sqrt(5) + 0.5 * rng.standard_normal(40)
th_formula = X.T @ np.linalg.solve(X @ X.T, y)
th_lstsq = np.linalg.lstsq(X, y, rcond=None)[0]
th_sk = LinearRegression(fit_intercept=False).fit(X, y).coef_
print('lstsq frente a la fórmula: %.1e' % np.abs(th_lstsq - th_formula).max())
print('sklearn frente a la fórmula: %.1e' % np.abs(th_sk - th_formula).max())
print('residuo de entrenamiento: %.1e' % np.abs(X @ th_sk - y).max())

Signal and the tail that absorbs noise

The theorem turns a question about the estimator into a question about its covariance spectrum. A benign covariance separates into two parts:

  • Signal. A few directions (k∗≪nk^* \ll n) with large eigenvalues contain θ∗\vb{\theta}^*. In those directions, the interpolator behaves like least squares with an implicit ridge penalty of size ∑i>k∗λi\sum_{i>k^*}\lambda_i.
  • Tail. Many directions (Rk∗≫nR_{k^*} \gg n) have small, similar eigenvalues. The interpolator finds in the tail the nn degrees of freedom it needs to fit nn points. Each tail direction has low variance, so θ^\hat{\vb{\theta}} can have large tail coefficients while changing predictions on new points very little.

Bartlett, Montanari and Rakhlin (2021) frame this as a general principle. An interpolator can decompose into a simple predictive part and a spiky part that fits noise without substantially affecting predictions in favorable settings. The theorem’s conditions identify three failure modes. A short tail keeps Rk∗R_{k^*} below nn and prevents variance from vanishing. A steep tail delays rkr_k from exceeding bnbn, so k∗k^* grows and k∗/nk^*/n remains large. A heavy tail raises r0/nr_0/n so the implicit ridge penalty suppresses signal. Keeping the tail long, flat and light requires dimension much larger than nn.

InteractiveDesign a benign spectrum
  • signal
  • tail
0.0010.010.1110100bias0.010variance0.025excess risk0.035theoryσ² (noise)zero-predictor risk
Mean over six exact samples with n=50n = 50. The theory marker is the theorem’s variance term up to constants.
5
5,000
5.00
0.00
50
0.50
r0(Σ)/nr_0(\Sigma)/n0.200
k∗k^* (with b=1b = 1)5
rk∗/nr_{k^*}/n and Rk∗/nR_{k^*}/n100.00 and 100.00
σ2(k∗/n+n/Rk∗)\sigma^2(k^*/n + n/R_{k^*})0.0275
Simulated excess risk / σ2\sigma^20.140
The interpolator fits the noise and keeps excess risk small relative to σ2\sigma^2. This is benign at the selected nn.
The Gaussian linear model has kk signal eigenvalues equal to 1 (orange) and a tail of ptp_t eigenvalues (blue) with profile i−αi^{-\alpha} and fixed sum, grouped into 14 logarithmic index bins. The plot shows the same stepped spectrum used in the simulation. The unit norm of θ∗\vb{\theta}^* is spread over signal directions. At left, the spectrum in log–log scale and the position of k∗+1k^* + 1 (vertical line), with b=1b = 1. At right, simulated bias, variance, and minimum-norm excess risk on a logarithmic scale, averaged over six exact design matrices, compared with σ2\sigma^2 and the zero-predictor risk. The black marker is σ2(k∗/n+n/Rk∗)\sigma^2(k^*/n + n/R_{k^*}). Start with the benign spectrum and try the other three. Shorten the tail until variance crosses σ2\sigma^2, or add tail mass until bias dominates.

With a flat tail, the theoretical marker and variance bar move together as ptp_t, nn or kk changes, even when their heights differ. The theorem leaves multiplicative constants unspecified. For a fixed tail, increasing nn eventually breaks benign behavior. r0/nr_0/n falls, which helps bias. With a flat tail, rkr_{k} for k≥5k \ge 5 is at most tail length ptp_t. As nn approaches ptp_t, no rkr_k reaches bnbn and variance spikes. Shorten the tail to a few hundred eigenvalues and raise nn to see this. The tail must grow with nn for risk to vanish, as in Theorem 6.

Benign, tempered and catastrophic overfitting

Benign interpolation is one extreme. At the other, fitting noise can make the predictor arbitrarily bad. Mallinar, Simon, Abedsoltan, Pandit, Belkin and Nakkiran (2022) found that many practical methods sit between these extremes and proposed three categories.

Any consistent estimator is benign, whether it interpolates or not. The interesting question is where interpolating methods fall. Take x∼Unif⁡[0,1]x \sim \Unif[0, 1] and y=f∗(x)+εy = f^*(x) + \eps with continuous f∗f^* and ε\eps of variance σ2\sigma^2. Then R∗=σ2R^* = \sigma^2, and excess risk is E(f^n(x)−f∗(x))2\E(\hat{f}_n(x) - f^*(x))^2.

1-NN has tempered overfitting

Proof

Let x(1)x_{(1)} be the training point closest to xx, and let ε(1)\eps_{(1)} be its noise. Then f^n(x)−f∗(x)=(f∗(x(1))−f∗(x))+ε(1)\hat{f}_n(x) - f^*(x) = \big(f^*(x_{(1)}) - f^*(x)\big) + \eps_{(1)}. The neighbor’s noise is independent of its position and xx, with zero mean and variance σ2\sigma^2. The cross term has mean zero, so E(f^n(x)−f∗(x))2=E(f∗(x(1))−f∗(x))2+σ2\E(\hat{f}_n(x) - f^*(x))^2 = \E\big(f^*(x_{(1)}) - f^*(x)\big)^2 + \sigma^2. Now ∣x(1)−x∣→0\abs{x_{(1)} - x} \to 0 in probability. The chance that no point lies within distance ε\eps of xx decays geometrically in nn. Because f∗f^* is continuous and bounded, the first term tends to zero by dominated convergence.

∎

Interpolation with 1-NN incurs one full noise variance even in the limit. Cover and Hart’s 1967 result gives the classification analogue: asymptotic 1-NN risk satisfies R∗≤R∞≤2R∗(1−R∗)R^* \le R_\infty \le 2R^*(1 - R^*) for two classes. Averaging the kk nearest neighbors with fixed kk lowers the noise term to σ2/k\sigma^2/k. The positive limit still gives tempered overfitting. Consistency requires k→∞k \to \infty and k/n→0k/n \to 0.

Unregularized kernels: Laplace is tempered and Gaussian is catastrophic

The minimum-norm interpolant for kernel KK is f^(x)=∑iαiK(x,xi)\hat{f}(x) = \sum_i \alpha_i K(x, x_i) with Kα=y\mat{K}\vb{\alpha} = \vb{y}, equivalent to kernel ridge with λ→0\lambda \to 0. The one-dimensional Laplace kernel K(s,t)=e−∣s−t∣/ℓK(s, t) = e^{-\abs{s-t}/\ell} has a closed-form solution. Its reproducing kernel Hilbert space is first-order Sobolev, and the minimum-norm interpolant solves f′′=f/ℓ2f'' = f/\ell^2 between consecutive points. This gives an exponential spline

f^(x)=yjsinh⁡((xj+1−x)/ℓ)+yj+1sinh⁡((x−xj)/ℓ)sinh⁡((xj+1−xj)/ℓ),xj≤x≤xj+1.\hat{f}(x) = \frac{y_j\sinh\big((x_{j+1} - x)/\ell\big) + y_{j+1}\sinh\big((x - x_j)/\ell\big)}{\sinh\big((x_{j+1} - x_j)/\ell\big)}, \qquad x_j \le x \le x_{j+1}.

As nn increases with fixed ℓ\ell, gaps become much smaller than ℓ\ell and the spline approaches piecewise linear interpolation. If xx lies in gap [xj,xj+1][x_j, x_{j+1}] at relative position uu, its predicted noise component is (1−u)εj+uεj+1(1 - u)\eps_j + u\eps_{j+1}, of variance σ2((1−u)2+u2)\sigma^2\big((1 - u)^2 + u^2\big). Since xx is uniform within the gap, u∼Unif⁡[0,1]u \sim \Unif[0, 1] and E[(1−u)2+u2]=2/3\E[(1 - u)^2 + u^2] = 2/3. Excess risk tends to 2σ2/32\sigma^2/3, giving tempered overfitting. Mallinar et al. cite this argument from Belkin et al. (2018) and extend it with an empirically checked spectral approximation of kernel ridge risk. Unregularized kernel ridge with a power-law spectrum, such as a Laplace or ReLU neural tangent kernel, is tempered in that analysis.

The Gaussian kernel e−(s−t)2/(2ℓ2)e^{-(s-t)^2/(2\ell^2)} behaves differently. Its Gram matrix approaches singularity when sample spacing falls below ℓ\ell. Its eigenvalues in one dimension decay like e−ci2e^{-ci^2}. To fit noisy points the interpolant uses huge alternating coefficients and oscillates sharply between the points. The spectral trichotomy in Mallinar et al., Theorem 3.1, gives benign behavior with positive ridge or eigenvalue decay as slow as i−1log⁡−αii^{-1}\log^{-\alpha} i with α>1\alpha > 1. It gives tempered behavior for power law i−αi^{-\alpha} with α>1\alpha > 1, and catastrophic behavior if decay is at least as fast as i−αlog⁡ii^{-\alpha\log i}. The Gaussian kernel is in the last category.

Singular-kernel Nadaraya–Watson is benign

Benign interpolators can exist in fixed dimension. Belkin, Rakhlin and Tsybakov (2019) use the Nadaraya–Watson estimator

f^(x)=∑iK((x−xi)/h)yi∑iK((x−xi)/h),K(u)=∥u∥−a1[∥u∥≤1],\hat{f}(x) = \frac{\sum_i K\big((x - x_i)/h\big)y_i}{\sum_i K\big((x - x_i)/h\big)}, \qquad K(u) = \norm{u}^{-a}\ind[\norm{u} \le 1],

with a kernel singular at the origin. Because K(0)=∞K(0) = \infty, each yiy_i dominates in a tiny neighborhood of xix_i, producing interpolation. Under their standard assumptions on the density of xx and on the noise, if f∗f^* is β\beta-Hölder with β∈(0,1]\beta \in (0, 1], 0<a<d/20 < a < d/2 and h=n−1/(2β+d)h = n^{-1/(2\beta + d)}, Theorem 1 gives pointwise squared error O(n−2β/(2β+d))\bigO(n^{-2\beta/(2\beta + d)}), the minimax rate. Noise is fit in arbitrarily narrow spikes, and away from the spikes the estimator averages like a smoother. Devroye, Györfi and Krzyżak (1998) had already proved consistency for the bandwidth-free Hilbert kernel ∥u∥−d\norm{u}^{-d}.

InteractiveBenign, tempered, or catastrophic
  • 1-NN
  • Singular Nadaraya–Watson
  • Unregularized Laplace
  • Unregularized Gaussian
  • σ²
  • 2σ²/3
64
0.50
Excess risk (mean), 1-NN, n = 640.2650
Excess risk divided by σ²1.060
Gaussian: largest n computable in double precision32
Dashed lines mark σ2\sigma^2 and 2σ2/32\sigma^2/3. Benign risk approaches zero, tempered risk plateaus in proportion to σ2\sigma^2, and catastrophic risk grows without bound.
Explicit model: x∼Unif⁡[0,1]x \sim \Unif[0, 1], y=sin⁡(2πx)+σ N(0,1)y = \sin(2\pi x) + \sigma\,\Normal(0, 1). Four interpolators: 1-NN; Nadaraya–Watson with K(u)=∣u∣−0.451[∣u∣≤1]K(u) = \abs{u}^{-0.45}\ind[\abs{u} \le 1] and bandwidth h=n−1/3h = n^{-1/3}; unregularized kernel ridge with Laplace scale 0.20.2 (closed-form exponential spline); and a Gaussian kernel with scale 0.050.05, computed when the Gram matrix admits double-precision Cholesky. At left, the data, f∗f^* (dashed) and the chosen fit at selected nn. At right, excess risk versus nn in log–log scale, averaging 12 samples at 600 evaluation points (for Gaussian, the median of 60 computable runs). References are σ2\sigma^2 and 2σ2/32\sigma^2/3. Values above 10610^6 are drawn at the boundary. Change nn for each method. Does risk vanish, settle onto a plateau proportional to σ2\sigma^2, or spike?

The NumPy simulation gives the numerical results.

[ ]Numerical overfitting taxonomyBrowser
f = lambda x: np.sin(2 * np.pi * x)
t = (np.arange(600) + 0.5) / 600              # puntos de evaluación en [0, 1]

def nn1(x, y):                                # x ordenado
    j = np.clip(np.searchsorted(x, t), 1, len(x) - 1)
    left = (t - x[j - 1]) <= (x[j] - t)
    return np.where(left, y[j - 1], y[j])

def nw_singular(x, y, a=0.45):                # K(u) = |u|^-a 1{|u| <= 1}, ventana h = n^(-1/3)
    h = len(x) ** (-1 / 3)
    d = np.abs(t[:, None] - x[None, :]) / h
    with np.errstate(divide='ignore'):
        w = np.where(d <= 1, d ** (-a), 0.0)
    return (w @ y) / w.sum(1)

def laplace(x, y, l=0.2):                     # mínima norma del núcleo e^{-|s-t|/l}: spline exponencial
    j = np.clip(np.searchsorted(x, t), 1, len(x) - 1)
    a, b = x[j - 1], x[j]
    out = (y[j - 1] * np.sinh((b - t) / l) + y[j] * np.sinh((t - a) / l)) / np.sinh((b - a) / l)
    out = np.where(t < x[0], y[0] * np.exp(-(x[0] - t) / l), out)
    return np.where(t > x[-1], y[-1] * np.exp(-(t - x[-1]) / l), out)

def gauss(x, y, l=0.05):                      # kernel ridge gaussiano sin regularizar
    K = np.exp(-(x[:, None] - x[None, :]) ** 2 / (2 * l * l))
    try:
        L = np.linalg.cholesky(K)
    except np.linalg.LinAlgError:
        return None
    if len(x) / np.min(np.diag(L)) ** 2 > 1e13:   # indicador de mal condicionamiento (el mismo del interactivo)
        return None                               # fuera del alcance de la doble precisión
    alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
    pred = np.exp(-(t[:, None] - x[None, :]) ** 2 / (2 * l * l)) @ alpha
    return pred if np.all(np.isfinite(pred)) else None

rng = np.random.default_rng(0)
sigma = 0.5
methods = {'1-NN': nn1, 'NW singular': nw_singular, 'Laplace': laplace}
print('riesgo en exceso / sigma^2, media de 12 muestras')
print(f"{'n':>5}" + ''.join(f'{m:>13}' for m in methods))
for n in [8, 16, 32, 128, 512, 1024]:
    acc = {m: [] for m in methods}
    for s in range(12):
        x = np.sort(rng.uniform(0, 1, n)); y = f(x) + sigma * rng.standard_normal(n)
        for m, fit in methods.items():
            acc[m].append(np.mean((fit(x, y) - f(t)) ** 2) / sigma**2)
    print(f'{n:5d}' + ''.join(f'{np.mean(v):13.3g}' for v in acc.values()))

# el gaussiano tiene colas enormes (dos puntos muy juntos bastan para disparar los coeficientes):
# se resume con la mediana de 100 muestras, contando cuántas se pueden calcular en doble precisión
print('\ngaussiano sin regularizar: mediana de 100 muestras (calculables)')
for n in [8, 12, 16, 20, 24, 28, 32]:
    v = []
    for s in range(100):
        x = np.sort(rng.uniform(0, 1, n)); y = f(x) + sigma * rng.standard_normal(n)
        pred = gauss(x, y)
        if pred is not None:
            v.append(np.mean((pred - f(t)) ** 2) / sigma**2)
    print(f'{n:5d} {np.median(v):12.3g}  ({len(v)})')

From n=128n = 128 onward, 1-NN stays between 0.970.97 and 1.02 σ21.02\,\sigma^2. The Laplace kernel stays between 0.640.64 and 0.69 σ20.69\,\sigma^2. The plateaus match σ2\sigma^2 and 2σ2/32\sigma^2/3 with variability across 12 samples. Singular Nadaraya–Watson falls from 1.18 σ21.18\,\sigma^2 at n=8n = 8 to 0.0232 σ20.0232\,\sigma^2 at n=1024n = 1024 while still interpolating. Gaussian errors have heavy tails because two close points are enough to yield huge coefficients. The cell reports the median of 100 runs. It goes from 2.93 σ22.93\,\sigma^2 at n=8n = 8 to 212 σ2212\,\sigma^2 at n=16n = 16, 1.07⋅105 σ21.07\cdot 10^5\,\sigma^2 at n=24n = 24, and 1.07⋅107 σ21.07\cdot 10^7\,\sigma^2 at n=32n = 32. At that point only 92 of 100 runs are computable in double precision. The overfitting is catastrophic, and computation starts to break down long before nn becomes large.

How neural networks behave

Mallinar et al. train a Wide ResNet 28×10 on binary CIFAR-10 (animals versus vehicles) with label flips and increasing nn in Figure 2. They also train ResNets on all ten classes in Figure 6a. Test error increases with label noise and does not return to the optimum as nn grows, so the interpolating networks are tempered. The same architectures can behave benignly with early stopping. Even a three-layer MLP on a simple synthetic problem with inputs on sphere S9S^9 and constant labels stops learning the constant function once it trains to interpolate a little noise.

The orange network in the opening experiment memorizes wrong labels in islands and pays residual test error for them. That is tempered behavior: prediction is still useful and the added error persists as data grow.

Memorization can help on long-tailed distributions

If memorization carries a cost, why does more regularization not solve the problem? Feldman (2020) gave an architecture-independent answer. On long-tailed distributions, a learner that avoids memorization can be necessarily suboptimal.

The model mixes many subpopulations, such as pictures taken at night of a rare dog breed. Frequencies are drawn from prior π\pi. In a sample of size nn, many subpopulations appear once and are called singletons. From one example the learner cannot distinguish a subgroup of frequency on the order of 1/n1/n, likely to be tested again, from a very rare outlier. If the singleton’s label cannot be inferred from other data, memorizing it is the only way to predict correctly on its subgroup.

Feldman’s Theorem 2.3 quantifies the cost. In the special case discussed here,

err(π,F,A)≥opt(π,F)+τ1⋅E[errnS(A,1)],τ1=Eα∼πˉN[α2(1−α)n−1]Eα∼πˉN[α(1−α)n−1],\text{err}(\pi, \mathcal{F}, \mathcal{A}) \ge \text{opt}(\pi, \mathcal{F}) + \tau_1\cdot\E\big[\text{errn}_S(\mathcal{A}, 1)\big], \qquad \tau_1 = \frac{\E_{\alpha\sim\bar{\pi}^N}\big[\alpha^2(1 - \alpha)^{n-1}\big]}{\E_{\alpha\sim\bar{\pi}^N}\big[\alpha(1 - \alpha)^{n-1}\big]},

where errnS(A,1)\text{errn}_S(\mathcal{A}, 1) counts training singletons the learned predictor misclassifies, and πˉN\bar{\pi}^N is the frequency distribution. Each missed singleton costs τ1\tau_1 in expected generalization error. For a long tail, τ1\tau_1 is on the order of 1/n1/n while singletons remain a constant fraction of nn. The total excess is constant. The cell reproduces the paper’s numerical example, using Zipf frequencies (pi∝1/ip_i \propto 1/i) over N=50 000N = 50\,000 elements and n=50 000n = 50\,000 samples.

[ ]The cost of avoiding memorization with a Zipf tailBrowser
N = n = 50_000
p = 1 / np.arange(1, N + 1); p /= p.sum()          # frecuencias de Zipf
w = (1 - p) ** (n - 1)
tau1 = np.sum(p**2 * w) / np.sum(p * w)             # pérdida esperada por cada singleton que no se ajusta
singletons = n * np.sum(p * w)                       # número esperado de elementos vistos una sola vez
missing = np.sum(p * (1 - p) ** n)                   # masa de los elementos que no aparecen en la muestra
print(f'tau_1 = {tau1 * n:.3f} / n')
print(f'fracción esperada de singletons: {singletons / n:.3f}')
print(f'exceso si se acierta al azar en los singletons (2 clases): {tau1 * singletons / 2:.4f}')
print(f'exceso si se acierta al azar en los singletons (10 clases): {tau1 * singletons * 0.9:.4f}')
print(f'masa no observada: {missing:.4f}  (error óptimo con 2 clases: {missing / 2:.4f})')

The result is τ1≈0.472/n\tau_1 \approx 0.472/n and 17 %17\,\% singletons, as in the paper. A predictor that performs at chance on singletons loses 4.04.0 error points with two classes, against optimum 8.5 %8.5\,\%, and 7.27.2 points with ten classes. Feldman extends this to noisy labels in Theorem 2.4. If a singleton’s observed label is the most likely one, fitting it remains optimal even when it is sometimes wrong. That helps explain why methods that generalize on natural data also remember some incorrect labels and why discouraging memorization through differential privacy or compression can cost accuracy in low-frequency groups. Memorized rare examples can also expose private information through membership inference and data extraction, covered in the reliability module.

Norm- and margin-based bounds for neural networks

If parameter count fails to quantify the relevant capacity, what does? The most studied alternative comes from linear models. The margin lesson showed that the class {x↦⟨w,x⟩:∥w∥≤W}\{\vb{x} \mapsto \inner{\vb{w}}{\vb{x}} : \norm{\vb{w}} \le W\} on data satisfying ∥x∥≤X\norm{\vb{x}} \le X has Rademacher complexity at most WX/nWX/\sqrt{n}, independent of dimension. The margin bound bounds test error by margin error γ\gamma plus a term on the order of WX/(γn)WX/(\gamma\sqrt{n}). Capacity depends on a norm divided by the margin.

For a network FA(x)=σL(ALσL−1(AL−1⋯σ1(A1x)))F_{\mat{A}}(\vb{x}) = \sigma_L(\mat{A}_L\sigma_{L-1}(\mat{A}_{L-1}\cdots\sigma_1(\mat{A}_1\vb{x}))) with ρi\rho_i-Lipschitz activations and σi(0)=0\sigma_i(0) = 0, as for ReLU and nonoverlapping max pooling with ρi=1\rho_i = 1, the network’s Lipschitz constant is bounded by ∏iρi∥Ai∥σ\prod_i\rho_i\norm{\mat{A}_i}_\sigma, the product of spectral norms. Bartlett, Foster and Telgarsky (2017) build their complexity measure from this quantity.

Lemma A.8 gives explicit constants after fixing norm bounds in advance. The theorem’s union over norm bounds adds logarithmic terms. The lemma gives

P[error]≤R^γ+8n+72 ∥X∥2 RAln⁡(2W)ln⁡nγn+3ln⁡(1/δ)2n.\Pr[\text{error}] \le \hat{R}_\gamma + \frac{8}{n} + \frac{72\,\norm{\mat{X}}_2\,R_{\mat{A}}\ln(2W)\ln n}{\gamma n} + 3\sqrt{\frac{\ln(1/\delta)}{2n}}.

and the lab evaluates it. The ratio γn/(∥X∥2RA)\gamma n/(\norm{\mat{X}}_2 R_{\mat{A}}) is the normalized margin. The paper recommends comparing full normalized-margin distributions because the bound applies across margin levels.

Quantity RAR_{\mat{A}} is invariant under rescalings that preserve the function. A bias-free ReLU network satisfies ReLU⁡(cz)=cReLU⁡(z)\relu(c\vb{z}) = c\relu(\vb{z}) for c>0c > 0, so scaling one layer by cc and another by 1/c1/c leaves the function unchanged. The product of spectral norms and the ratios ∥Ai⊤∥2,1/∥Ai∥σ\norm{\mat{A}_i\T}_{2,1}/\norm{\mat{A}_i}_\sigma are unchanged. The sum of squared Frobenius norms changes.

[ ]Measures with and without rescaling invarianceBrowser
rng = np.random.default_rng(0)
A = [rng.standard_normal((64, 20)) / 4, rng.standard_normal((64, 64)) / 8, rng.standard_normal((3, 64)) / 8]
X = rng.standard_normal((100, 20)); y = rng.integers(0, 3, 100)

def net(A, X):
    h = X.T
    for W in A[:-1]:
        h = np.maximum(W @ h, 0)
    return (A[-1] @ h).T

def medidas(A):
    spec = [np.linalg.norm(W, 2) for W in A]
    l21 = [np.linalg.norm(W, axis=1).sum() for W in A]          # ||A^T||_{2,1}: suma de normas de filas
    R_A = np.prod(spec) * sum((l / s) ** (2 / 3) for l, s in zip(l21, spec)) ** 1.5
    out = net(A, X)
    marg = out[np.arange(100), y] - np.max(np.where(np.eye(3)[y] == 1, -np.inf, out), axis=1)
    return np.prod(spec), sum(np.linalg.norm(W) ** 2 for W in A), R_A, marg / R_A

c = 10.0
B = [A[0] * c, A[1] / c, A[2]]                  # misma función: relu(c z) = c relu(z)
print('misma salida:', np.allclose(net(A, X), net(B, X)))
res = [medidas(W) for W in (A, B)]
for name, (p, f2, R, nm) in zip(['original', 'reescalada'], res):
    print(f'{name:>10}: prod ||A_i||_2 = {p:.4f}   sum ||A_i||_F^2 = {f2:9.2f}   R_A = {R:.4f}')
print('márgenes normalizados idénticos:', np.allclose(res[0][3], res[1][3]))

The sum of squared Frobenius norms goes from 144.21144.21 to 7726.927726.92 for the same function. To compare networks with different parameterizations, such as different initialization scales or use of batch normalization, use invariant measures or normalize them first.

Lab: random labels and spectral norms on a GPU

The lab reproduces the Zhang et al. experiment and uses the measurements of Bartlett, Foster and Telgarsky. It trains an MLP 3×5123\times 512 like the one in the paper and a small CNN with two 3×33\times 3 convolutions of 32 and 64 channels, max pooling and two linear layers. Both omit biases to meet the bound’s assumptions. CIFAR-10 labels are randomized at rates p=0p = 0, 0.20.2, 0.50.5 and 11. The lab uses SGD with momentum 0.9, learning rate 0.01, batches of 128, and no augmentation or weight decay. Each network stops when mean training cross-entropy falls below 10−310^{-3}. A common stopping criterion makes norms and margins more comparable across runs. Jiang et al. (2020) use the same idea and stop at 0.010.01. The lab records the first epoch with zero training error, clean-label test error, and each layer’s spectral, Frobenius and (2,1)(2, 1) norms. It treats convolutions as linear operators over the full image. Power iteration uses convolution and its transpose, and the (2,1)(2, 1) norm sums the exact row norms. It also records RAR_{\mat{A}}, the normalized-margin distribution, and the Lemma A.8 bound with γ\gamma set to the tenth percentile of training margins and δ=0.05\delta = 0.05.

Run the full configuration with n=50 000n = 50\,000, all CIFAR-10 and three seeds. With ORYON_VERIFY_SHORT=1 the shorter run uses n=10 000n = 10\,000, two seeds and 5,000 test images. Automated checks skip this cell because of its runtime. Data come from a pinned copy of CIFAR-10 on Hugging Face (uoft-cs/cifar10) downloaded once.

[ ]Random labels and spectral norms on the GPULocal GPU
"""Etiquetas aleatorias y cotas espectrales: el experimento de Zhang et al. (2017) medido como Bartlett, Foster y Telgarsky (2017).

Una MLP 3x512 y una CNN pequeña, ambas sin sesgos (como en la cota de BFT), se entrenan con SGD sobre un subconjunto de
CIFAR-10 con una fracción p de etiquetas aleatorias (con probabilidad p, la etiqueta se sustituye por una clase uniforme,
sorteada una vez). Cada red se entrena hasta que su entropía cruzada media de entrenamiento baja de 0.001 (o hasta MAX_EPOCHS).
Se registran la época en que ajusta, el error de test (con etiquetas limpias), las normas espectral, de Frobenius y (2,1)
de cada capa, la complejidad espectral R_A, los márgenes normalizados y la cota del lema A.8 de BFT.

ORYON_VERIFY_SHORT=1 ejecuta una versión corta (menos datos, dos semillas) que comprueba el flujo.
"""
import io as _io
import json
import math
import os
import time
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn

SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if SHORT:
    N_TRAIN, N_TEST, MAX_EPOCHS, SEEDS = 10000, 5000, 500, [0, 1]
else:
    N_TRAIN, N_TEST, MAX_EPOCHS, SEEDS = 50000, 10000, 2000, [0, 1, 2]
NOISES = [0.0, 0.2, 0.5, 1.0]
LR, MOMENTUM, BATCH, DELTA = 0.01, 0.9, 128, 0.05
CE_STOP = 0.001  # se para cuando la entropía cruzada media de entrenamiento baja de aquí (Jiang et al. usan 0.01)
OUT = Path(os.environ.get('ORYON_SPECTRAL_OUTPUT', 'random-labels-spectral.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)
X_raw, y_clean = load_cifar('train', gen.permutation(50000)[:N_TRAIN])
mean, std = X_raw.mean((0, 2, 3), keepdim=True), X_raw.std((0, 2, 3), keepdim=True)
Xtr = ((X_raw - mean) / std).to(device)
Xte_raw, yte = load_cifar('test', gen.permutation(10000)[:N_TEST])
Xte, yte = ((Xte_raw - mean) / std).to(device), yte.to(device)
X_NORM = Xtr.flatten(1).norm().item()  # ||X||_2 de BFT: norma de Frobenius de la matriz de datos (n x d)
print(f'n = {N_TRAIN}, test limpio = {N_TEST}, ||X||_2 = {X_NORM:.1f}')


def corrupt(p, seed):
    """Con probabilidad p, la etiqueta se sustituye por una clase uniforme (puede coincidir con la verdadera)."""
    g = np.random.default_rng(1000 + seed)
    mask = torch.tensor(g.random(N_TRAIN) < p)
    rand = torch.tensor(g.integers(0, 10, N_TRAIN))
    return torch.where(mask, rand, y_clean).to(device)


# ---------------------------------------------------------------- modelos (sin sesgos: F_A(x) = s_L(A_L ... s_1(A_1 x)))
def make_mlp():
    return nn.Sequential(nn.Flatten(), nn.Linear(3072, 512, bias=False), nn.ReLU(), nn.Linear(512, 512, bias=False),
                         nn.ReLU(), nn.Linear(512, 512, bias=False), nn.ReLU(), nn.Linear(512, 10, bias=False))


def make_cnn():
    return nn.Sequential(nn.Conv2d(3, 32, 3, padding=1, bias=False), nn.ReLU(), nn.MaxPool2d(2),
                         nn.Conv2d(32, 64, 3, padding=1, bias=False), nn.ReLU(), nn.MaxPool2d(2),
                         nn.Flatten(), nn.Linear(4096, 256, bias=False), nn.ReLU(), nn.Linear(256, 10, bias=False))


IN_SHAPES = {'mlp': None, 'cnn': [(3, 32, 32), (32, 16, 16), None, None]}


# ---------------------------------------------------------------- normas de cada capa como operador lineal
@torch.no_grad()
def layer_norms(layer, in_shape):
    """(espectral, Frobenius del operador, ||A^T||_{2,1}, dimensión de salida) de una capa lineal o convolucional."""
    W = layer.weight.float()
    if isinstance(layer, nn.Linear):
        s = torch.linalg.matrix_norm(W, ord=2).item()
        return s, W.norm().item(), W.norm(dim=1).sum().item(), W.shape[0]
    # convolución (paso 1, relleno 1) como matriz de (C_out H W) x (C_in H W)
    x = torch.randn(1, *in_shape, device=W.device)
    for _ in range(100):  # iteración de potencias con A y su traspuesta
        x = F.conv_transpose2d(F.conv2d(x, W, padding=1), W, padding=1)
        x = x / x.norm()
    s = F.conv2d(x, W, padding=1).norm().item()
    row_sq = F.conv2d(torch.ones(1, *in_shape, device=W.device), W ** 2, padding=1)  # ||fila||^2 de cada salida
    return s, row_sq.sum().sqrt().item(), row_sq.sqrt().sum().item(), row_sq.numel()


def spectral_stats(model, kind):
    layers = [m for m in model if isinstance(m, (nn.Linear, nn.Conv2d))]
    shapes = IN_SHAPES[kind] or [None] * len(layers)
    rows = [layer_norms(l, sh) for l, sh in zip(layers, shapes)]
    spec = [r[0] for r in rows]
    lip = math.prod(spec)
    R_A = lip * sum((r[2] / r[0]) ** (2 / 3) for r in rows) ** 1.5  # ec. (1.2) con M_i = 0
    W_max = max([3072] + [r[3] for r in rows])
    return {'spectral': spec, 'frobenius': [r[1] for r in rows], 'l21': [r[2] for r in rows],
            'lipschitz': lip, 'R_A': R_A, 'W': W_max}


@torch.no_grad()
def margins_and_error(model, X, y):
    model.eval()
    out = torch.cat([model(X[i:i + 1000]).float() for i in range(0, len(X), 1000)])
    model.train()
    true = out.gather(1, y[:, None])[:, 0]
    other = out.scatter(1, y[:, None], float('-inf')).max(1).values
    return (true - other), (out.argmax(1) != y).float().mean().item(), F.cross_entropy(out, y).item()


# ---------------------------------------------------------------- entrenamiento hasta ajustar
def run(kind, p, seed):
    y = corrupt(p, seed)
    torch.manual_seed(seed)
    model = (make_mlp() if kind == 'mlp' else make_cnn()).to(device)
    opt = torch.optim.SGD(model.parameters(), lr=LR, momentum=MOMENTUM)
    g = torch.Generator(device=device).manual_seed(seed)
    curve, fit_epoch = [], None
    for ep in range(1, MAX_EPOCHS + 1):
        perm = torch.randperm(N_TRAIN, device=device, generator=g)
        for i in range(0, N_TRAIN, BATCH):
            b = perm[i:i + BATCH]
            loss = F.cross_entropy(model(Xtr[b]), y[b])
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
        _, tr_err, ce = margins_and_error(model, Xtr, y)
        if fit_epoch is None and tr_err == 0:
            fit_epoch = ep
        if ep in (1, 2, 3, 5, 7) or ep % 10 == 0 or ce <= CE_STOP or ep == MAX_EPOCHS:
            _, te_err, _ = margins_and_error(model, Xte, yte)
            curve.append({'epoch': ep, 'train': tr_err, 'test': te_err, 'ce': ce})
        if ce <= CE_STOP:
            break
    marg, tr_err, ce = margins_and_error(model, Xtr, y)
    _, te_err, _ = margins_and_error(model, Xte, yte)
    st = spectral_stats(model, kind)
    n = N_TRAIN
    gamma = torch.quantile(marg, 0.10).item()  # margen que deja un 10 % de puntos por debajo
    ramp = (marg <= gamma).float().mean().item()
    complexity = X_NORM * st['R_A'] / (gamma * n)  # término de BFT sin factores logarítmicos
    bound = ramp + 8 / n + 72 * complexity * math.log(2 * st['W']) * math.log(n) + 3 * math.sqrt(math.log(1 / DELTA) / (2 * n))
    norm_m = (marg / (st['R_A'] * X_NORM / n)).cpu().numpy()
    res = {'model': kind, 'noise': p, 'seed': seed, 'fit_epoch': fit_epoch, 'epochs': curve[-1]['epoch'],
           'steps': curve[-1]['epoch'] * math.ceil(n / BATCH), 'train_err': tr_err, 'test_err': te_err,
           'wrong_labels': (y.cpu() != y_clean).float().mean().item(), 'gamma': gamma, 'margin_err': ramp,
           'complexity': complexity, 'bound': bound, 'curve': curve,
           'norm_margin_q': np.quantile(norm_m, np.linspace(0, 1, 41)).tolist(), **st}
    del model, opt
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    return res


results = {'config': {'n_train': N_TRAIN, 'n_test': N_TEST, 'max_epochs': MAX_EPOCHS, 'lr': LR, 'momentum': MOMENTUM,
                      'batch': BATCH, 'delta': DELTA, 'x_norm': X_NORM, 'short': SHORT}, 'runs': []}
t0 = time.time()
for kind in ['mlp', 'cnn']:
    for p in NOISES:
        for seed in SEEDS:
            r = run(kind, p, seed)
            results['runs'].append(r)
            print(f"{kind} p={p:.1f} s={seed}: ajusta en época {r['fit_epoch']}, para en {r['epochs']}, test {r['test_err']:.3f}, "
                  f"Lip {r['lipschitz']:.3g}, R_A {r['R_A']:.3g}, gamma {r['gamma']:.3g}, "
                  f"cota {r['bound']:.3g}  [{time.time() - t0:.0f} s]")
OUT.write_text(json.dumps(results), encoding='utf-8')
print('guardado en', OUT)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
InteractiveThe spectral bound tracks label randomness
test errorbound / bound at p = 00 %50 %100 %0.00.51.01.5chancep = 0p = 0.2p = 0.5p = 1
  • p = 0
  • p = 0.2
  • p = 0.5
  • p = 1
p = 1
Test error (mean across seeds)89.8 %
BFT bound (mean)2.86 · 10⁷
∏i∥Ai∥σ\prod_i\|\mathbf{A}_i\|_\sigma and RAR_{\mathbf{A}} (means)71.9 and 6.30 · 10⁴
γ\gamma (mean tenth-percentile margin)7.06
Epochs to zero error and to stopping60 and 61 · 68 and 68
Recorded short run: n=10000n = 10000, two seeds (black dots), and 5000 test images. From p=0p = 0 to p=1p = 1, the mean bound rises by a factor of 1.52, while test error goes from 52 % to chance. Values above 1 are vacuous.
Recorded output of the preceding cell with ORYON_VERIFY_SHORT=1: n=10 000n = 10\,000 CIFAR-10 images, two seeds per setting (black dots, with mean bars) and 5000 clean test images. At left, for each fraction pp of randomized labels, test error (dashed line marks 90% chance error) and the Bartlett, Foster and Telgarsky Lemma A.8 bound divided by its value on real labels. Absolute bounds appear in the readouts. At right, the cumulative distribution of normalized training margins (seed 0). A curve farther left means a larger bound at each margin. Compare the MLP and CNN. Their bounds rise with noise and remain seven to nine orders of magnitude above 1.

Fitting random labels takes only modestly longer. On real labels, the MLP reaches zero training error at epochs 38 and 48, one per seed. On fully random labels it takes 60 and 68. The CNN takes 22 and 21 versus 38 and 36. This is the small factor seen by Zhang et al., between 1.41.4 and 1.81.8 times as many epochs. Test error approaches chance. The MLP goes from 52.2 %52.2\,\% test error on real labels to 59.759.7, 70.470.4 and 89.8 %89.8\,\% at p=0.2p = 0.2, 0.50.5 and 11. The CNN goes from 36.9 %36.9\,\% to 48.248.2, 63.863.8 and 90.0 %90.0\,\%. Both train with 10,000 images and without data augmentation. The bound increases with noise. The MLP mean goes from 1.88⋅1071.88\cdot 10^7 for real labels to 2.362.36, 2.502.50 and 2.86⋅1072.86\cdot 10^7, in order and differing by a factor of 1.521.52 between endpoints. Its spectral-norm product rises from 47 to 72 as the tenth-percentile margin barely changes, from 6.56.5 to 7.17.1. For the CNN the sequence is 1.99⋅1091.99\cdot 10^9, 2.432.43, 2.722.72 and 2.73⋅1092.73\cdot 10^9. It separates real from noisy labels, but between p=0.5p = 0.5 and p=1p = 1 the mean differs by 0.4 %0.4\,\%, less than the gap between seeds, while test error jumps from 6464 to 90 %90\,\%. The normalized-margin distributions show more detail. In the MLP the median drops from 0.49⋅10−30.49\cdot 10^{-3}, averaged across seeds, to 0.34⋅10−30.34\cdot 10^{-3}. The curves move left as noise increases, as in Bartlett et al., Figure 2b.

Holding architecture and hyperparameters fixed while adding noise increases the bound, which demonstrates its data dependence. Its absolute values 10710^7 and 10910^9 exceed 1, making the error guarantees vacuous, and the ratio between endpoints, 1.5 or 1.4, is much smaller than the observed difference in generalization. The full results in the source study show a similar separation for AlexNet on CIFAR-10 at the end of training (Figure 2b). Use the full dataset and three seeds before drawing conclusions about small differences.

Empirical measures of generalization

A vacuous bound can still be useful if it ranks models correctly as hyperparameters change. Jiang, Neyshabur, Mobahi, Krishnan and Bengio (2020) tested this with more than 10,000 convolutional networks trained on CIFAR-10 and SVHN, varying seven hyperparameters systematically. They studied more than 40 complexity measures and used rank correlations designed to distinguish causal relationships from spurious ones. PAC-Bayes and sharpness measures performed best overall. Sharpness measures how much the loss rises when weights are perturbed, as discussed in the flatness lesson. Spectral complexity correlated negatively with generalization across hyperparameter types, especially changes in depth. Path norm performed well, and several optimization measures such as training speed had substantial predictive value.

Dziugaite, Drouin, Neal, Rajkumar, Caballero, Wang, Mitliagkas and Roy (2020) argued that average performance can hide systematic failure under a particular intervention. They evaluated 24 measures over more than 1,600,000 experiment pairs using robust sign error, a worst-case score over environments where just one hyperparameter changes. No measure beat chance by this statistic. Every measure had at least one environment where it consistently predicted the wrong direction. Most families predicted sample-size effects, though some Frobenius-based measures grew with nn for shallow, narrow networks. Depth and width were difficult for all measures, with some PAC-Bayes measures robust in a substantial fraction of environments. Norm-based measures did best when learning rate changed.

Limits of uniform convergence

The bounds in this lesson and nearly all those in this module use uniform convergence. They bound sup⁡h∈H∣R(h)−R^(h)∣\sup_{h\in\mathcal{H}}\abs{R(h) - \hat{R}(h)} over a class H\mathcal{H} and apply the result to the learned predictor. The random-label experiment already shows why H\mathcal{H} cannot include the full architecture without giving a vacuous bound. A natural approach is to narrow the class to predictors the algorithm actually returns on typical samples, perhaps using bounded norms, proximity to initialization or large margins. Nagarajan and Kolter (2019) showed that even the tightest version of this approach fails in simple examples.

A set Sδ\mathcal{S}_\delta of probability 1−δ1 - \delta can exclude rare samples. The definition requires one set of probability δ\delta shared by all predictors, rather than a different set for each hh. The limits of uniform convergence appear when an algorithm generalizes well and yet εunif-alg\eps_{\text{unif-alg}} is close to 1.

The linear example

Inputs are x=(x1,x2)\vb{x} = (\vb{x}_1, \vb{x}_2) with x1∈RK\vb{x}_1 \in \R^K and x2∈RD\vb{x}_2 \in \R^D. Label y∈{−1,1}y \in \{-1, 1\} is uniform. Set x1=2yu\vb{x}_1 = 2y\vb{u} for fixed u\vb{u} with ∥u∥=1/m\norm{\vb{u}} = 1/\sqrt{m}. The noise x2∼N(0,32DID)\vb{x}_2 \sim \Normal(\vb{0}, \frac{32}{D}\mat{I}_D) is independent of everything else. Starting from the origin, the algorithm takes one gradient step of size 1 to maximize y h(x)y\,h(\vb{x}) with h(x)=w1⊤x1+w2⊤x2h(\vb{x}) = \vb{w}_1\T\vb{x}_1 + \vb{w}_2\T\vb{x}_2. This gives w1=2mu\vb{w}_1 = 2m\vb{u} and w2=∑iy(i)x2(i)\vb{w}_2 = \sum_i y^{(i)}\vb{x}_2^{(i)}. The margin of a point is

y h(x)=4+y w2⊤x2,y\,h(\vb{x}) = 4 + y\,\vb{w}_2\T\vb{x}_2,

because y w1⊤x1=4m∥u∥2=4y\,\vb{w}_1\T\vb{x}_1 = 4m\norm{\vb{u}}^2 = 4.

  • Training. For training point jj, y(j)w2⊤x2(j)=∥x2(j)∥2+∑i≠jy(i)y(j)⟨x2(i),x2(j)⟩≈32y^{(j)}\vb{w}_2\T\vb{x}_2^{(j)} = \norm{\vb{x}_2^{(j)}}^2 + \sum_{i\ne j}y^{(i)}y^{(j)}\inner{\vb{x}_2^{(i)}}{\vb{x}_2^{(j)}} \approx 32. Every point is classified correctly with a large margin.
  • Test. x2\vb{x}_2 is independent of w2\vb{w}_2, so y w2⊤x2∼N(0,∥w2∥2⋅32/D)y\,\vb{w}_2\T\vb{x}_2 \sim \Normal(0, \norm{\vb{w}_2}^2\cdot 32/D) with ∥w2∥2≈32m\norm{\vb{w}_2}^2 \approx 32m. Its standard deviation is 32m/D32\sqrt{m/D}, below 4 when D≫mD \gg m. Test error is small.
  • Noise-negated sample. In S′={((x1,−x2),y):((x1,x2),y)∈S}S' = \{((\vb{x}_1, -\vb{x}_2), y) : ((\vb{x}_1, \vb{x}_2), y) \in S\} each margin is 4−y(j)w2⊤x2(j)≈4−32<04 - y^{(j)}\vb{w}_2\T\vb{x}_2^{(j)} \approx 4 - 32 < 0. The classifier trained on SS gets every point wrong.

Crucially, S′S' has exactly the same distribution as SS because the Gaussian noise is symmetric. If Sδ\mathcal{S}_\delta has probability 1−δ1 - \delta with small δ\delta, then for most samples SS, both SS and S′S' lie in Sδ\mathcal{S}_\delta. Both are typical. Then hS∈Hδh_S \in \mathcal{H}_\delta and S′∈SδS' \in \mathcal{S}_\delta, so the definition forces

εunif-alg≥∣LD(hS)−L^S′(hS)∣≈∣ε−1∣=1−ε.\eps_{\text{unif-alg}} \ge \abs{\mathcal{L}_\mathcal{D}(h_S) - \hat{\mathcal{L}}_{S'}(h_S)} \approx \abs{\eps - 1} = 1 - \eps.

Theorem 3.1 of Nagarajan and Kolter states that for every ε,δ>0\eps, \delta > 0 with δ≤1/4\delta \le 1/4, if D=Ω(max⁡(mln⁡(m/δ),mln⁡(1/ε)))D = \Omega\big(\max(m\ln(m/\delta), m\ln(1/\eps))\big), generalization error is at most ε\eps and still εunif-alg(m,δ)≥1−ε\eps_{\text{unif-alg}}(m, \delta) \ge 1 - \eps. This holds for 0–1 loss and margin losses L(γ)\mathcal{L}^{(\gamma)} with γ∈[0,1]\gamma \in [0, 1].

InteractiveThe uniform convergence trap
−60−40−200204060margin y·h(x) (negative values are errors)training StestS′ (x₂ → −x₂)
64
16,384
Training error on S0.0 %
Test error (400 new points)3.3 %
Error on S′ (noise negated)100.0 %
Test standard deviation of y·w₂·x₂2.00
S′S' has the same distribution as SS. The classifier trained on SS misclassifies 100 % of its points. A uniform bound over the algorithm’s classifiers must cover (hS,S′)(h_S, S'), so it is at least ∣0.03−1.00∣|0.03 - 1.00|.
Nagarajan and Kolter’s linear example: mm training examples with noise x2∼N(0,(32/D)ID)\vb{x}_2 \sim \Normal(\vb{0}, (32/D)\mat{I}_D) and one gradient step from the origin. Each dot is an example margin y h(x)=4+y w2⊤x2y\,h(\vb{x}) = 4 + y\,\vb{w}_2\T\vb{x}_2. The top row shows training examples. The middle row shows 160 of 400 test examples drawn from their exact distribution. The bottom row shows S′S', the same sample with the noise negated. Shading marks classification error. With DD large relative to mm, nearly all test margins sit to the right of zero and all S′S' margins sit to the left. The classifier generalizes yet fails on a sample drawn from the same distribution. Lower DD to see test margins spread across zero.
[ ]Nagarajan and Kolter’s exampleBrowser
def nagarajan_kolter(m, D, rng, n_test=2000):
    """Clasificador lineal de un paso de gradiente: margen y h(x) = 4 + y w2.x2 (sección 3.1 de N&K)."""
    y = rng.choice([-1.0, 1.0], m)
    X2 = rng.standard_normal((m, D)) * np.sqrt(32 / D)          # ruido de alta dimensión
    w2 = y @ X2                                                  # w2 = sum_i y_i x2_i  (y w1 = 2 m u)
    s = (y[:, None] * X2) @ w2                                   # y_j w2.x2_j
    train = 4 + s                                                # margen en S
    neg = 4 - s                                                  # margen en S' = {((x1, -x2), y)}
    # en test, x2 es independiente de w2: y w2.x2 ~ N(0, ||w2||^2 32/D) exactamente
    test = 4 + np.linalg.norm(w2) * np.sqrt(32 / D) * rng.standard_normal(n_test)
    return [np.mean(v <= 0) for v in (train, test, neg)]

rng = np.random.default_rng(0)
print(f"{'m':>4} {'D':>6} {'error S':>8} {'test':>6} {'error S_':>8}")
for m, D in [(64, 512), (64, 4096), (64, 16384), (128, 16384)]:
    tr, te, ng = nagarajan_kolter(m, D, rng)
    print(f'{m:4d} {D:6d} {tr:8.3f} {te:6.3f} {ng:8.3f}')

With m=64m = 64 and D=16 384D = 16\,384, test error is 2.8 %2.8\,\% and error on S′S' is 100 %100\,\%. With D=512D = 512, test error increases to 36.5 %36.5\,\% and every point of S′S' remains misclassified. Doubling mm at fixed DD, with 128128 and 16 38416\,384, raises test error to 8.6 %8.6\,\%, as predicted by standard deviation 32m/D32\sqrt{m/D}. The theorem thus needs DD on the order of mln⁡mm\ln m.

Neural networks and sample size

Nagarajan and Kolter repeat the argument with a two-layer ReLU network and 100 000100\,000 hidden units. Inputs lie on two concentric spheres of radii 1 and 1.1 in R1000\R^{1000}. They train with SGD at learning rate 0.1 and batch size 64 until 99 %99\,\% of points has margin at least 10. With mm between 2122^{12} and 2162^{16}, test error falls like O(m−0.5)\bigO(m^{-0.5}). Every point of the sample S′S' is misclassified. Projecting each point onto the other sphere and flipping the label preserves the data distribution. The paper finds a related pattern in five-layer, width-1024 networks on MNIST trained by batch-size-one SGD to the same margin criterion. Test error falls like 1/m0.431/m^{0.43} while distance from initialization and the product of spectral norms grow with mm. Bounds based on these quantities grow like m0.68m^{0.68}. Such a bound worsens as sample size grows, even as observed error improves.

The argument targets two-sided bounds, which also bound L^S−LD\hat{\mathcal{L}}_S - \mathcal{L}_\mathcal{D}. The paper shows that PAC-Bayes bounds, usually stated one-sided, become nearly vacuous in its examples. Other avenues include analyzing stability for the actual data and algorithm, sample-dependent information bounds, or direct analysis of the predictor. Bartlett et al.’s linear regression analysis is an example of the last approach: it computes the minimum-norm interpolator’s risk without uniform convergence.

Open problems

  • A theory of interpolating networks. The taxonomy is understood for linear models and kernels with known spectra. Networks trained to interpolate with SGD appear tempered in Mallinar et al.’s experiments. A theory that predicts the cost of memorized noise from the architecture and data is still open.
  • Nonvacuous bounds that rank models. Optimized PAC-Bayes bounds are nonvacuous in some settings. None of the measured quantities passes Dziugaite et al.’s robust sign error test.
  • Beyond uniform convergence. The examples motivate studying a particular algorithm on its data. Bartlett, Montanari and Rakhlin (2021) survey the limits of uniform convergence, implicit regularization in gradient descent, benign interpolation and the linear regime of networks.
  • The role of memorization. Feldman explains why memorization can help in long-tailed populations. Determining how much a network needs to memorize, and how much is avoidable tempered error, remains an empirical question with privacy consequences.

Common mistakes

Exercises

ProofThe interpolator’s variance term
Prove: Let X∈Rn×p\mat{X} \in \R^{n\times p} with invertible XX⊤\mat{X}\mat{X}\T. Let y=Xθ∗+ε\vb{y} = \mat{X}\vb{\theta}^* + \vb{\eps}, where ε\vb{\eps} is independent of X\mat{X}, Eε=0\E\vb{\eps} = \vb{0} and Cov⁡(ε)=σ2In\Cov(\vb{\eps}) = \sigma^2\mat{I}_n. Set θ^=X⊤(XX⊤)−1y\hat{\vb{\theta}} = \mat{X}\T(\mat{X}\mat{X}\T)\inv\vb{y}. If new points satisfy E[xx⊤]=Σ\E[\vb{x}\vb{x}\T] = \mat{\Sigma} and y=x⊤θ∗+εy = \vb{x}\T\vb{\theta}^* + \eps, then EεR(θ^)=θ∗TBθ∗+σ2tr⁡((XX⊤)−1XΣX⊤(XX⊤)−1)\E_{\vb{\eps}}R(\hat{\vb{\theta}}) = \vb{\theta}^{*\mathsf{T}}\mat{B}\vb{\theta}^* + \sigma^2\tr\big((\mat{X}\mat{X}\T)\inv\mat{X}\mat{\Sigma}\mat{X}\T(\mat{X}\mat{X}\T)\inv\big), where B=(I−P)Σ(I−P)\mat{B} = (\mat{I} - \mat{P})\mat{\Sigma}(\mat{I} - \mat{P}) and P=X⊤(XX⊤)−1X\mat{P} = \mat{X}\T(\mat{X}\mat{X}\T)\inv\mat{X}.
0
Write M=X⊤(XX⊤)−1∈Rp×n\mat{M} = \mat{X}\T(\mat{X}\mat{X}\T)\inv \in \R^{p\times n}, so that θ^=My\hat{\vb{\theta}} = \mat{M}\vb{y} and P=MX\mat{P} = \mat{M}\mat{X}.

Step 1 of 4. What is θ^−θ∗\hat{\vb{\theta}} - \vb{\theta}^*?

NumericEffective rank of a spike and tail
Let Σ=diag⁡(1,0.01,…,0.01)\mat{\Sigma} = \diag(1, 0.01, \dots, 0.01) with 999 eigenvalues equal to 0.010.01. What is r0(Σ)=tr⁡(Σ)/∥Σ∥r_0(\mat{\Sigma}) = \tr(\mat{\Sigma})/\norm{\mat{\Sigma}}?
NumericThe theorem’s variance term
A covariance has 3 eigenvalues equal to 1 and 20,000 equal to 0.0010.001. With n=50n = 50 and b=1b = 1, compute k∗k^* and then the variance factor k∗/n+n/Rk∗(Σ)k^*/n + n/R_{k^*}(\mat{\Sigma}).
NumericThe cost of averaging k neighbors
Consider one-dimensional regression with continuous f∗f^*, noise variance σ2=0.36\sigma^2 = 0.36 independent of xx, and positive density of xx. The kk-NN predictor averages labels of the k=3k = 3 nearest neighbors, with fixed kk as n→∞n \to \infty. What is the limit of excess risk E(f^n(x)−f∗(x))2\E(\hat{f}_n(x) - f^*(x))^2?
QuizWhat Zhang et al.’s experiment shows
A network fits CIFAR-10 with random labels to zero training error. With real labels it reaches 86% test accuracy. Which conclusion is correct?
QuizHow should nearest-neighbor interpolation be classified?
The 1-NN asymptotic risk is at most 2R∗2R^* (Cover and Hart). Where does 1-NN fit in Mallinar et al.’s taxonomy, and why?
QuizWhich spectra are benign?
According to Bartlett et al., Theorem 6, which covariance spectra or sequences are benign for the minimum-norm interpolator? Use γk=e−k\gamma_k = e^{-k} in the finite-dimensional cases.

More than one answer may be correct.

QuizOne network, two parameterizations
Take a three-layer bias-free ReLU network. Multiply the first weight matrix by 10 and divide the second by 10. Which quantity distinguishes the two networks?
QuizThe crucial step in Nagarajan and Kolter’s argument
In the linear example, the classifier trained on SS fails on every point of S′S', the noise-negated sample. What property of S′S' is essential to conclude εunif-alg≥1−ε\eps_{\text{unif-alg}} \ge 1 - \eps?
QuizWhat the large-scale studies found
Which claim summarizes Jiang et al. (2020) and Dziugaite et al. (2020) on measures of generalization?
CodeThe two effective ranks
Implement effective_ranks(eigs, k). It takes covariance eigenvalues as a nonnegative array in any order and an integer k≥0k \ge 0. Return (rk,Rk)(r_k, R_k) with rk=∑i>kλi/λk+1r_k = \sum_{i>k}\lambda_i/\lambda_{k+1} and Rk=(∑i>kλi)2/∑i>kλi2R_k = (\sum_{i>k}\lambda_i)^2/\sum_{i>k}\lambda_i^2, using descending eigenvalues and indices starting at 1 in the formulas and 0 in code. Leave the input array intact. The tests use constant, geometric, and power-law spectra with closed-form results.
import numpy as np

def effective_ranks(eigs, k):
  """Devuelve (r_k, R_k) de los autovalores eigs (en cualquier orden)."""
  raise NotImplementedError
Shift+Enter to run

Summary

Key idea
A network that can memorize random labels can also generalize on real labels, so the explanation must use the data. In linear regression, the minimum-norm interpolator is close to optimal when the covariance has a few signal directions and a long, flat, light tail that absorbs noise (r0≪nr_0 \ll n, k∗≪nk^* \ll n, Rk∗≫nR_{k^*} \gg n). Many interpolators outside this setting show tempered overfitting, including neural networks. The uniform convergence examples show that even tightly focused bounds can be vacuous.
  • Zhang et al. (2017) found that the same networks reached zero training error on real and random labels, with only a modest increase in training time. Bounds based only on the class or algorithm and nn must cover the random case and can be vacuous.
  • In Bartlett, Long, Lugosi and Tsigler’s theorem, for k∗=min⁡{k:rk≥bn}k^* = \min\{k : r_k \ge bn\}, if r0≤nr_0 \le n and k∗<n/c1k^* < n/c_1, minimum-norm risk is bounded up to constants and confidence factors by ∥θ∗∥2∥Σ∥r0/n+σ2(k∗/n+n/Rk∗)\norm{\vb{\theta}^*}^2\norm{\mat{\Sigma}}\sqrt{r_0/n} + \sigma^2(k^*/n + n/R_{k^*}). The upper and lower bounds on the variance term match in order.
  • The covariance tail absorbs noise across many low-variance directions (n/Rk∗n/R_{k^*}) and induces a ridge penalty of size ∑i>k∗λi\sum_{i>k^*}\lambda_i on signal directions.
  • Mallinar et al.’s taxonomy distinguishes benign (Rn→R∗R_n \to R^*), tempered (a finite plateau) and catastrophic (Rn→∞R_n \to \infty) behavior. 1-NN (excess σ2\sigma^2), unregularized Laplace (2σ2/32\sigma^2/3 in 1D) and the studied interpolating networks are tempered. Singular-kernel Nadaraya–Watson is benign and unregularized Gaussian interpolation is catastrophic.
  • In Feldman’s long-tailed distributions, skipping memorization costs τ1\tau_1 in error per singleton. With Zipf frequencies and n=50 000n = 50\,000, it costs four error points for two classes.
  • Spectrally normalized margin bounds depend on data and rise with label noise, but are vacuous by many orders of magnitude. In large-scale studies no measure robustly predicts generalization across interventions.
  • Nagarajan and Kolter exhibit algorithms with generalization error ε\eps and a tightest uniform bound of at least 1−ε1 - \eps, even when the class is restricted to the algorithm’s outputs.