TExcelTAD

Weight Decay and Dropout

A model with more parameters than it has training examples can memorise the training set: training loss near zero, validation loss bad. Two cheap tools fight this inside the training loop itself. Weight decay pulls every weight a little towards zero at each step, so the model prefers small, smooth solutions. Dropout switches off a random part of the network at each step, so no unit can rely on one particular partner. Both are switched on for training only, and both are a hyperparameter you tune on validation data. The broader picture of overfitting is in Underfitting, Overfitting and Generalisation.

Weight decay and the L2 penalty

Add a penalty on the squared size of the weights to the loss:

Lreg(w)=L(w)+λ2∥w∥2.L_{\text{reg}}(\mathbf{w}) = L(\mathbf{w}) + \frac{\lambda}{2} \lVert \mathbf{w} \rVert^2 .

Its gradient adds λw\lambda \mathbf{w}, so one gradient-descent step becomes

w←w−η(∇L(w)+λw)=(1−ηλ) w−η∇L(w).\mathbf{w} \leftarrow \mathbf{w} - \eta \big( \nabla L(\mathbf{w}) + \lambda \mathbf{w} \big) = (1 - \eta\lambda)\, \mathbf{w} - \eta \nabla L(\mathbf{w}) .

Read the right-hand side: first shrink every weight by the factor 1−ηλ1 - \eta\lambda, then take the usual step. That shrinking is why it is called weight decay. For plain (stochastic) gradient descent the L2 penalty and weight decay are the same thing. It is ridge regression's penalty applied to any model (Ridge, Lasso and Elastic Net); the Bayesian view, a Gaussian prior on the weights, is in MAP Estimation and Regularization, and the deep-learning view in Regularization.

A degree-9 polynomial fitted to 15 noisy points of sin⁡πx\sin \pi x by gradient descent, with the decay written exactly as the shrink-then-step update above (validation on 200 fresh points):

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
def make(n):
    x = rng.uniform(-1, 1, n)
    return x, np.sin(np.pi * x) + rng.normal(0, 0.2, n)
x_tr, y_tr = make(15)
x_val, y_val = make(200)
feats = lambda x: np.vander(x, 10, increasing=True)     # 1, x, ..., x^9
F_tr, F_val = feats(x_tr), feats(x_val)

def train(wd, lr=0.3, steps=20000):
    w = np.zeros(10)
    for _ in range(steps):
        g = F_tr.T @ (F_tr @ w - y_tr) / len(y_tr)       # gradient of half MSE
        w = (1 - lr * wd) * w - lr * g                  # weight decay: shrink, then step
    mse = lambda F, y: np.mean((F @ w - y) ** 2)
    return mse(F_tr, y_tr), mse(F_val, y_val), np.linalg.norm(w)

for wd in [0.0, 1e-4, 1e-3, 1e-2, 1e-1]:
    tr, va, norm = train(wd)
    print(f"weight decay {wd:6.4f}  train MSE {tr:.4f}  val MSE {va:.4f}  |w| {norm:6.2f}")
weight decay 0.0000  train MSE 0.0139  val MSE 0.0818  |w|   4.99
weight decay 0.0001  train MSE 0.0141  val MSE 0.0756  |w|   4.75
weight decay 0.0010  train MSE 0.0186  val MSE 0.0634  |w|   3.57
weight decay 0.0100  train MSE 0.0475  val MSE 0.1097  |w|   1.90
weight decay 0.1000  train MSE 0.1398  val MSE 0.3157  |w|   0.74

The pattern is the classic one. As λ\lambda grows the weights get smaller and the training error rises steadily. The validation error first falls (0.0818 to 0.0634 at λ=10−3\lambda = 10^{-3}) and then rises again when the penalty starts to flatten the sine wave itself (underfitting). The best λ\lambda is found by a validation sweep on a log grid, like any hyperparameter (Grid and Random Search).

With Adam, L2 and weight decay are not the same

Adaptive optimizers divide each gradient coordinate by a running estimate of its size. If the penalty is added to the gradient (L2), the term λw\lambda \mathbf{w} is divided too, so weights with large gradients are barely decayed and weights with small gradients are decayed hard. Decoupled weight decay applies the shrink (1−ηλ) w(1 - \eta\lambda)\,\mathbf{w} separately, outside the adaptive scaling, so every weight decays at the same relative rate. That is the difference between Adam(weight_decay=…) (L2) and AdamW in PyTorch, and it is why AdamW is the default for transformers; see Adam and AdamW. Usual practice: do not decay biases and normalisation parameters, only weight matrices.

Dropout

During training, dropout sets each activation of a layer to zero with probability pp, a fresh random choice at every step:

h~j=mj1−p hj,mj∼Bernoulli(1−p).\tilde{h}_j = \frac{m_j}{1 - p} \, h_j, \qquad m_j \sim \text{Bernoulli}(1 - p) .

Dividing by 1−p1 - p (inverted dropout) keeps the expected value unchanged, E[h~j]=hj\mathbb{E}[\tilde{h}_j] = h_j, so at evaluation time the layer is simply the identity: no mask, no rescaling. Each step thus trains a different random sub-network, and the full network at test time behaves roughly like an average of all of them. Units cannot co-adapt (rely on a specific other unit being present), which makes the learned features more robust.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)

def dropout(h, p, training):
    if not training or p == 0:
        return h                                        # eval mode: identity
    mask = rng.random(h.shape) >= p                     # keep each unit with prob 1 - p
    return h * mask / (1 - p)                           # inverted dropout: rescale now

h = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
print("train pass 1:", dropout(h, 0.5, True))
print("train pass 2:", dropout(h, 0.5, True))
print("eval pass:   ", dropout(h, 0.5, False))
avg = np.mean([dropout(h, 0.5, True) for _ in range(20000)], axis=0)
print("mean of 20000 train passes:", avg.round(2))
train pass 1: [ 2.  0.  0.  0. 10. 12.]
train pass 2: [ 2.  4.  6.  8. 10.  0.]
eval pass:    [1. 2. 3. 4. 5. 6.]
mean of 20000 train passes: [1.01 1.99 2.97 4.03 4.96 5.96]

With p=0.5p = 0.5 the kept units are doubled, and on average the output equals the input.

Dropout in a small network

A one-hidden-layer network with 200 ReLU units trained on only 40 points of the noisy two-moons data, full-batch gradient descent for 3000 epochs, evaluated (dropout off) on 1020 other points. Backpropagation multiplies by the same mask, because a dropped unit contributed nothing:

python · try it yourself
import numpy as np
from sklearn.datasets import make_moons

X, y = make_moons(n_samples=1060, noise=0.35, random_state=0)
X_tr, y_tr, X_val, y_val = X[:40], y[:40], X[40:], y[40:]   # tiny training set: easy to overfit

def train(p, epochs=3000, lr=0.5, H=200, seed=0):
    rng = np.random.default_rng(seed)
    W1 = rng.normal(0, np.sqrt(2 / 2), (2, H)); b1 = np.zeros(H)
    W2 = rng.normal(0, np.sqrt(1 / H), H); b2 = 0.0
    for _ in range(epochs):
        a = np.maximum(0, X_tr @ W1 + b1)                    # ReLU hidden layer
        mask = (rng.random(a.shape) >= p) / (1 - p)           # inverted dropout (training only)
        a_d = a * mask
        prob = 1 / (1 + np.exp(-(a_d @ W2 + b2)))
        d = (prob - y_tr) / len(y_tr)                         # dLoss/dlogit
        gW2, gb2 = a_d.T @ d, d.sum()
        da = np.outer(d, W2) * mask * (a > 0)
        gW1, gb1 = X_tr.T @ da, da.sum(0)
        W1 -= lr * gW1; b1 -= lr * gb1; W2 -= lr * gW2; b2 -= lr * gb2
    def evaluate(X, y):                                      # eval mode: no dropout
        prob = 1 / (1 + np.exp(-(np.maximum(0, X @ W1 + b1) @ W2 + b2)))
        prob = np.clip(prob, 1e-12, 1 - 1e-12)
        return np.mean((prob > 0.5) == y), -np.mean(y * np.log(prob) + (1 - y) * np.log(1 - prob))
    return evaluate(X_tr, y_tr), evaluate(X_val, y_val)

for p in [0.0, 0.3, 0.6]:
    (tr_acc, tr_loss), (va_acc, va_loss) = train(p)
    print(f"dropout p={p}  train acc {tr_acc:.3f} loss {tr_loss:.3f}  |  val acc {va_acc:.3f} loss {va_loss:.3f}")
dropout p=0.0  train acc 1.000 loss 0.017  |  val acc 0.869 loss 0.696
dropout p=0.3  train acc 1.000 loss 0.023  |  val acc 0.881 loss 0.560
dropout p=0.6  train acc 1.000 loss 0.035  |  val acc 0.889 loss 0.581

All three still fit the 40 training points perfectly, but dropout lowers the validation log-loss from 0.696 to about 0.56 to 0.58 and gains 1 to 2 points of accuracy. The effect is modest here: it is one seed on a two-dimensional toy problem, and the network is still far too big for 40 points. In large networks dropout rates of 0.1 to 0.5 on fully connected layers are common; convolutional layers use it less, and many modern architectures rely on weight decay, data augmentation and normalisation instead.

Train mode and eval mode

Dropout (and batch normalisation) behave differently in training and evaluation, so frameworks keep a mode flag. In PyTorch model.train() turns dropout on and model.eval() turns it off; you switch before validating and back before the next epoch. Forgetting model.eval() gives noisy, slightly worse validation scores that change from run to run; forgetting model.train() afterwards silently trains without dropout. The flag is the training argument of the NumPy function above.

Pitfalls

  • Decaying everything. Weight decay on biases and normalisation scales rarely helps and can hurt; exclude them.
  • Using Adam(weight_decay=…) and calling it AdamW. In PyTorch that is the coupled L2 version; use AdamW.
  • Tuning λ\lambda together with a changing learning rate. With decoupled decay the per-step shrink is ηλ\eta\lambda, so the effective decay changes when the learning rate or schedule changes.
  • Dropout at evaluation time (wrong mode), or a non-inverted implementation that forgets to rescale.
  • Dropout on a model that underfits. It is a regulariser; if training loss is still high, it makes things worse.

Practice

  1. With η=0.1\eta = 0.1 and λ=0.01\lambda = 0.01, by what factor does weight decay shrink every weight per step, before the gradient step? After 1000 steps with a zero gradient, what fraction of a weight remains?
Answer

1−ηλ=0.9991 - \eta\lambda = 0.999 per step, and 0.9991000≈0.3680.999^{1000} \approx 0.368, about e−1e^{-1}.

  1. A layer has activations h=(2,4)h = (2, 4) and dropout p=0.25p = 0.25. List the possible training outputs with their probabilities and check that the expected value is hh.
Answer

A kept unit is multiplied by 1/0.75=4/31/0.75 = 4/3. Outputs: (8/3,16/3)(8/3, 16/3) with probability 0.56250.5625, (8/3,0)(8/3, 0) and (0,16/3)(0, 16/3) with 0.18750.1875 each, (0,0)(0, 0) with 0.06250.0625. Expected first coordinate: 0.75⋅8/3=20.75 \cdot 8/3 = 2; second: 0.75⋅16/3=40.75 \cdot 16/3 = 4.

Test yourself

For plain gradient descent, adding λ2∥w∥2\frac{\lambda}{2}\lVert \mathbf{w} \rVert^2 to the loss is equivalent to…

  1. dividing the learning rate by λ\lambda
  2. multiplying the weights by 1−ηλ1 - \eta\lambda before each gradient step
  3. adding noise to the gradient
  4. dropping out a fraction λ\lambda of the weights

Why does inverted dropout divide the kept activations by 1−p1 - p during training?

  1. To make training faster
  2. So the expected activation is unchanged and nothing needs rescaling at evaluation time
  3. To avoid division by zero
  4. To increase the dropout rate

In the polynomial example, what happened as the weight decay grew from 10−310^{-3} to 10−110^{-1}?

  1. Both errors fell
  2. Training error rose and validation error rose too: the model began to underfit
  3. Validation error fell to zero
  4. Nothing changed

Why is AdamW preferred over Adam with an L2 penalty?

  1. It uses less memory
  2. Its decay is applied outside the adaptive scaling, so every weight decays at the same relative rate
  3. It has no learning rate
  4. It does not need gradients