Dropout

Dive into Deep Learning · §4.6

Dropout: Regularization via Multiplicative Hidden Noise
co-adaptation · inverted dropout 1/(1-p) · train vs. test semantics · slowing noisy-label memorization

Why Inject Random Noise Into Hidden Units?

Motivation & Co-Adaptation

  • Three complementary regularizers: Weight decay penalizes large weight norms \|\mathbf{W}\|_{\textrm{F}}^2; early stopping halts before late-stage noise memorization; dropout (Srivastava et al., 2014) randomly zeroes out each hidden unit with probability p on every training step.
  • Preventing hidden-unit co-adaptation: When units are always present together, groups of neurons can conspire to fix isolated training errors. Random masking forces every unit to extract features useful alongside random subsets of partners.

Warm-Up: Input Noise Equals L2 Weight Decay

Noise as Regularization

\mathbb{E}_{\boldsymbol{\epsilon}}\!\left[\bigl(\mathbf{w}^\top(\mathbf{x} + \boldsymbol{\epsilon}) + b - y\bigr)^2\right] = (\mathbf{w}^\top\mathbf{x} + b - y)^2 + s^2\|\mathbf{w}\|_2^2

  • Bishop’s equivalence (1995): Perturbing inputs by zero-mean noise \boldsymbol{\epsilon} with variance s^2 has zero cross-term (\mathbb{E}[\boldsymbol{\epsilon}] = \mathbf{0}) and adds an exact \ell_2 ridge penalty s^2\|\mathbf{w}\|_2^2.
  • From additive to multiplicative noise: Dropout extends noise injection to binary multiplicative masking across every hidden layer.

Inverted Dropout: Masking and 1/(1 − p) Rescaling

Mathematical Formulation

h_j' = \frac{\xi_j\, h_j}{1 - p}, \qquad \xi_j \sim \mathrm{Bernoulli}(1 - p)

  • Unbiased training expectation (\mathbb{E}[h_j'] = h_j): Dividing surviving units by 1 - p during training ensures \mathbb{E}[h_j'] = p \cdot 0 + (1 - p)\frac{h_j}{1 - p} = h_j.
  • Zero test-time overhead: At inference time we simply disable dropout (h_j' = h_j) with no weight rescaling needed.

Variance Inflation Under Inverted Dropout

Second-Moment Scaling

\mathbb{E}\bigl[(h_j')^2\bigr] = \frac{h_j^2}{1 - p}, \qquad \mathrm{Var}[h_j'] = \frac{p}{1 - p}\,h_j^2

  • Multiplicative noise scale: At p = 0.5, survivors double (2\times) and the injected standard deviation equals 100\% of |h_j|; at p = 0.8, survivors scale by 5\times (\textrm{std} = 2|h_j|).
  • Second-moment shift: Because training inflates \mathbb{E}[(h_j')^2] by \frac{1}{1-p}, placing dropout directly before BatchNorm shifts its running variance between training and inference.

Adaptive Ridge Penalty vs. Nonlinear Test-Time Mismatch

Linear Exactness vs. ReLU Approximation

How does the deterministic test-time network (h_j' = h_j) relate to the 2^h random subnetworks sampled during training?

1. Exact adaptive ridge on a linear layer:

\mathbb{E}_{\boldsymbol{\xi}}\!\left[(\mathbf{w}^\top\mathbf{x}' + b - y)^2\right] = (\mathbf{w}^\top\mathbf{x} + b - y)^2 + \frac{p}{1 - p}\sum_{j=1}^d x_j^2 w_j^2

  • Penalizes each weight w_j^2 in proportion to its feature energy x_j^2 (frequent features are regularized more strongly).

2. Nonlinear expectation mismatch (\mathbb{E}[\mathrm{ReLU}(z)] \neq \mathrm{ReLU}(\mathbb{E}[z])):

(h_1', h_2') at p = 0.5 (0, 0) (2, 0) (0, 2) (2, 2)
Pre-activation z = h_1' - h_2' 0 +2 -2 0
\mathrm{ReLU}(z) = \max(z, 0) 0 2 0 0
  • Average of thinned ReLUs is \mathbb{E}[\mathrm{ReLU}(z)] = 0.5, whereas deterministic test network gives \mathrm{ReLU}(\mathbb{E}[z]) = \mathrm{ReLU}(0) = 0.

Implementing Inverted Dropout in Three Lines of Code

From-Scratch Layer

Our dropout_layer(X, dropout) draws uniform random numbers in [0, 1), keeps entries \ge p, and rescales by 1 / (1 - p):

def dropout_layer(X, dropout):
    assert 0 <= dropout <= 1
    if dropout == 1: return torch.zeros_like(X)
    mask = torch.rand_like(X) >= dropout
    return mask.to(X.dtype) * X / (1.0 - dropout)
p = 0: tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])
p = 0.5: tensor([[ 0.,  2.,  4.,  6.,  8., 10., 12., 14.],
        [ 0., 18.,  0., 22., 24., 26.,  0., 30.]])
p = 1: tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0., 0.]])
mean 1.000, variance 0.250

Where Dropout Sits in a Multi-Layer MLP

Architecture & Mode Switching

We insert dropout immediately after each hidden layer’s ReLU activation—active only during training and bypassed during validation/inference:

  • Two-hidden-layer Fashion-MNIST MLP: 784 \to 256 \to 256 \to 10 (269{,}322 parameters, He-initialized).
  • Layerwise dropout schedule: Lower dropout near the input (dropout_1 = 0.2) to preserve raw feature signal; stronger dropout deeper (dropout_2 = 0.5) where co-adaptation risk is highest.
  • Backward pass automatically masked: Because h_j' = \frac{\xi_j}{1 - p}h_j, autograd multiplies gradients through dropped units by 0 and surviving units by \frac{1}{1 - p}.

Defining and Training DropoutMLPScratch

From-Scratch Model

In DropoutMLPScratch, we guard each dropout_layer call with the framework’s training-mode flag:

class DropoutMLPScratch(d2l.Classifier):
    def __init__(self, num_outputs, num_hiddens_1, num_hiddens_2,
                 dropout_1, dropout_2, lr, num_inputs=784):
        super().__init__()
        self.save_hyperparameters()
        he = lambda n_in, n_out: nn.Parameter(  # Variance 2 / n_in
            d2l.normal(0, (2 / n_in) ** 0.5, (n_in, n_out)))
        self.W1 = he(num_inputs, num_hiddens_1)
        self.W2 = he(num_hiddens_1, num_hiddens_2)
        self.W3 = he(num_hiddens_2, num_outputs)
        self.b1 = nn.Parameter(d2l.zeros(num_hiddens_1))
        self.b2 = nn.Parameter(d2l.zeros(num_hiddens_2))
        self.b3 = nn.Parameter(d2l.zeros(num_outputs))

    def forward(self, X):
        X = X.reshape(-1, self.num_inputs)
        H1 = torch.relu(X @ self.W1 + self.b1)
        if self.training:
            H1 = dropout_layer(H1, self.dropout_1)
        H2 = torch.relu(H1 @ self.W2 + self.b2)
        if self.training:
            H2 = dropout_layer(H2, self.dropout_2)
        return H2 @ self.W3 + self.b3

20-Epoch Training Curve on Full Fashion-MNIST

Full-Dataset Benchmark

Training DropoutMLPScratch for 20 epochs on all 60{,}000 images reaches \sim 87\% validation accuracy:

  • Why training loss sits above validation loss early on: train_loss is evaluated on noisy, thinned networks (p_1 = 0.2, p_2 = 0.5), whereas val_loss uses the clean unmasked ensemble approximation.
  • Little overfitting on 60{,}000 clean images: Over 20 epochs, even an unregularized MLP barely overfits the full dataset—to see dropout’s true power, we test under label noise next.

Concise Implementation with Framework Dropout Layers

High-Level API

Framework Sequential containers interleave Dropout(p) modules after each ReLU, automatically toggling masks between train and eval modes inside Trainer:

class DropoutMLP(d2l.Classifier):
    def __init__(self, num_outputs, num_hiddens_1, num_hiddens_2,
                 dropout_1, dropout_2, lr):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nn.Flatten(), nn.LazyLinear(num_hiddens_1), nn.ReLU(),
            nn.Dropout(dropout_1), nn.LazyLinear(num_hiddens_2), nn.ReLU(),
            nn.Dropout(dropout_2), nn.LazyLinear(num_outputs))

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

Combatting Memorization Under 40% Label Corruption

Label-Noise Stress Test

On the 1{,}000-image benchmark with 40\% of labels redrawn (\sim 36\% wrong), we train DropoutMLP for 200 epochs with p = 0 vs. p = 0.5:

  • No dropout (p = 0, blue): Memorizes 100\% of the wrong labels by epoch 100 (C0--), dragging validation accuracy (C0-) down by \sim 10 points from its early peak.
  • With dropout (p = 0.5, orange): Slows wrong-label memorization (C1--, 70–85\% reproduced at epoch 200 and still rising) and finishes 3 to 6 percentage points higher in validation accuracy (C1-).

dropout 0: wrong labels reproduced 1.00, validation accuracy over the last 10 epochs 0.595
dropout 0.5: wrong labels reproduced 0.80, validation accuracy over the last 10 epochs 0.654

Three Complementary Interpretations of Dropout

Theoretical Perspectives

  • Adaptive noise regularization: Injects multiplicative variance \mathrm{Var}[h_j'] = \frac{p}{1-p}h_j^2, penalizing high-energy feature weights \propto \frac{p}{1-p}x_j^2 w_j^2.
  • Anti-co-adaptation (Hinton et al.): Any pair of units co-occurs with probability (1 - p)^2 (25\% at p = 0.5), breaking fragile multi-unit conspiracies on noisy labels.
  • Implicit subnetwork ensemble: Shares weights across 2^h thinned subnetworks (2^{512} \approx 10^{154} masks in our 2-layer MLP).

When to Use Dropout—and When to Avoid It

Modern Engineering Guidelines

  • Dense layers on small/noisy data (p \in [0.2, 0.5]): High p/n ratio across many epochs creates strong co-adaptation risk.
  • Multi-epoch Transformers (p \approx 0.1) vs. single-epoch LLMs (p = 0.0): Single-pass pretraining over trillions of tokens sees fresh data every step, so epoch memorization cannot build up.
  • Avoid directly before BatchNorm (p = 0.0): Training second-moment inflation \frac{1}{1-p} causes a train/test variance shift in BatchNorm’s running statistics (Li et al., 2019).

Concept Check: Inverted Dropout, Partners & Variance

Check

Test your command of dropout mathematics and systems behavior:

  1. Extreme dropout (p = 0.8): If a hidden unit has activation h_j = 1.0 and we apply inverted dropout with p = 0.8, what value does a surviving unit take, and what are \mathbb{E}[h_j'] and \mathrm{Var}[h_j']?
  2. Pairwise co-adaptation probability: In a 256-unit hidden layer with p = 0.5, how many units survive on average per example, and on what fraction of training steps are three specific partner units (j_1, j_2, j_3) all active together?
  3. Forgetting to turn off dropout at test time: What symptoms appear if you accidentally leave the model in training mode during validation?

Answers:

  1. At p = 0.8: Survivors are scaled to 1 / (1 - 0.8) = 5.0 (occurring 20\% of the time). The mean is \mathbb{E}[h_j'] = 0.2 \times 5.0 = 1.0, and the variance is \mathrm{Var}[h_j'] = \frac{0.8}{0.2}(1.0)^2 = 4.0 (standard deviation 2.0 = 2|h_j|).
  2. Partner survival: On average 256 \times 0.5 = 128 units survive, and any triple (j_1, j_2, j_3) co-occurs on only (1 - 0.5)^3 = 1/8 = 12.5\% of steps.
  3. Test-time bug: Validation predictions become non-deterministic across calls and suffer lower single-pass accuracy (unless averaged across T \ge 20 Monte Carlo passes).

Summary: Dropout Regularization

Key Takeaways

  • Unbiased inverted mask: h_j' = \frac{\xi_j h_j}{1 - p} keeps \mathbb{E}[h_j'] = h_j during training so the test-time network runs completely unscaled (h_j' = h_j).
  • Adaptive regularization: Injects multiplicative variance \mathrm{Var}[h_j'] = \frac{p}{1-p}h_j^2, acting as an energy-weighted \ell_2 penalty on linear layers.
  • Empirical impact: On 40\%-corrupted Fashion-MNIST (n = 1{,}000), p = 0.5 slows wrong-label memorization and lifts validation accuracy by 3–6 percentage points.