4.5 Generalization in Deep Learning

In Section 2.6, a degree-19 polynomial with 2020 parameters interpolated 2020 noisy data points and blew up on test data. By that classical intuition, our Fashion-MNIST MLP in Section 4.2, with 203,530203{,}530 parameters for 60,00060{,}000 training images (3.43.4 parameters per image), ought to overfit severely, especially if trained until it interpolates every single training image. Yet it reached ∼87%\sim 87\% accuracy on unseen images. And as we will see below, the same architecture given only 1,0001{,}000 training images and driven to 100%100\% training accuracy still classifies about 80%80\% of unseen images correctly.

Understanding why heavily overparameterized networks generalize is one of the central open problems of modern machine learning. In this section, we combine controlled experiments with exact results on tractable models to uncover four key pieces of the puzzle:

  1. Random-label memorization: Standard MLPs easily reach 100%100\% training accuracy on completely random labels (Zhang et al., 2021), proving that classical distribution-free capacity bounds (like VC dimension) cannot explain their generalization on real labels.
  2. Double descent: Sweeping model width past the interpolation threshold h=nh = n reveals a spike in test error at h=nh = n (where the feature matrix is nearly singular) followed by a second descent as extra parameters allow smaller-norm interpolators (Belkin et al., 2019).
  3. Implicit bias of gradient descent: Among infinitely many zero-loss solutions, gradient descent automatically selects the minimum-norm interpolator under squared loss and the maximum-margin separator under logistic loss (Soudry et al., 2018).
  4. Clean-first learning and early stopping: On noisy datasets, gradient descent fits clean structured patterns long before memorizing corrupted labels (Arpit et al., 2017), making early stopping a potent regularizer.

4.5.1 Memorization and Capacity#

4.5.1.1 Random Labels#

To test raw memorization capacity following Zhang et al. (2021), we draw 2,0002{,}000 Fashion-MNIST training images (1,0001{,}000 for training, 1,0001{,}000 for validation) and 2,0002{,}000 test images, define ArrayData and Tracker helpers along with a He-initialized 256-unit MLP, and train for 200 epochs once on the true labels (fraction=0) and once on completely random labels (fraction=1):

data = d2l.FashionMNIST(batch_size=2000)
X, y = next(iter(data.train_dataloader()))          # 2,000 random images
X_test, y_test = next(iter(data.val_dataloader()))  # the first 2,000
X, y, X_test, y_test = (d2l.numpy(a) for a in (X, y, X_test, y_test))
X, X_test = X.reshape(2000, -1), X_test.reshape(2000, -1)
X_train, y_train, X_val, y_val = X[:1000], y[:1000], X[1000:], y[1000:]

Two lightweight helpers streamline the experiments ahead: ArrayData wraps NumPy arrays into shuffled minibatches, and Tracker subclasses Trainer to log epoch-by-epoch accuracy across an arbitrary dictionary of named datasets.

class ArrayData(d2l.DataModule):
    """Minibatches of the arrays X and y; training batches are shuffled."""
    def __init__(self, X, y, batch_size=64):
        super().__init__()
        self.save_hyperparameters()

    def get_dataloader(self, train):
        return self.get_tensorloader(
            (d2l.tensor(self.X), d2l.tensor(self.y)), train)

class Tracker(d2l.Trainer):
    """A Trainer that records the accuracy on named datasets every epoch."""
    def __init__(self, max_epochs, datasets):
        super().__init__(max_epochs, num_gpus=1)
        self.datasets = datasets
        self.accuracy = {name: [] for name in datasets}
        self.board.display = False  # We plot the accuracies ourselves

    def validate(self):
        for name, dataset in self.datasets.items():
            self.val_dataloader = dataset.val_dataloader()
            self.accuracy[name].append(super().validate()['acc'])
        return {}

Our model is the same 256-unit ReLU MLP from Section 4.2, upgraded with He initialization (Section 4.4.2.2) in place of std=0.01 so training takes off immediately from epoch 1 (with zero biases and pre-flattened inputs).

class MLP(d2l.Classifier):
    def __init__(self, num_hiddens, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(nn.LazyLinear(num_hiddens), nn.ReLU(),
                                 nn.LazyLinear(10))

    def weight_init(self, module):
        if isinstance(module, nn.Linear):
            nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
            nn.init.zeros_(module.bias)

Now we define corrupt(y, fraction, rng) to replace each training label with a uniform random class in {0,…,9}\{0, \ldots, 9\} with probability fraction, train MLP(num_hiddens=256, lr=0.1) for 200200 epochs at fraction = 0 (true labels) and fraction = 1 (pure random labels), and plot both training and test accuracy trajectories:

def corrupt(y, fraction, rng):
    """Replace each label, with probability fraction, by a random class."""
    redraw = rng.random(len(y)) < fraction
    y = y.copy()
    y[redraw] = rng.integers(0, 10, redraw.sum())
    return y

rng = np.random.default_rng()
curves = []
for fraction in (0, 1):
    labels = corrupt(y_train, fraction, rng)
    trainer = Tracker(max_epochs=200, datasets={
        'train': ArrayData(X_train, labels, 1000),
        'test': ArrayData(X_test, y_test, 1000)})
    trainer.fit(MLP(num_hiddens=256, lr=0.1), ArrayData(X_train, labels))
    curves += [trainer.accuracy['train'], trainer.accuracy['test']]
d2l.plot(list(range(1, 201)), curves, 'epoch', 'accuracy',
         fmts=('C0-', 'C1-', 'C0--', 'C1--'), figsize=(5, 3))
d2l.plt.legend(['train, true labels', 'test, true labels',
                'train, random labels', 'test, random labels'],
               loc='center right', bbox_to_anchor=(1, 0.4));

Look at what the two runs prove:

  • On true labels, training accuracy hits 100%100\% within 60–90 epochs while test accuracy plateaus above 80%80\% (even on just 1,0001{,}000 training images).
  • On completely random labels, the exact same architecture and optimizer still reach 100%100\% training accuracy (taking slightly longer, ∼120\sim 120–150150 epochs) while test accuracy remains at 10%10\% random chance.

4.5.1.2 Limits of Capacity Bounds and Inductive Bias#

Because our MLP achieves zero training error (ϵS(f)=0\epsilon_{\mathcal{S}}(f) = 0) on random labels where the true population error is ϵ(f)=0.90\epsilon(f) = 0.90, any distribution-free bound of the form ϵ(f)≤ϵS(f)+B(F,n,δ)\epsilon(f) \leq \epsilon_{\mathcal{S}}(f) + B(\mathcal{F}, n, \delta) that depends only on the hypothesis class F\mathcal{F} must have B(F,n,δ)≥0.90B(\mathcal{F}, n, \delta) \geq 0.90, making it vacuous on real labels as well (Exercise 1).

By the no free lunch theorem (Wolpert, 1996), no learner can generalize across all distributions; generalization depends on whether the learner's inductive bias—which interpolating function it prefers among infinitely many—matches the structure of real data, just as a 1-nearest-neighbor classifier interpolates 100%100\% of its training data yet generalizes well whenever nearby inputs share labels (Cover and Hart, 1967).

4.5.2 Double Descent#

4.5.2.1 The Interpolation Threshold and Conditioning#

What happens when we increase model width hh right past the sample size nn? Let us test a tractable random-features model (Rahimi and Recht, 2007): we freeze a He-initialized first layer W(1)∈R784×10000\mathbf{W}^{(1)} \in \mathbb{R}^{784 \times 10000} on our n=1,000n = 1{,}000 centered training images to precompute 10,00010{,}000 random ReLU features H and H_test, encode the labels as a one-hot matrix Y, and define error(H, W2, y):

W1 = rng.normal(0, np.sqrt(2 / 784), (784, 10000))  # He-initialized, frozen
mean = X_train.mean(axis=0)                         # The mean training image
H = np.maximum((X_train - mean) @ W1, 0)
H_test = np.maximum((X_test - mean) @ W1, 0)
Y = np.eye(10)[y_train]                             # One-hot labels

def error(H, W2, y):
    """Fraction of examples whose largest output is not their label."""
    return (np.argmax(H @ W2, axis=1) != y).mean()

We now sweep the hidden width h across 15 values from 5050 to 10,00010{,}000, fitting the output weights W(2)∈Rh×10\mathbf{W}^{(2)} \in \mathbb{R}^{h \times 10} on the first h feature columns H[:, :h] by minimum-norm least squares (np.linalg.lstsq) while recording the smallest singular value s_min[h] and Frobenius norm norm[h]:

widths = [50, 100, 200, 400, 600, 800, 900, 1000, 1100, 1200, 1500, 2000,
          3000, 5000, 10000]
train_err, test_err, s_min, norm = [], [], {}, {}
for h in widths:
    W2, _, _, s = np.linalg.lstsq(H[:, :h], Y, rcond=None)
    train_err.append(error(H[:, :h], W2, y_train))
    test_err.append(error(H_test[:, :h], W2, y_test))
    s_min[h], norm[h] = s.min(), np.linalg.norm(W2)
d2l.plot([widths, widths, [1000, 1000]], [train_err, test_err, [0, 1]],
         'hidden units h', 'error', legend=['train', 'test', 'h = n'],
         xscale='log', fmts=('C0-', 'C1-', 'k:'), figsize=(5, 3))

This is the celebrated double-descent curve (Belkin et al., 2019):

  1. Classical U-curve (h<nh \lt n): Test error drops from ∼30%\sim 30\% at h=50h = 50 to ∼23%\sim 23\% around h=200h = 200, then shoots up to ∼90%\sim 90\% right at the interpolation threshold h=n=1,000h = n = 1{,}000.
  2. Second descent (h>nh > n): As hh grows past n=1,000n = 1{,}000 up to 10,00010{,}000, every model interpolates the training set, yet test error plunges back down to ∼20%\sim 20\%, beating the best underparameterized model.

Why does test error spike so violently at h=nh = n and heal for h≫nh \gg n? Let us inspect the smallest singular value smin⁡s_{\min} of H:,:h\mathbf{H}_{:, :h} and the Frobenius norm ∥W(2)∥F\|\mathbf{W}^{(2)}\|_{\textrm{F}}:

for h in (200, 900, 1000, 1100, 10000):
    print(f'h = {h:5d}: smallest singular value {s_min[h]:.1e}, '
          f'norm of W2 {norm[h]:6.1f}')
h =   200: smallest singular value 1.7e+00, norm of W2    3.7
h =   900: smallest singular value 1.2e-01, norm of W2   20.4
h =  1000: smallest singular value 2.0e-04, norm of W2 1577.9
h =  1100: smallest singular value 2.3e-02, norm of W2   20.4
h = 10000: smallest singular value 2.1e-01, norm of W2    2.2

At h=n=1,000h = n = 1{,}000, H\mathbf{H} is a square 1000×10001000 \times 1000 matrix with a tiny smallest singular value smin⁡s_{\min}, so the unique exact inverse H−1Y\mathbf{H}^{-1}\mathbf{Y} divides label noise by smin⁡s_{\min} and explodes ∥W(2)∥F\|\mathbf{W}^{(2)}\|_{\textrm{F}} into the hundreds or more. For h≫nh \gg n, the extra columns open up an (h−n)(h - n)-dimensional subspace of exact interpolators, allowing the minimum-norm solution to avoid poorly conditioned directions and shrink ∥W(2)∥F\|\mathbf{W}^{(2)}\|_{\textrm{F}} all the way down to ∼2\sim 2. In fact, holding h=1,000h = 1{,}000 fixed, doubling the training set from n=500n = 500 to n=1,000n = 1{,}000 lands the unregularized fit squarely on the h=nh = n cliff and drives test error up from ∼30%\sim 30\% to 85–90%85\text{--}90\%:

for n in (500, 1000):
    W2 = np.linalg.lstsq(H[:n, :1000], Y[:n], rcond=None)[0]
    test_error = error(H_test[:, :1000], W2, y_test)
    print(f'{n} training images: test error {test_error:.2f}')
500 training images: test error 0.28
1000 training images: test error 0.89

4.5.3 Implicit Bias of Gradient Descent#

The second descent above relied on lstsq picking the minimum-norm interpolator among infinitely many zero-loss solutions. Remarkably, gradient descent has that exact preference built in—an implicit bias (or implicit regularization) that operates even without any explicit penalty term.

4.5.3.1 Minimum-Norm Interpolation under Squared Loss#

For an overparameterized linear system Hw=y\mathbf{H}\mathbf{w} = \mathbf{y} (h>nh > n, full row rank), the unique minimum-norm interpolator is w⋆=H⊤(HH⊤)−1y\mathbf{w}^\star = \mathbf{H}^\top(\mathbf{H}\mathbf{H}^\top)^{-1}\mathbf{y}.

Proposition. Gradient descent on L(w)=12∥Hw−y∥22L(\mathbf{w}) = \frac{1}{2}\|\mathbf{H}\mathbf{w} - \mathbf{y}\|_2^2 initialized at w0=0\mathbf{w}_0 = \mathbf{0} (with a converging step size) converges to the minimum-norm interpolator w⋆\mathbf{w}^\star.

Proof. Every gradient ∇L(w)=H⊤(Hw−y)\nabla L(\mathbf{w}) = \mathbf{H}^\top(\mathbf{H}\mathbf{w} - \mathbf{y}) lies in the row space of H\mathbf{H}. Starting at w0=0\mathbf{w}_0 = \mathbf{0}, every iterate wt\mathbf{w}_t, and hence the limit w∞=H⊤a\mathbf{w}_{\infty} = \mathbf{H}^\top\mathbf{a}, remains in the row space of H\mathbf{H} (Figure 4.5.1). Since Hw∞=HH⊤a=y\mathbf{H}\mathbf{w}_{\infty} = \mathbf{H}\mathbf{H}^\top\mathbf{a} = \mathbf{y}, we have a=(HH⊤)−1y\mathbf{a} = (\mathbf{H}\mathbf{H}^\top)^{-1}\mathbf{y} and w∞=w⋆\mathbf{w}_{\infty} = \mathbf{w}^\star. Any other interpolator w⋆+v\mathbf{w}^\star + \mathbf{v} has Hv=0\mathbf{H}\mathbf{v} = \mathbf{0} (so v⊥w⋆\mathbf{v} \perp \mathbf{w}^\star) and strictly larger norm ∥w⋆∥22+∥v∥22\|\mathbf{w}^\star\|_2^2 + \|\mathbf{v}\|_2^2. ■\blacksquare

Figure 4.5.1:

Gradient descent on an underdetermined linear equation h⊤w=y\mathbf{h}^\top\mathbf{w} = y moves strictly perpendicular to the solution hyperplane, so starting from 0\mathbf{0} (blue) lands at the minimum-norm solution w⋆\mathbf{w}^\star, whereas starting from w0≠0\mathbf{w}_0 \neq \mathbf{0} (orange) preserves the null-space component of w0\mathbf{w}_0.

Let us verify this proposition numerically on 2020 equations in 100100 unknowns, comparing w0=0\mathbf{w}_0 = \mathbf{0} against a random initialization:

H_small = rng.normal(size=(20, 100))
y_small = rng.normal(size=20)
w_star = np.linalg.lstsq(H_small, y_small, rcond=None)[0]
lr = 1 / np.linalg.norm(H_small, 2) ** 2  # Below 2 / largest curvature
for name, w in (('zero', np.zeros(100)), ('random', rng.normal(size=100))):
    for _ in range(2000):
        w = w - lr * H_small.T @ (H_small @ w - y_small)
    residual = np.linalg.norm(H_small @ w - y_small)
    print(f'start {name:6s}: residual {residual:.0e}, norm '
          f'{np.linalg.norm(w):5.2f}, distance to w* '
          f'{np.linalg.norm(w - w_star):.1f}')
start zero  : residual 8e-17, norm  0.79, distance to w* 0.0
start random: residual 3e-15, norm  9.39, distance to w* 9.4

4.5.3.2 Maximum-Margin Classification under Logistic Loss#

On linearly separable binary classification data (yi∈{−1,+1}y_i \in \{-1, +1\}) under the logistic (cross-entropy) loss ∑ilog⁡(1+exp⁡(−yiw⊤xi))\sum_i \log(1 + \exp(-y_i \mathbf{w}^\top\mathbf{x}_i)), ∥wt∥2→∞\|\mathbf{w}_t\|_2 \to \infty as t→∞t \to \infty, and Soudry et al. (2018) proved that the direction wt/∥wt∥2\mathbf{w}_t / \|\mathbf{w}_t\|_2 converges (at a 1/log⁡t1/\log t rate) to the hard-margin SVM maximum-margin separator (Figure 4.5.2), because support vectors with the smallest margins dominate the exponentially decaying tail of log⁡(1+e−m)\log(1 + e^{-m}) (see Exercise 5 for how layer rescaling complicates parameter-norm margins in multi-layer ReLU networks).

Figure 4.5.2:

Gradient descent on linearly separable logistic regression rotates wt/∥wt∥2\mathbf{w}_t / \|\mathbf{w}_t\|_2 toward the maximum-margin hyperplane (left) at a logarithmic rate that continues long after training accuracy reaches 100%100\% (right).

4.5.4 Early Stopping#

Even when an MLP has enough capacity to memorize corrupted labels, gradient descent learns clean structured patterns first and memorizes label noise much later (Arpit et al., 2017). Let us corrupt 20%20\% of the labels in our 1,0001{,}000-image training set and track accuracy separately on the clean training examples, the mislabeled training examples (scored against their corrupted labels), and the 1,0001{,}000 clean validation images over 200 epochs:

labels = corrupt(y_train, 0.2, rng)
wrong = labels != y_train
trainer = Tracker(max_epochs=200, datasets={
    'clean': ArrayData(X_train[~wrong], labels[~wrong], 1000),
    'mislabeled': ArrayData(X_train[wrong], labels[wrong], 1000),
    'validation': ArrayData(X_val, y_val, 1000),
    'test': ArrayData(X_test, y_test, 1000)})
trainer.fit(MLP(num_hiddens=256, lr=0.1), ArrayData(X_train, labels))
acc = trainer.accuracy
d2l.plot(list(range(1, 201)), [acc['clean'], acc['mislabeled'],
                               acc['validation']], 'epoch', 'accuracy',
         legend=['clean training labels', 'wrong training labels',
                 'validation'], figsize=(5, 3))

By epoch 20, the MLP gets over 80%80\% of the clean training images right while memorizing fewer than 20%20\% of the corrupted labels, and validation accuracy reaches its peak in this early window before late-epoch noise memorization drags it down. Early stopping, halting training once validation performance fails to improve for a specified patience window (Exercise 2) and restoring the best validation checkpoint, recovers several percentage points of test accuracy while saving compute (and in linear least squares acts analogously to ℓ2\ell_2 weight decay; see Exercise 4):

best = int(np.argmax(acc['validation']))
print(f'best validation accuracy after epoch {best + 1}: '
      f'test accuracy {acc["test"][best]:.3f}')
print(f'after all 200 epochs: test accuracy {acc["test"][-1]:.3f}')
best validation accuracy after epoch 16: test accuracy 0.775
after all 200 epochs: test accuracy 0.716

One famous exception to early stopping is grokking (Power et al., 2022) (Figure 4.5.3, Exercise 6), where networks trained with weight decay on small algorithmic tasks (such as modular addition) memorize the training table rapidly while validation accuracy remains near chance for 100×100\times longer before suddenly jumping to 100%100\%.

Figure 4.5.3:

Grokking (Power et al. (2022)): on modular arithmetic, training accuracy saturates within ∼103\sim 10^3 steps while validation accuracy jumps to generalization only after ∼105\sim 10^5 steps.

4.5.5 Summary#

Overparameterized neural networks can memorize completely random labels while generalizing well on structured data, rendering distribution-free capacity bounds vacuous and placing the burden of explanation on inductive bias. In random-features least squares, test error spikes at the interpolation threshold h=nh = n, where a tiny smallest singular value smin⁡(H)s_{\min}(\mathbf{H}) inflates ∥W(2)∥\|\mathbf{W}^{(2)}\|, and descends a second time for h≫nh \gg n as minimum-norm interpolation spreads weights across redundant features. Remarkably, gradient descent from zero finds this minimum-norm interpolator automatically under squared loss and converges in direction to the maximum-margin separator under logistic loss. Because gradient descent also fits coherent patterns before memorizing corrupted labels, early stopping on a validation set serves as a simple and effective regularizer.

4.5.6 Exercises#

  1. Limits of complexity measures. Consider a generalization bound that holds for every data distribution: with probability at least 1−δ1 - \delta over the draw of nn training examples, every classifier ff in a class F\mathcal{F} satisfies
ϵ(f)≤ϵS(f)+B(F,n,δ).(4.5.1)\epsilon(f) \leq \epsilon_\mathcal{S}(f) + B(\mathcal{F}, n, \delta). \tag{4.5.1}

Here ϵ(f)\epsilon(f) is the population error, ϵS(f)\epsilon_\mathcal{S}(f) is the training error, and the term BB depends only on F\mathcal{F}, nn, and δ\delta, as the term c(v+log⁡(1/δ))/nc\sqrt{(v + \log(1/\delta))/n} of the VC bound does. The text ran the random-label argument against such a bound for 1,000 images.

  1. Suppose that training also finds a member of F\mathcal{F} with zero training error on all 60,000 Fashion-MNIST training images when their labels are drawn uniformly at random, as Zhang et al. (2021) observed for image classifiers. What lower bound on B(F,60,000,δ)B(\mathcal{F}, 60{,}000, \delta) follows, and what does the bound then guarantee for the network trained on the true labels?
  2. Many later bounds let the second term depend on the classifier that training returns, for example through the norm of its weights or through its margins on the training examples. Which step of the argument no longer goes through? What must such a quantity do on the random-label run if the bound is to say something on the true labels?
  1. [code] Patience-based stopping. FashionMNIST uses the Fashion-MNIST test set as its validation data, so hold out 10,000 training images as a validation set instead. Train an MLP with one hidden layer of 256 units, as in Section 4.2, on the remaining images for a fixed number of epochs large enough to overfit, and record the validation loss and the test accuracy after every epoch. A patience rule with tolerance θ\theta and patience kk stops once the validation loss has failed to improve on its best value by more than θ\theta for kk consecutive epochs. It then retains the parameters of the epoch with the lowest validation loss so far.

    1. Fix θ\theta and apply the rule to the recorded curves for k∈{1,5,20}k \in \{1, 5, 20\}. For each kk, report the stopping epoch, the retained epoch, and the test accuracy at both.
    2. How does the test accuracy at the retained epoch depend on kk? Relate the dependence to the epoch-to-epoch fluctuation of the validation loss.

    Adapted from Michael Nielsen, Neural Networks and Deep Learning, Chapter 3.

  2. [code] Weight decay at the threshold. Replace the minimum-norm fit of the double-descent experiment by the ridge solution W(2)=(1nH⊤H+λI)−11nH⊤Y\mathbf{W}^{(2)} = (\frac{1}{n}\mathbf{H}^\top\mathbf{H} + \lambda \mathbf{I})^{-1}\frac{1}{n}\mathbf{H}^\top\mathbf{Y} of Section 2.7, which, as there, averages the squared error over the nn examples.

    1. Plot the test error against the width for λ∈{10−5,10−3,10−1}\lambda \in \{10^{-5}, 10^{-3}, 10^{-1}\}. What happens to the peak at h=nh = n?
    2. Show that the ridge solution approaches the minimum-norm solution as λ→0\lambda \to 0 for h>nh > n. Hint: write (1nH⊤H+λI)−11nH⊤=H⊤(HH⊤+nλI)−1(\frac{1}{n}\mathbf{H}^\top\mathbf{H} + \lambda \mathbf{I})^{-1}\frac{1}{n}\mathbf{H}^\top = \mathbf{H}^\top(\mathbf{H}\mathbf{H}^\top + n\lambda \mathbf{I})^{-1}.
    3. For each width, choose λ\lambda on the 1,000 validation images. Does the curve of the tuned model still descend twice?
  3. Early stopping and weight decay. ● Early stopping limits the number of training epochs where weight decay limits the weights. Linear least squares makes this precise. Let X⊤X/n\mathbf{X}^\top\mathbf{X}/n have eigenvalues μi>0\mu_i > 0, let w∗\mathbf{w}^* minimize L(w)=12n∥Xw−y∥2L(\mathbf{w}) = \frac{1}{2n}\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2, and run gradient descent on LL from w0=0\mathbf{w}_0 = \mathbf{0} with learning rate η<1/max⁡iμi\eta \lt 1/\max_i \mu_i.

    1. Show that after tt steps the coordinate of wt\mathbf{w}_t along the ii-th eigenvector equals 1−(1−ημi)t1 - (1 - \eta\mu_i)^t times that of w∗\mathbf{w}^*.
    2. The minimizer of L(w)+λ2∥w∥2L(\mathbf{w}) + \frac{\lambda}{2}\|\mathbf{w}\|^2 scales the same coordinate by μi/(μi+λ)\mu_i/(\mu_i + \lambda) (Section 2.7.3). For which λ\lambda, as a function of η\eta and tt, do the two factors approximately agree both in the directions with ημit≪1\eta\mu_i t \ll 1 and in those with ημit≫1\eta\mu_i t \gg 1?

    Adapted from Ian Goodfellow, Yoshua Bengio, and Aaron Courville, Deep Learning, Section 7.8.

  4. Implicit bias of the logistic loss. ● For linearly separable data, gradient descent on the logistic loss converges in direction to the maximum-margin separator (Soudry et al., 2018). Take labels yi∈{−1,+1}y_i \in \{-1, +1\}.

    1. For a linear predictor f(x)=w⊤xf(\mathbf{x}) = \mathbf{w}^\top\mathbf{x}, show that on separable data the loss ∑ilog⁡(1+exp⁡(−yiw⊤xi))\sum_i \log\left(1 + \exp(-y_i \mathbf{w}^\top\mathbf{x}_i)\right) is positive for every w\mathbf{w} but has infimum zero. Conclude that ∥wt∥\|\mathbf{w}_t\| grows without bound when gradient descent drives the loss to zero, so that only the direction wt/∥wt∥\mathbf{w}_t/\|\mathbf{w}_t\| can converge.
    2. For a two-layer ReLU network f(x)=∑jvjmax⁡(0,wj⊤x)f(\mathbf{x}) = \sum_j v_j \max(0, \mathbf{w}_j^\top\mathbf{x}), show that replacing (wj,vj)(\mathbf{w}_j, v_j) by (cjwj,vj/cj)(c_j\mathbf{w}_j, v_j/c_j) with cj>0c_j > 0 leaves ff unchanged. Find the smallest value of ∑j(∥wj∥2+vj2)\sum_j (\|\mathbf{w}_j\|^2 + v_j^2) over these rescalings. Explain why a margin measured with the parameter norm of the network, unlike one measured with ∥w∥\|\mathbf{w}\| for the linear predictor, is not a property of the function ff alone.
  5. [extended] Grokking. ●● Reproduce the setup of Power et al. (2022): train a small network (they use a two-layer transformer, but a wide MLP on one-hot pairs also works) to predict c=(a+b) mod 97c = (a + b) \bmod 97 from the pair (a,b)(a, b), using a random 50% of all pairs for training, with weight decay, for 10510^5 or more steps. Plot training and validation accuracy against the logarithm of the step count, and compare with Figure 4.5.3. How does the delay before generalization change with the training fraction and with the weight-decay strength?

Discussions