Modern Training Recipes for Convnets

Dive into Deep Learning · §7.6

Modern Training Recipes for Convnets
AdamW · cosine warmup · label smoothing · Mixup & CutMix · stochastic depth · EMA weight averaging

Why Reported Architecture Gains Are Often Recipe Gains

Motivation & Benchmark Confounding

  • ResNet-50 Strikes Back (Wightman et al., 2021): Upgrading the training recipe lifts an unchanged 2015 ResNet-50 from 76.1\% to 80.4\% (+4.3 points) on ImageNet, using LAMB, a BCE loss, RandAugment/Mixup/CutMix, and 600 epochs.
  • Scientific rule: Always compare architectures under matched training recipes; a 1–2 point gain over an un-retrained baseline confounds recipe with architecture.

Evolution of Vision Training Recipes (2015 vs. 2022)

The Modern Recipe Menu

  • Data & forward pass: RandAugment + Mixup + CutMix + Stochastic Depth (drop_path).
  • Objective & optimizer: Label smoothing (\epsilon = 0.1) + AdamW or LAMB (decoupled weight decay) + linear warmup & half-cosine decay over 300–600 epochs.
  • Checkpoint: Often a shadow exponential moving average (EMA) \bar{\boldsymbol{\theta}}_T; the 80.4\% ResNet-50 run used none.

Decoupled Weight Decay in AdamW vs. Coupled SGD

Optimizer Mechanics

\boldsymbol{\theta}_{t+1} = (1 - \eta_t \lambda)\,\boldsymbol{\theta}_t - \eta_t \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}

  • Why L2 fails in Adam: Dividing \lambda \boldsymbol{\theta}_t by \sqrt{\hat{\mathbf{v}}_t} shrinks high-gradient weights less.
  • Comparing across optimizers: Compare per-step fractional decay \eta_0 \lambda (0.002 \times 0.05 = 10^{-4} for AdamW).

Label Smoothing: Bounding Optimal Logit Margins

Loss Regularization

Under standard one-hot cross-entropy (-\log p_y), driving the loss toward zero forces the true class logit z_y \to +\infty, producing overconfident, poorly calibrated predictions:

  • Softened target distribution: Label smoothing (Szegedy et al., 2016) places probability 1 - \epsilon on the true class y and distributes \epsilon uniformly across all K classes (\epsilon / K each): l_\epsilon(\mathbf{p}, y) = -(1 - \epsilon)\log p_y - \frac{\epsilon}{K} \sum_{k=1}^K \log p_k
  • Finite optimal logit gap: Minimized when p_y^* = 1 - \epsilon + \epsilon/K and p_k^* = \epsilon/K (k \neq y), which occurs at the exact finite logit margin z_y^* - z_k^* = \log\bigl(1 + \frac{K(1-\epsilon)}{\epsilon}\bigr) (e.g., \approx 3.33 for K=3, \epsilon=0.1).
  • Penalizing overconfidence: On logits (10, 0, 0), \epsilon=0.1 raises loss from 0.0001 to 0.67, pulling extreme logits back:
epsilon=0.0: loss=0.0001
epsilon=0.1: loss=0.6668

Step Decay vs. Cosine Decay with Linear Warmup

Learning-Rate Schedules

Plotting our 30-epoch step schedule against our 45-epoch cosine warmup schedule illustrates why modern recipes abandoned discrete step drops:

  • Warmup (0 \le t < t_{\textrm{w}}): Linearly ramps \eta_t = \eta_0 \cdot (t / t_{\textrm{w}}), letting BatchNorm running stats and AdamW second moments \hat{\mathbf{v}}_t equilibrate before full steps occur.
  • Half-cosine decay (t_{\textrm{w}} \le t \le T): \eta_t = \frac{\eta_0}{2}\left(1 + \cos\frac{\pi(t - t_{\textrm{w}})}{T - t_{\textrm{w}}}\right) Eliminates drop-epoch tuning and anneals smoothly to 0 at step T.

Mixup and CutMix: Blending Examples and Labels

Data Augmentation

def mixup(X, y, alpha):
    """Mix a minibatch with a shuffled copy; return both label sets."""
    lam = random.betavariate(alpha, alpha)
    perm = torch.randperm(X.shape[0], device=X.device)
    return lam * X + (1 - lam) * X[perm], y, y[perm], lam
  • Convex combinations (\lambda \sim \mathrm{Beta}(\alpha, \alpha)): Mixup blends whole images; CutMix pastes a rectangular patch of area 1-\lambda and mixes labels by area.

Visualizing Mixup and Contrasting with CutMix

Augmentation Geometry

During training, \alpha = 0.2 concentrates \lambda near 0 and 1; below we plot \alpha = 2.0 (\lambda \approx 0.5) so the superposed garment mixtures are clearly visible:

  • Linear decision boundaries: Forces network predictions to transition linearly between classes rather than oscillating sharply outside the training manifold.
  • CutMix (Yun et al., 2019): Because global alpha-blending creates ghostly double exposures, CutMix pastes a rectangular patch of area fraction 1 - \lambda from \mathbf{x}_j onto \mathbf{x}_i and mixes labels by the exact patch area, preserving local pixel statistics.

lambda = 0.81

Stochastic Depth: Dropping Whole Residual Branches

Structural Regularization

\mathbf{x}_{\ell+1} = \mathbf{x}_\ell + \frac{b}{1 - p_\ell}\,f(\mathbf{x}_\ell), \qquad b \sim \mathrm{Bernoulli}(1 - p_\ell)

  • Implicit ensemble of depths: Drops entire residual branches per example with linear schedule p_\ell = (\ell/L)p_{\max}.
  • Expectation preservation: Scaling by 1/(1-p_\ell) keeps \mathbb{E}[\mathbf{x}_{\ell+1}] = \mathbf{x}_\ell + f(\mathbf{x}_\ell) so b \equiv 1 at eval.

Implementing and Verifying drop_path

Stochastic Depth Code

def drop_path(Y, p, training):
    """Zero each example of Y with probability p, rescale the rest."""
    if not training or p == 0:
        return Y
    shape = (Y.shape[0],) + (1,) * (Y.ndim - 1)  # One draw per example
    keep = torch.rand(shape, device=Y.device) > p
    return Y * keep / (1 - p)

class StochasticResidual(d2l.Residual):
    """A residual block whose branch is dropped with probability p."""
    def __init__(self, num_channels, p):
        super().__init__(num_channels)
        self.p = p

    def forward(self, X):
        Y = self.bn2(self.conv2(F.relu(self.bn1(self.conv1(X)))))
        return F.relu(X + drop_path(Y, self.p, self.training))

blk, X = StochasticResidual(3, p=0.5), torch.randn(1000, 3, 8, 8)
Y = blk(X)  # A module is in training mode until .eval() is called
dropped = (Y == F.relu(X)).flatten(1).all(1).float().mean()
print(f'fraction of examples with a dropped branch: {float(dropped):.3f}')

Implementing and Verifying drop_path (cont.)

Stochastic Depth Code

Sampling one Bernoulli mask per example (shape = (B, 1, 1, 1)) and passing 1,000 inputs through StochasticResidual(p=0.5) confirms that half of the examples bypass the branch and equal \textrm{ReLU}(\mathbf{X}) identically:

fraction of examples with a dropped branch: 0.473

Exponential Moving Average (EMA) of Model Weights

Iterate Averaging

Near convergence, minibatch noise causes SGD/AdamW iterates \boldsymbol{\theta}_t to bounce around the walls of a flat loss valley. Maintaining a non-trainable shadow copy \bar{\boldsymbol{\theta}}_t averages out this oscillation:

  • EMA update after each optimizer step: \bar{\boldsymbol{\theta}}_t \leftarrow \rho\,\bar{\boldsymbol{\theta}}_{t-1} + (1 - \rho)\,\boldsymbol{\theta}_t
  • Effective memory horizon 1/(1-\rho): Iterate \boldsymbol{\theta}_{t-k} carries weight (1-\rho)\rho^k.
  • Pitfall (Horizon vs. Run Length): At \rho = 0.99 (horizon 100 steps), the shadow trajectory lags 20\% below a 50-step ramp even at step 200. Always choose 1/(1-\rho) \ll T (e.g., \rho = 0.9999 only for >50{,}000-step runs).

Controlled Experiment: One ResNet-18 Under Two Recipes

Head-to-Head Comparison

  • Same 11.2M ResNet-18 on FashionMNIST10k: Compares ClassicRecipe (30 ep, SGD \eta_0=0.05, step drops, 1-hot CE) against ModernRecipe (45 ep, AdamW \eta_0=0.002, cosine warmup, Mixup 0.2, label smoothing 0.1).
  • Result: ModernRecipe wins every paired run by +0.5 to +1.5 percentage points (90.5\text{--}91.0\% vs. 89.0\text{--}90.5\%).

Implementing Classic vs. Modern Training Steps

Recipe Implementation

ClassicRecipe and ModernRecipe share ResNet18, differing only in two methods:

class ClassicRecipe(ResNet18):
    """Recipe A: SGD with momentum, weight decay, warmup, step decay."""
    def configure_optimizers(self):
        optim = torch.optim.SGD(self.parameters(), lr=self.lr, momentum=0.9,
                                weight_decay=5e-4)
        warmup = 2 * self.num_steps // 30  # Two of the 30 epochs
        return optim, torch.optim.lr_scheduler.LambdaLR(
            optim, lambda t: step_decay(t, self.num_steps, warmup))

class ModernRecipe(ResNet18):
    """Compact modern recipe: AdamW, warmup and cosine, smoothing, Mixup."""
    def configure_optimizers(self):
        warmup = 3 * self.num_steps // 45  # Three of the 45 epochs
        optim = torch.optim.AdamW(self.parameters(), lr=self.lr,
                                  weight_decay=0.05)
        return optim, torch.optim.lr_scheduler.LambdaLR(
            optim, lambda t: d2l.cosine_warmup(t, self.num_steps, warmup))

    def training_step(self, batch):
        X, y_a, y_b, lam = mixup(*batch, alpha=0.2)
        Y_hat = self(X)
        smooth = lambda y: F.cross_entropy(Y_hat, y, label_smoothing=0.1)
        return lam * smooth(y_a) + (1 - lam) * smooth(y_b)

Baseline Trajectory: 30 Epochs of Classic Recipe A

Classic Recipe Training Curve

Under ClassicRecipe (30 epochs, unsmoothed cross-entropy without Mixup), training loss plunges toward zero while validation loss rebounds to 0.4\text{--}0.5 as logits grow overconfident:

0.8958

Diagnostic Pitfall: Never Compare Raw Training Losses

Reading Recipe Curves

Inspecting the training and validation curves of ModernRecipe reveals a diagnostic trap that catches many practitioners:

  • Why train_loss > val_loss under ModernRecipe: train_loss is evaluated on Mixup-blended images with label-smoothed targets (whose theoretical minimum is bounded well above 0), whereas val_loss is plain cross-entropy on clean unmixed validation images.
  • Better calibration: Under ClassicRecipe, training loss hits \approx 0 while overconfident validation loss rebounds to 0.4\text{--}0.5; ModernRecipe keeps validation loss below 0.4.

0.9063

Reading Leaderboards: Ablations & Distribution Shift

Benchmark Methodology

  • 1. Always retune LR on optimizer swap: AdamW (\eta_0 = 0.002) vs. SGD (\eta_0 = 0.05) differ by 25\times.
  • 2. ImageNet-V2 distribution shift (Recht et al., 2019): Drops all models by 11\text{--}14\% while preserving relative model rankings linearly.
  • 3. Downstream transfer: Once ImageNet top-1 nears its multi-label floor, test backbones on COCO detection and segmentation.

Concept Check: Smoothed Logits, EMA & Weight Decay

Concept Check

Test your grasp of modern recipe mechanics with these three calculations:

  1. Optimal logit gap under label smoothing: For K = 10 classes and \epsilon = 0.1, what probability p_y^* does label smoothing assign to the true class, what probability p_k^* to each of the 9 incorrect classes, and what is the optimal logit difference z_y^* - z_k^* = \log(p_y^* / p_k^*)?
  2. EMA horizon vs. epoch count: In our 45-epoch FashionMNIST10k run (79 steps/epoch, T = 3{,}555 total steps), how many epochs does an EMA with \rho = 0.999 average over, and why can that hurt final validation accuracy?
  3. EMA + BatchNorm pitfall: When you swap in EMA shadow weights \bar{\boldsymbol{\theta}} at evaluation time, why can BatchNorm’s running statistics (\hat{\mu}, \hat{\sigma}^2) be slightly mismatched, and how is this fixed?

Answers:

  1. p_y^* = 1 - 0.1 + 0.1/10 = 0.91, and p_k^* = 0.1/10 = 0.01 for each of the 9 other classes. The optimal logit gap is \log(0.91 / 0.01) = \log(91) \approx \mathbf{4.51} (vs. \infty without smoothing).
  2. The effective window is 1/(1 - 0.999) = 1{,}000 steps \approx \mathbf{12.7\text{ epochs}} (over a third of the entire 45-epoch run), pulling the average back toward undertrained early weights.
  3. BatchNorm’s moving_mean and moving_var were accumulated using the live weights \boldsymbol{\theta}_t with \rho_{\text{BN}} = 0.9 (10-step window), not the smoothed weights \bar{\boldsymbol{\theta}}_t. Either maintain EMA shadow copies of BN buffers or run one forward pass over training batches with \bar{\boldsymbol{\theta}} frozen to recompute fresh BN stats.

Summary: Key Takeaways on Modern Training Recipes

Summary

Ingredient Mathematical Formulation Practical Role & Tuning Rule
AdamW \boldsymbol{\theta}_{t+1} = (1 - \eta_t \lambda)\boldsymbol{\theta}_t - \eta_t \hat{\mathbf{m}}_t / (\sqrt{\hat{\mathbf{v}}_t} + \epsilon) Decouples weight shrinkage \eta_t \lambda from adaptive gradient normalization; base LR \sim 25\times smaller than SGD
Cosine Warmup Linear ramp 0 \to \eta_0 over t_{\textrm{w}}, then \frac{\eta_0}{2}(1 + \cos\frac{\pi(t-t_{\textrm{w}})}{T-t_{\textrm{w}}}) Prevents early BN/Adam divergence and eliminates step-drop threshold tuning
Label Smoothing l_\epsilon = -(1-\epsilon)\log p_y - \frac{\epsilon}{K}\sum_k \log p_k Bounds optimal logit gap to \log(1 + K(1-\epsilon)/\epsilon), improving calibration
Mixup / CutMix \tilde{\mathbf{x}} = \lambda \mathbf{x}_i + (1-\lambda)\mathbf{x}_j, \tilde{\mathbf{y}} = \lambda \mathbf{y}_i + (1-\lambda)\mathbf{y}_j Regularizes inter-class paths; requires longer training horizons (300–600 epochs on ImageNet)
Stochastic Depth \mathbf{x} + \frac{b}{1-p}f(\mathbf{x}) with b \sim \mathrm{Bernoulli}(1-p) per example Drops whole residual branches during training; p_\ell ramps linearly from 0 to p_{\max} with depth
Weight EMA \bar{\boldsymbol{\theta}}_t \leftarrow \rho \bar{\boldsymbol{\theta}}_{t-1} + (1-\rho)\boldsymbol{\theta}_t Damps late-training oscillation at zero inference cost; keep horizon 1/(1-\rho) \ll T