Weight Decay

Dive into Deep Learning · §2.7

Weight Decay & Spectral Regularization
ℓ₂ ridge penalty · multiplicative decay · ℓ₁ lasso sparsity · Gaussian MAP prior · eigenspectrum shrinkage

Why Feature Selection Fails on Collinear Features

Motivation: The Two-Thermometer Pathology

  • Model A (\mathbf{w} = (1, 1)^\top): Averages two sensors x_1 \approx x_2 with \|\mathbf{w}\|_2^2 = 2, cutting sensor noise variance in half.
  • Model B (\mathbf{w} = (501, -499)^\top): Has \|\mathbf{w}\|_2^2 = 500{,}002; fits tiny noise in x_1 - x_2 and amplifies a 2^\circ sensor drift by +1{,}000.
  • Continuous capacity control: Penalizing \|\mathbf{w}\|_2^2 keeps all d features while continuously damping poorly determined directions.

The ℓ₂-Penalized Objective (Ridge Regression)

Penalized Empirical Risk

L_{\lambda}(\mathbf{w}, b) = L(\mathbf{w}, b) + \frac{\lambda}{2}\|\mathbf{w}\|_2^2

  • Lipschitz sensitivity bound: Bounding \|\mathbf{w}\|_2 bounds |\mathbf{w}^\top(\mathbf{x} - \mathbf{x}')| \leq \|\mathbf{w}\|_2\|\mathbf{x} - \mathbf{x}'\|_2.
  • Unpenalized bias & standardized features: The intercept b only shifts baseline output units and is left unpenalized; features should be standardized to unit variance.

Why ℓ₂ Regularization Is Called ‘Weight Decay’

Per-Step Multiplicative Shrinkage

\mathbf{w} \leftarrow (1 - \eta\lambda)\,\mathbf{w} - \eta\,\nabla_{\mathbf{w}} L_{\mathcal{B}}(\mathbf{w}, b)

  • Multiplicative contraction: Before applying the data gradient step -\eta\nabla_{\mathbf{w}} L_{\mathcal{B}}, each update shrinks \mathbf{w} toward \mathbf{0} by (1 - \eta\lambda) < 1.
  • Geometric decay of unreinforced directions: Where \nabla_{\mathbf{w}} L_{\mathcal{B}} = \mathbf{0}, weights decay exponentially as (1 - \eta\lambda)^t.

Constraint Geometry: ℓ₂ Ridge vs. ℓ₁ Lasso Sparsity

Why Lasso Zeroes Coordinates While Ridge Keeps All Nonzero

By Lagrangian duality, minimizing L(\mathbf{w}) + \frac{\lambda}{2}\|\mathbf{w}\|_p^p is equivalent to minimizing L(\mathbf{w}) inside a norm ball \|\mathbf{w}\|_p \leq r:

  • \ell_2 Ridge (smooth disk \|\mathbf{w}\|_2 \leq r): Expanding elliptical contours of L(\mathbf{w}) centered at \hat{\mathbf{w}} meet the smooth circle tangentially away from the axes, keeping all coordinates nonzero and preferring (1, 1)^\top over (2, 0)^\top.
  • \ell_1 Lasso (sharp diamond \|\mathbf{w}\|_1 \leq r): The \ell_1 ball \sum_j |w_j| \leq r has sharp corners sitting directly on the coordinate axes; loss contours frequently hit a corner first, setting w_1 = 0 (sparsity / feature selection).

Bayesian View: MAP Estimation With a Gaussian Prior

Probabilistic Derivation of λ

-\log p(\mathbf{w} \mid \mathbf{X}, \mathbf{y}) = \frac{n}{\sigma^2}L(\mathbf{w}, b) + \frac{1}{2\tau^2}\|\mathbf{w}\|_2^2 + \textrm{const} \implies \lambda = \frac{\sigma^2}{n\tau^2}

  • Zero-mean Gaussian prior w_j \sim \mathcal{N}(0, \tau^2): Maximizing the posterior density yields ridge regression with \lambda = \sigma^2 / (n\tau^2) (1/3 for \sigma = 1, n = 300, \tau = 0.1).

High-Dimensional Testbed: 200 Features, 300 Examples

From-Scratch Experimental Setup

tau, sigma, n = 0.1, 1.0, 300   # size of the weights, noise, examples
data = d2l.SyntheticRegressionData(w=d2l.ones(200) * tau, b=0.05,
                                   noise=sigma, num_train=n, num_val=1000,
                                   batch_size=20)
class WeightDecayScratch(d2l.LinearRegressionScratch):
    def __init__(self, num_inputs, lambd, lr, sigma=0.01):
        super().__init__(num_inputs, lr, sigma)
        self.save_hyperparameters()

    def training_step(self, batch):
        loss = super().training_step(batch)
        return loss + self.lambd * l2_penalty(self.w)
  • Reference benchmarks: Oracle (\mathbf{w}^*, b^*) achieves \frac{1}{2}\sigma^2 = 0.50, whereas constant predictor \mathbf{w} = \mathbf{0} incurs \frac{1}{2}(\|\mathbf{w}^*\|_2^2 + \sigma^2) = 1.50.

Unregularized (λ = 0) vs. Prior Decay (λ = 1/3)

Overfitting Cured by Weight Decay

For \sigma = 1.0, n = 300, \tau = 0.1, the Gaussian prior formula prescribes \lambda = \sigma^2 / (n\tau^2) = 1 / (300 \times 0.01) = \frac{1}{3}:

validation loss 1.610 (lowest 0.891, epoch 2), norm of w 2.03
validation loss 0.874, norm of w 1.17
  • Without penalty (\lambda = 0): Training loss drops to \sim 0.25 (far below the 0.50 noise floor), while validation loss climbs to 1.1–1.9, no better than the trivial constant predictor at 1.50.
  • With penalty (\lambda = 1/3): Validation loss stabilizes at 0.8–1.0 and \|\hat{\mathbf{w}}\|_2 \approx 1.2 stays compact.

Spectral View: Shrinkage in the Eigenbasis of XᵀX/n

Why Weight Decay Is Directional Filtering, Not Blind Scaling

\mathbf{v}_j^\top \hat{\mathbf{w}}_{\lambda} = \frac{\mu_j}{\mu_j + \lambda}\bigl(\mathbf{v}_j^\top \hat{\mathbf{w}}_0\bigr), \qquad \operatorname{df}(\lambda) = \sum_{j=1}^d \frac{\mu_j}{\mu_j + \lambda}

  • Variance-adaptive filtering: Preserves well-determined directions (\mu_j \gg \lambda), strongly damps noisy collinear directions (\mu_j \ll \lambda), and zeroes null-space directions (\mu_j = 0).

Visualizing the Directional Shrinkage Factor μ/(μ + λ)

Variance-Adaptive Filtering

  • Half-power threshold (\mu_j = \lambda): An eigendirection whose empirical feature variance equals \lambda has its least-squares coefficient halved (\frac{\mu_j}{\mu_j + \lambda} = \frac{1}{2}).
  • Null-space annihilation (\mu_j = 0): Any unobserved direction (d > n or exact duplicate features) is set identically to 0.
  • Two-thermometer resolution: For x_1 \approx x_2, the sum direction \mathbf{v}_+ = (1, 1)^\top/\sqrt{2} has \mu_+ \approx 2 \gg \lambda (preserved), while the difference direction \mathbf{v}_- = (1, -1)^\top/\sqrt{2} has \mu_- \approx 10^{-6} \ll \lambda (zeroed out, forcing \hat{w}_1 \approx \hat{w}_2 \approx 1).

Spectrum and Error Breakdown on Our 200 Features

Where the Error Lives

mu from 0.04 to 3.2, 54 of 200 below lambda
factors from 0.10 to 0.91, df = 127
  lambda = 0: squared error 1.49 in the 54 poorly determined directions, 0.52 in the rest
lambda = 1/3: squared error 0.30 in the 54 poorly determined directions, 0.40 in the rest
  • Selective noise removal: Roughly k \approx 55 eigenvalues fall below \lambda = 1/3 (\operatorname{df} \approx 127); turning on \lambda = 1/3 slashes squared error in those noisy directions by 2\times–6\times.

Why Unregularized SGD Peaked Early: Early Stopping

Spectral Dynamics of Gradient Descent

  • Eigenvalue-dependent speed: Along \mathbf{v}_j, each step contracts the gap to \hat{w}_{0,j} by (1 - \eta\mu_j)—after 1 epoch (15 steps at \eta = 0.05), \mu_j = 3.2 is 93\% converged while \mu_j = 0.04 is only 3\% converged.
  • Early stopping as a spectral filter: Stopping after T steps applies filter 1 - (1 - \eta\mu_j)^T \approx \mu_j / (\mu_j + 1/(\eta T)), mimicking ridge without a penalty.

Concise Implementation: Optimizer-Level Weight Decay

Framework Parameter Groups & Masks

class WeightDecay(d2l.LinearRegression):
    def __init__(self, wd, lr):
        super().__init__(lr)
        self.save_hyperparameters()

    def configure_optimizers(self):
        return torch.optim.SGD([
            {'params': self.net.weight, 'weight_decay': self.wd},
            {'params': self.net.bias}], lr=self.lr)
  • Exempting the bias: The optimizer decays the weights while leaving the bias unpenalized.

Matching Hyperparameters When Framework MSE Omits 1/2

Concise Training Verification

Because framework MSE omits the \frac{1}{2} factor on the data loss, its data gradient is doubled (2\nabla L), whereas optimizer-level weight decay adds wd \cdot\,\mathbf{w} directly to the gradient without going through the loss:

validation loss 1.785, norm of w 1.17
  • Halve lr, double wd: To preserve both the data step -\eta \nabla L and the per-step multiplicative decay factor (1 - \eta\lambda) = 1 - 0.05 \times \frac{1}{3} = 1 - \frac{1}{60}, we set lr = 0.025 (\eta/2) and wd = 2 * lambd (2/3).
  • Identical solution: The concise run recovers the exact same weight norm \|\hat{\mathbf{w}}\|_2 \approx 1.2 and validation accuracy.

Concept Check: Priors, Shrinkage & Adaptive Decay

Check Your Understanding

Work out these three questions:

  1. Cost of shrinking the truth: In our 200-feature benchmark (\|\mathbf{w}^*\|_2^2 = 2.0, expected validation loss \frac{1}{2}\|\mathbf{w} - \mathbf{w}^*\|_2^2 + 0.5), what validation loss does \mathbf{w} = 0.8\,\mathbf{w}^* incur?
  2. Effective parameters at \lambda = \mu_j: A 10-feature design matrix has eigenvalues \mu = 2.0 (5\times), 0.5 (3\times), and 0 (2\times). What is \operatorname{df}(\lambda) at \lambda = 0.5?
  3. Decoupled weight decay (AdamW vs. \ell_2 penalty): If an adaptive optimizer preconditions each coordinate’s gradient by a_j > 0, compare the decoupled update w_j \leftarrow (1 - \eta\lambda)w_j - \eta a_j \partial_{w_j} L against the coupled update w_j \leftarrow w_j - \eta a_j (\partial_{w_j} L + \lambda w_j). Which one decays all weights at the same rate regardless of a_j?

Answers:

  1. Shrinking \mathbf{w}^* by 20\% yields \frac{1}{2}\|(0.8 - 1)\mathbf{w}^*\|_2^2 + 0.5 = \frac{1}{2}(0.04)(2.0) + 0.5 = 0.54: only 0.04 above the oracle floor 0.50, whereas unregularized noise-fitting cost > 0.70.
  2. \operatorname{df}(0.5) = 5 \cdot \frac{2.0}{2.0 + 0.5} + 3 \cdot \frac{0.5}{0.5 + 0.5} + 2 \cdot \frac{0}{0 + 0.5} = 5(0.8) + 3(0.5) + 0 = 5.5 effective parameters out of 10.
  3. The decoupled update (AdamW) shrinks every weight by the uniform factor (1 - \eta\lambda); the coupled update shrinks coordinate j by (1 - \eta a_j \lambda), under-decaying coordinates with large historical gradients (a_j \ll 1).

Summary & Key Takeaways

Summary

Perspective on Weight Decay Mathematical Formulation Key Insight / Mechanism
Penalized Optimization \min_{\mathbf{w}, b} L(\mathbf{w}, b) + \frac{\lambda}{2}\|\mathbf{w}\|_2^2 Bounds Lipschitz slope \|\mathbf{w}\|_2; bias b is never penalized; features must be standardized
SGD Multiplicative Step \mathbf{w} \leftarrow (1 - \eta\lambda)\mathbf{w} - \eta \nabla_{\mathbf{w}} L_{\mathcal{B}} Shrinks \mathbf{w} toward \mathbf{0} by factor 1 - \eta\lambda every step before applying data gradient
Constraint Geometry (\ell_2 vs. \ell_1) Smooth sphere \|\mathbf{w}\|_2 \leq r vs. diamond \|\mathbf{w}\|_1 \leq r \ell_2 ridge shares weight across correlated features (1,1); \ell_1 lasso hits axis corners (sparsity)
Bayesian MAP Prior w_j \sim \mathcal{N}(0, \tau^2),\, \epsilon \sim \mathcal{N}(0, \sigma^2) \Rightarrow \lambda = \frac{\sigma^2}{n\tau^2} Optimal penalty scales with noise-to-signal ratio \sigma^2/\tau^2 and decays as 1/n
Spectral Shrinkage \mathbf{v}_j^\top\hat{\mathbf{w}}_\lambda = \frac{\mu_j}{\mu_j + \lambda}(\mathbf{v}_j^\top\hat{\mathbf{w}}_0), \operatorname{df}(\lambda) = \sum_j \frac{\mu_j}{\mu_j+\lambda} Preserves well-determined directions (\mu_j \gg \lambda) and quashes ill-conditioned noise (\mu_j \ll \lambda)