Tuning Deep Networks in Practice

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Most of the time lost in deep learning is not spent on clever ideas but on runs that never had a chance: a bug in the data pipeline, a learning rate off by a factor of ten, a comparison between two models that differ in three ways at once. This page condenses the method of the Google Research Deep Learning Tuning Playbook and the practical advice of the Stanford CS231n course notes into a procedure you can follow: make the pipeline trustworthy, choose a sensible starting point, then improve the model through small experiments that each answer one question.

The advice is framework-independent. Examples target Python 3.13, PyTorch 2.15 and TensorFlow 2.21 with Keras 3.15, and were checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with PyTorch 2.15 (CPU) and Optuna on 2026-11-01. The page builds on Training Deep Networks, Optimizers & Learning-Rate Schedules and Generalization, Bias-Variance & Regularization; for the evaluation discipline behind it see Model Evaluation & Validation, and for scikit-learn’s own search classes see Grid, Randomized & Halving Search.

The playbook’s scope and mindset

The playbook targets the supervised and self-supervised learning setting, where you train with a gradient-based optimizer and judge the result on held-out data. It is deliberately about the process, not about numbers: a configuration that is best on one dataset and model size is only a starting point on another. Three ideas run through it.

  • Improve incrementally. Start from a simple configuration that works, then change one thing at a time in rounds, adopting a change only when the evidence supports it. A tuned system is the accumulated result of many small, understood decisions.

  • Aim for insight, not only for a better number. Each round has a goal that answers a question ("does a wider layer help?", "is the model limited by regularisation?"). Experiments that are not designed to answer a question produce numbers you cannot reuse.

  • Spend the compute budget deliberately. Early rounds should favour exploration (many cheap, short runs that reveal which directions matter); late rounds favour exploitation (fewer, longer runs around the best region).

Step 0: make the pipeline trustworthy

Before any tuning, rule out bugs. Tuning a broken pipeline is the most expensive mistake there is, and the symptoms (a loss that does not decrease, a validation score no better than chance) look identical to a bad hyperparameter.

  1. Inspect the data the model actually sees. Print a few batches after augmentation and normalisation, with their labels. Check shapes, dtypes, value ranges, label alignment and that the validation pipeline is deterministic and unaugmented.

  2. Check the initial loss. With \(C\) balanced classes and a sensible initialisation, the first loss of a softmax classifier should be close to \(\ln C\) (about 2.30 for ten classes); a very different value points to a scaling or initialisation bug (see Loss Functions & Information Theory).

  3. Overfit a single small batch. A model with enough capacity must drive the loss on 8 to 32 examples to nearly zero. If it cannot, the problem is a bug, not a hyperparameter: wrong loss, mismatched labels, frozen parameters, zero_grad in the wrong place, a missing activation or a shape broadcast.

  4. Check that every parameter receives a gradient and changes. Parameters with grad is None after backward() are disconnected from the loss.

  5. Establish a baseline. A trivial model (majority class, last value, linear model, gradient boosting) tells you how much the neural network is worth; see Tabular Data: Gradient Boosting vs Deep Learning.

import torch
from torch import nn

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Linear(64, 10))
loss_fn = nn.CrossEntropyLoss()

x = torch.randn(16, 20)
y = torch.randint(0, 10, (16,))

with torch.no_grad():
    print("initial loss:", round(loss_fn(model(x), y).item(), 3), "(ln 10 = 2.303)")

optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
for step in range(200):
    optimizer.zero_grad(set_to_none=True)
    loss = loss_fn(model(x), y)
    loss.backward()
    optimizer.step()

print("loss after overfitting one batch:", round(loss.item(), 4))
missing = [n for n, p in model.named_parameters() if p.grad is None]
print("parameters without gradient:", missing)

Step 1: choose the starting configuration

The playbook recommends picking each of the following to be boring and proven, and only then tuning.

  • Model architecture. Start from an established architecture for your problem type and size, ideally one with a public reference implementation, instead of inventing one. Get something working end to end before making it novel. Convolutional image models are covered in Convolutional Neural Networks, sequence models in RNNs, LSTMs & GRUs and Attention & Transformers, and starting from pre-trained weights in Transfer Learning, Fine-Tuning & Foundation Models.

  • Optimizer. Pick a well-established optimizer for the problem type (SGD with momentum, or Adam/AdamW) and be prepared to tune all of its hyperparameters, not only the learning rate; Adam’s \(\epsilon\), \(\beta_1\) and \(\beta_2\) can matter. See Optimizers & Learning-Rate Schedules.

  • Batch size. The batch size mainly determines training speed and memory, and should not be tuned to improve validation performance. As long as the other hyperparameters (especially learning rate and regularisation) are retuned, any batch size can reach the same quality in principle. Choose the largest size that fits and keeps the hardware busy, with the caveat that returns diminish: beyond a point doubling the batch no longer halves the number of steps needed. Batch normalisation couples the batch size to the statistics it computes, so very small batches change its behaviour (see Training Deep Networks).

  • Initial hyperparameters. Start with settings that are simple and cheap: a modest model, no optional regularisation, a conservative learning rate with warmup, and a training length that finishes quickly.

The reproducibility basics (versions, seeds, data versions) are in Reproducibility & MLOps Basics and Experiment Tracking & MLOps for Training.

Step 2: the improvement loop

Each round of experiments follows the same four steps: choose a goal, design the experiments, learn from them, and decide whether to adopt the change.

flowchart LR A["Pick a goal for this round
one question"] --> B["Design experiments
classify hyperparameters"] B --> C["Run and analyse
curves, plots, seeds"] C --> D{"Evidence strong
enough?"} D -- yes --> E["Adopt the change
update the baseline"] D -- no --> F["Refine the question
or run more seeds"] E --> A F --> B

Scientific, nuisance and fixed hyperparameters

The central idea of the experiment design is to sort hyperparameters by their role in the current question.

  • A scientific hyperparameter is the thing whose effect you want to measure: for example the activation function, the number of layers or whether a regulariser is on.

  • A nuisance hyperparameter must be optimised separately for every value of the scientific one for the comparison to be fair. The learning rate is the classic nuisance hyperparameter: the best rate for model A is not the best rate for model B, so comparing them at one shared rate measures how well the shared rate suits each, not which model is better.

  • A fixed hyperparameter is held constant in this round; the conclusion is valid only under that setting.

A hyperparameter can play different roles in different rounds. The consequence is a rule: never compare two variants of a scientific hyperparameter with the nuisance hyperparameters left at the same untuned value. Tune the nuisance ones (at least the learning rate and, depending on the question, the regularisation strength) for each variant, then compare the best of each.

For a handful of hyperparameters the playbook recommends quasi-random search in the early rounds, because it spreads trials evenly over the space without the exponential cost of a grid and, unlike grid search, tries a new value of every hyperparameter in each trial. Low-discrepancy sequences (Sobol, Halton) do this better than pure random draws, whose clumps leave gaps. Later, when a good region is known and the budget is larger, Bayesian optimisation (for example the TPE and Gaussian-process samplers of Optuna) can help, but it brings its own settings and is no substitute for a well-chosen space. Practical points:

  • Search on the right scale. Learning rate, weight decay and \(\epsilon\) are searched on a logarithmic scale; dropout, momentum and the fraction of data on a linear one (for \(\beta_1\) or \(\beta_2\) search \(1-\beta\) on a log scale).

  • Check the boundaries. If the best trial sits at the edge of the search range, the true optimum may lie outside it; widen the range and repeat. Plot each hyperparameter against the objective and look at the shape.

  • Make the search space match the budget. A trial count in the dozens supports about three or four searched hyperparameters; more dimensions need either many more trials or a staged search.

  • Do not tune what you can fix by reasoning. The batch size, the number of training steps in a compute-bound setting and the model size are usually decided by the budget, not searched blindly.

The following pure-Python example generates a scrambled Halton sequence (a low-discrepancy sequence) and maps it to a log-scaled search space. The function fake_validation_loss stands in for "train and return the validation loss".

import math
import random

def halton(index: int, base: int) -> float:
    """Radical inverse of index in the given base (index starts at 1)."""
    result, f = 0.0, 1.0 / base
    while index > 0:
        result += f * (index % base)
        index //= base
        f /= base
    return result

def scrambled_halton(n: int, bases=(2, 3, 5), seed: int = 0):
    rng = random.Random(seed)
    shifts = [rng.random() for _ in bases]          # random shift per dimension
    for i in range(1, n + 1):
        yield [(halton(i, b) + s) % 1.0 for b, s in zip(bases, shifts)]

def to_trial(u):
    return {
        "lr": 10 ** (-5 + 4 * u[0]),            # 1e-5 .. 1e-1, log scale
        "weight_decay": 10 ** (-6 + 4 * u[1]),  # 1e-6 .. 1e-2, log scale
        "dropout": 0.5 * u[2],                  # 0 .. 0.5, linear
    }

def fake_validation_loss(t):
    return (math.log10(t["lr"]) + 3) ** 2 + 0.2 * (math.log10(t["weight_decay"]) + 4) ** 2 + 2 * (t["dropout"] - 0.2) ** 2

trials = [to_trial(u) for u in scrambled_halton(16)]
results = sorted(((fake_validation_loss(t), t) for t in trials), key=lambda r: r[0])
for loss, t in results[:3]:
    print(f"loss {loss:.3f}  lr {t['lr']:.2e}  wd {t['weight_decay']:.1e}  dropout {t['dropout']:.2f}")

Output:

loss 0.021  lr 7.55e-04  wd 1.4e-04  dropout 0.23
loss 0.278  lr 1.34e-03  wd 9.1e-06  dropout 0.05
loss 0.427  lr 4.24e-04  wd 1.5e-03  dropout 0.13

Source: derived from the search-space advice in the Deep Learning Tuning Playbook; see also the SciPy quasi-Monte Carlo module (scipy.stats.qmc.Sobol, Halton) for production-grade generators.

With Optuna the same idea is a sampler choice, and the study object records every trial:

import optuna

def objective(trial: optuna.Trial) -> float:
    lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True)
    weight_decay = trial.suggest_float("weight_decay", 1e-6, 1e-2, log=True)
    dropout = trial.suggest_float("dropout", 0.0, 0.5)
    # Train a model here and return the validation metric to minimise.
    return (lr * 1e3 - 1) ** 2 + weight_decay + (dropout - 0.2) ** 2

study = optuna.create_study(
    direction="minimize",
    sampler=optuna.samplers.QMCSampler(seed=0),   # quasi-random search for exploration
)
study.optimize(objective, n_trials=32)
print(study.best_params)

Source: Optuna: samplers.

Choosing how long to train

Training length changes the answer to almost every other question, so decide it explicitly.

  • Compute-bound training means you would still be improving if you trained longer, and the budget (time or money) is what stops you. Here the aim is to get the best result in a fixed number of steps; the training length is a budget, not a hyperparameter to tune against validation, and the learning-rate schedule must be built for exactly that budget.

  • Not compute-bound training means the model reaches a plateau and more steps would not help. Here the question is how long it takes to plateau, and training for the minimum number of steps that gets there saves time.

  • Do not stop on one noisy validation point. Evaluate regularly and keep the checkpoint (or the schedule’s final state) selected by validation performance, retrospectively.

  • A schedule needs a horizon. If you extend training, extend the schedule; otherwise you compare a decayed run with a run that stopped mid-schedule. Warmup-stable-decay and similar schedules (see Optimizers & Learning-Rate Schedules) make later extension easier.

  • Re-tune after large changes. Doubling the training length or the model width moves the best learning rate and regularisation strength; a tuned configuration is valid for the scale it was tuned at.

Evaluating during training

  • Evaluate by step count, not only by epoch, so that runs with different dataset sizes and batch sizes align on the x axis.

  • Hold out three sets with three jobs: a training set; a validation set that you tune against; a test set you touch rarely and report once. A validation set that is too small makes differences between configurations unmeasurable; compute the noise on the metric (bootstrap or seed variance) before deciding that a 0.2-point gain is real.

  • Use the same preprocessing at training and evaluation time, except for random augmentation. Models with batch normalisation or dropout must be put in evaluation mode (model.eval() in PyTorch, training=False in Keras) for validation.

  • Track more than the loss. Log the learning rate, the gradient norm, the loss on a fixed training subset (evaluated in evaluation mode) and the task metric. The gap between training-subset and validation metrics is the diagnostic that matters.

  • Seeds matter. Differences between two configurations that are smaller than the spread between seeds of one configuration are not evidence. Run at least a few seeds for the final comparison, or when a gain looks small.

import torch
from torch import nn

@torch.no_grad()
def evaluate(model: nn.Module, loader, loss_fn, device) -> dict:
    """Mean loss and accuracy over a loader, in evaluation mode."""
    was_training = model.training
    model.eval()
    total_loss, correct, count = 0.0, 0, 0
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        logits = model(x)
        total_loss += loss_fn(logits, y).item() * len(y)
        correct += (logits.argmax(dim=1) == y).sum().item()
        count += len(y)
    model.train(was_training)
    return {"loss": total_loss / count, "accuracy": correct / count}

# Inside the training loop, evaluate every N steps, not only at the end of an epoch:
#     if step % eval_every == 0:
#         val = evaluate(model, val_loader, loss_fn, device)
#         train_subset = evaluate(model, train_subset_loader, loss_fn, device)
#         log(step=step, lr=scheduler.get_last_lr()[0], grad_norm=float(grad_norm), **val)

A learning-rate range test

The learning rate is the one hyperparameter you always tune. A range test gives a first estimate cheaply: raise the rate geometrically over a few hundred steps, record the loss, and stop when it diverges.

import copy
import math
import torch
from torch import nn

def lr_range_test(model, make_batches, loss_fn, lr_min=1e-7, lr_max=1.0, steps=200):
    """Return (learning rates, smoothed losses) for a quick learning-rate sweep."""
    model = copy.deepcopy(model)                       # do not disturb the real model
    optimizer = torch.optim.SGD(model.parameters(), lr=lr_min, momentum=0.9)
    gamma = (lr_max / lr_min) ** (1.0 / steps)
    lrs, losses, best, smooth = [], [], math.inf, None
    batches = iter(make_batches())
    for step in range(steps):
        x, y = next(batches)
        lr = lr_min * gamma**step
        for group in optimizer.param_groups:
            group["lr"] = lr
        optimizer.zero_grad(set_to_none=True)
        loss = loss_fn(model(x), y)
        loss.backward()
        optimizer.step()
        value = loss.item()
        smooth = value if smooth is None else 0.9 * smooth + 0.1 * value
        lrs.append(lr)
        losses.append(smooth)
        best = min(best, smooth)
        if not math.isfinite(smooth) or smooth > 4 * best:
            break                                       # diverged
    return lrs, losses

# Example with synthetic data
torch.manual_seed(0)
net = nn.Sequential(nn.Linear(20, 32), nn.ReLU(), nn.Linear(32, 1))
def batches():
    while True:
        x = torch.randn(64, 20)
        yield x, x[:, :1] * 2.0

lrs, losses = lr_range_test(net, batches, nn.MSELoss())
print(f"swept {len(lrs)} steps, lowest smoothed loss {min(losses):.4f} at lr {lrs[losses.index(min(losses))]:.2e}")

Source: derived from the learning-rate guidance in the CS231n notes and the Deep Learning Tuning Playbook; the geometric sweep follows Smith, "Cyclical Learning Rates for Training Neural Networks".

Pick a peak rate somewhat below the rate where the loss was lowest, then confirm with real runs: the test assumes the final data, architecture and optimizer, and the best rate of a long run with a decay schedule is usually different from the one this short sweep suggests.

Reading the training curves

Plot training and validation loss (and the metric) against steps for every run and read the shape before changing anything.

What you see Likely meaning What to try

Training loss does not move from the initial value

Bug, learning rate far too small or too large, dead activations, frozen layers

Overfit one batch; check gradients; run the range test; check labels.

Loss goes to nan or infinity

Learning rate too high, missing warmup, unstable loss computation, bad data

Lower the rate, add warmup, clip the global gradient norm, use a numerically stable loss, check inputs for non-finite values.

Training loss falls slowly and the gap to validation is small

Underfitting or an optimisation problem

Raise the learning rate (up to stability), train longer, enlarge the model, reduce regularisation.

Training loss is low and validation loss is high or rising

Overfitting

More data or augmentation, stronger weight decay or dropout, smaller model, early stopping, transfer learning.

Both losses are low but the task metric is poor

Wrong objective, label noise, train/test mismatch

Re-examine the metric, label quality and the evaluation split.

Loss curve has sudden spikes

Rare large gradients, data glitches, too-high peak rate

Clip gradients, lower the peak rate, find the offending batches.

Validation noisy from one evaluation to the next

Validation set too small, high learning rate, batch-norm statistics

Larger validation set, evaluate more often, smooth for decisions, check evaluation mode.

Training is much better under one seed than another

High variance between runs

Run several seeds before drawing conclusions; consider lower learning rate or EMA of weights.

flowchart TD S["Model does not learn well"] --> Q1{"Can it overfit
one small batch?"} Q1 -- no --> B1["Fix bugs: labels, loss,
shapes, frozen layers,
zero_grad placement"] Q1 -- yes --> Q2{"Is training loss
stable and decreasing?"} Q2 -- no --> B2["Lower learning rate,
add warmup, clip gradients,
check for non-finite data"] Q2 -- yes --> Q3{"Large gap between
train and validation?"} Q3 -- yes --> B3["Regularise: augmentation,
weight decay, dropout,
more data, smaller model"] Q3 -- no --> Q4{"Training loss still
too high?"} Q4 -- yes --> B4["Bigger model, longer training,
retune learning rate,
less regularisation"] Q4 -- no --> B5["Check metric, labels,
and train/test mismatch"]

Making comparisons you can trust

  • One change at a time. If two things change between runs, you cannot attribute the difference.

  • Same data, same splits, same evaluation code. A different validation split is a different benchmark.

  • Tune each candidate with equal effort. A heavily tuned baseline against an untuned new idea is a common source of false progress; give both the same search budget and report the best of each.

  • Report spread. Give the mean and standard deviation over seeds, or at least the range, and avoid reporting the maximum over many runs as if it were typical.

  • Keep the test set out of the loop. Using it to pick hyperparameters turns it into a validation set and makes the final estimate optimistic.

  • Record everything. Every run needs its code version, data version, seed, hyperparameters, environment and metrics, which Experiment Tracking & MLOps for Training shows how to do.

Tuning and compute

  • Optimise the input pipeline first. If the accelerator waits on data, every experiment takes longer; profile the loader (workers, prefetching, caching, decoding on the accelerator) before buying hardware. The hardware side is in Hardware, Memory & Mixed Precision.

  • Use early rounds on small models and short runs, then verify that conclusions transfer to the full scale; some hyperparameters transfer (initialisation scale with width-aware parameterisations) and many do not.

  • Prefer an ensemble of reasonable models or weight averaging to squeezing the last 0.1 points out of one model when the budget allows it, and distil or compress afterwards (see Model Compression: Quantization, Pruning & Distillation).

  • Stop when the gains stop being worth the cost. Tuning has diminishing returns; improved data, labels or problem framing usually beat another round of hyperparameter search (see Problem Framing & the ML Project Lifecycle).

Framework notes

In PyTorch, set seeds with torch.manual_seed and consult the reproducibility notes: bit-for-bit determinism requires torch.use_deterministic_algorithms(True) and costs speed, and some GPU operations are non-deterministic by default. In Keras 3, keras.utils.set_random_seed(seed) seeds Python, NumPy and the active backend in one call, and keras.callbacks.EarlyStopping(restore_best_weights=True) implements retrospective checkpoint selection. The old Keras tuner and scikit-learn wrapper routes differ across versions: for scikit-learn-style searches around a Keras 3 model use the built-in keras.wrappers.SKLearnClassifier, SKLearnRegressor and SKLearnTransformer wrappers (SciKeras is archived), and for PyTorch use skorch, or write the search loop directly as above.

Checklist

  1. Verify the data, the initial loss, one-batch overfitting and gradient flow before tuning.

  2. Start from a proven architecture, a standard optimizer, a throughput-driven batch size and a simple configuration.

  3. Work in rounds: one question per round, scientific hyperparameters varied, nuisance ones tuned, the rest fixed.

  4. Search on log scales, use quasi-random search for exploration, and check that the best trial is not at the boundary.

  5. Tie the training length and schedule horizon to the budget and re-tune when scale changes.

  6. Evaluate on a fixed schedule of steps with a validation set large enough to see the differences you care about.

  7. Run several seeds before declaring an improvement.

  8. Keep the test set for the end, and log everything needed to reproduce each run.