The Training Loop & Evaluation

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

PyTorch has no fit() method. You write the loop yourself, which is more code than in Keras or scikit-learn but makes every step visible and modifiable. The loop is short, and almost every training bug is one of a handful of ordering or mode mistakes in it. This page builds the canonical loop from the pieces covered in the previous pages (nn.Module, Loss Functions, Optimizers, Datasets & DataLoader), then adds the evaluation loop, metrics, gradient accumulation, clipping, learning-rate schedulers, early stopping and checkpointing. The general theory of what the loop optimises is in Gradient Descent & Optimization and Backpropagation & Automatic Differentiation.

Examples were run on Python 3.13 with PyTorch 2.15 on 2026-10-31. The recipe follows the official "Optimizing Model Parameters" and "Saving and Loading Models" tutorials.

Anatomy of one training step

flowchart TD A["batch from DataLoader"] --> B["move to device"] B --> C["forward: logits = model(x)"] C --> D["loss = criterion(logits, y)"] D --> E["loss.backward(): fill .grad"] E --> F["optional: clip gradients"] F --> G["optimizer.step(): update parameters"] G --> H["optimizer.zero_grad(): clear .grad"] H --> I["optional: scheduler.step() per step or per epoch"]

The five lines that matter:

logits = model(x)                 # forward pass builds the autograd graph
loss = criterion(logits, y)       # scalar
loss.backward()                   # accumulates d(loss)/d(param) into param.grad
optimizer.step()                  # uses param.grad to update the parameters
optimizer.zero_grad()             # gradients accumulate by default, so reset them

Gradients are added to the existing .grad of each parameter on every backward() call. The official tutorial states the reason for clearing them each iteration: gradients by default add up, so they are zeroed explicitly to prevent double counting. The clear can come either right after optimizer.step() (as in the tutorial) or right before loss.backward(); what matters is that exactly one clear happens between two backward passes that should not be summed. Since PyTorch 2.0 zero_grad defaults to set_to_none=True, which frees the gradient tensors instead of filling them with zeros, saving memory and a kernel launch; a parameter whose .grad is None is skipped by most optimizers.

train() and eval() modes

model.train() and model.eval() set the training flag recursively on every submodule. They do not change gradient tracking. Layers that behave differently are:

  • Dropout (and AlphaDropout, Dropout2d…​) zeroes activations in training mode and is the identity in evaluation mode.

  • BatchNorm uses batch statistics and updates its running mean and variance in training mode, and uses the stored running statistics in evaluation mode. LayerNorm and GroupNorm behave the same in both modes.

  • Some torchvision models and custom layers (stochastic depth, spectral norm) also check the flag.

Forgetting model.eval() before validation gives noisy, pessimistic metrics (dropout still active, batch norm using validation-batch statistics). Forgetting to switch back with model.train() at the start of the next epoch silently trains without dropout and with frozen batch-norm statistics. Make the switch the first line of the train and evaluate functions rather than relying on the caller. Details of both layers are in Embeddings, Normalization, Dropout & Activations.

Evaluation without gradients

During evaluation you do not need the autograd graph. Wrapping the loop in torch.no_grad() avoids building it, which reduces memory and computation. torch.inference_mode() is a stricter and slightly faster variant for code that will never use the tensors in autograd afterwards; the differences, and a few corner cases, are explained in no_grad, inference_mode & Grad Modes. model.eval() and torch.no_grad() are independent and you normally want both.

@torch.inference_mode()
def evaluate(model, loader, criterion, device):
    model.eval()
    total_loss, correct, count = 0.0, 0, 0
    for x, y in loader:
        x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
        logits = model(x)
        total_loss += criterion(logits, y).item() * y.size(0)   # weight by batch size
        correct += (logits.argmax(dim=1) == y).sum().item()
        count += y.size(0)
    return total_loss / count, correct / count

Averaging per-batch losses without weighting by batch size over-counts a small final batch; weighting by y.size(0), as above, gives the exact per-sample mean. The .item() calls force a synchronisation with the GPU each batch; for long evaluations accumulate on the device and call .item() once at the end.

A complete runnable example

The program below trains a small classifier on synthetic data, so it runs anywhere in seconds. It picks the device with torch.accelerator, tracks the best validation accuracy and saves a checkpoint.

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset, random_split

torch.manual_seed(0)

# ---- data: two Gaussian blobs in 10 dimensions ----
n = 4000
x0 = torch.randn(n // 2, 10) + 1.0
x1 = torch.randn(n // 2, 10) - 1.0
X = torch.cat([x0, x1])
y = torch.cat([torch.zeros(n // 2), torch.ones(n // 2)]).long()
dataset = TensorDataset(X, y)
train_ds, val_ds = random_split(dataset, [0.8, 0.2],
                                generator=torch.Generator().manual_seed(0))
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True)
val_loader = DataLoader(val_ds, batch_size=256)

# ---- model, loss, optimiser, scheduler ----
device = torch.accelerator.current_accelerator() or torch.device("cpu")
model = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Dropout(0.1), nn.Linear(32, 2)).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=20)


def train_one_epoch(model, loader):
    model.train()
    running = 0.0
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        optimizer.zero_grad()
        loss = criterion(model(x), y)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()
        running += loss.item() * y.size(0)
    return running / len(loader.dataset)


@torch.inference_mode()
def evaluate(model, loader):
    model.eval()
    loss_sum, correct = 0.0, 0
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        logits = model(x)
        loss_sum += criterion(logits, y).item() * y.size(0)
        correct += (logits.argmax(1) == y).sum().item()
    n_samples = len(loader.dataset)
    return loss_sum / n_samples, correct / n_samples


best_acc, patience, bad_epochs = 0.0, 5, 0
for epoch in range(20):
    train_loss = train_one_epoch(model, train_loader)
    val_loss, val_acc = evaluate(model, val_loader)
    scheduler.step()                                   # epoch-level scheduler
    print(f"epoch {epoch:2d}  train {train_loss:.4f}  val {val_loss:.4f}  acc {val_acc:.3f}")
    if val_acc > best_acc:
        best_acc, bad_epochs = val_acc, 0
        torch.save({"epoch": epoch,
                    "model_state_dict": model.state_dict(),
                    "optimizer_state_dict": optimizer.state_dict(),
                    "scheduler_state_dict": scheduler.state_dict(),
                    "best_acc": best_acc}, "best.pt")
    else:
        bad_epochs += 1
        if bad_epochs >= patience:                     # early stopping
            print("early stop")
            break

On the run for this page the validation accuracy reached 1.000 at epoch 3; because it could no longer improve, early stopping ended training after epoch 8.

Points worth noting in the example:

  • The optimizer is created after the model is moved to its device, so its state tensors live on the same device as the parameters.

  • clip_grad_norm_ runs after backward() and before step(), because it rescales the existing .grad values.

  • Early stopping watches a validation metric and not the training loss, and the checkpoint is written only when the metric improves.

  • The held-out validation set is used for model selection; a separate test set should be touched once at the end (see Generalization & Regularization and Deep Learning Tuning Playbook).

Gradient accumulation

When the batch you want does not fit in memory, run several smaller micro-batches and update the parameters once. Because gradients add up in .grad, accumulation is just a matter of delaying step() and zero_grad(). Divide each micro-batch loss by the number of accumulation steps so that the summed gradient matches the gradient of the mean loss over the large batch.

accum_steps = 4
optimizer.zero_grad()
for i, (x, y) in enumerate(train_loader):
    x, y = x.to(device), y.to(device)
    loss = criterion(model(x), y) / accum_steps
    loss.backward()
    if (i + 1) % accum_steps == 0 or (i + 1) == len(train_loader):
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        optimizer.zero_grad()

Batch normalisation statistics are still computed per micro-batch, so accumulation is not exactly equivalent to a large batch for models that contain batch norm. Under DistributedDataParallel, skip the gradient synchronisation on non-final micro-steps with model.no_sync() (see DistributedDataParallel). The memory side of the trade-off is discussed in Hardware, Memory & Mixed Precision.

Gradient clipping

Exploding gradients, common in recurrent networks and transformers, are tamed by clipping before the update. The two utilities are torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=2.0), which rescales all gradients together so their global norm does not exceed max_norm (and returns the total norm before clipping, a useful value to log), and torch.nn.utils.clip_grad_value_(parameters, clip_value), which clamps each element. The global-norm version preserves the gradient direction and is the usual choice. With mixed-precision loss scaling you must unscale before clipping (see Mixed Precision with torch.amp).

Schedulers: where to call step()

A learning-rate scheduler must be stepped after the optimizer: optimizer.step() first, then scheduler.step(). Calling them in the opposite order skips the first value of the schedule and PyTorch warns about it. Epoch-based schedulers (StepLR, CosineAnnealingLR, MultiStepLR) step once per epoch; per-iteration schedulers (OneCycleLR, CyclicLR, and warm-up combined with decay through SequentialLR) step after every batch. ReduceLROnPlateau is stepped with the validation metric: scheduler.step(val_loss). See Learning-Rate Schedulers & SWA/EMA and the conceptual treatment in Optimizers & Learning-Rate Schedules. Save and restore the scheduler state alongside the optimizer state when resuming, as the checkpoint above does.

Checkpointing and resuming

A resumable checkpoint stores more than the weights. The official tutorial lists the epoch, the model state, the optimizer state and the loss, and you should add the scheduler state, the scaler state when using mixed precision, and the random-number-generator state if exact reproducibility matters. To resume:

ckpt = torch.load("best.pt", map_location=device, weights_only=True)
model.load_state_dict(ckpt["model_state_dict"])
optimizer.load_state_dict(ckpt["optimizer_state_dict"])
scheduler.load_state_dict(ckpt["scheduler_state_dict"])
start_epoch = ckpt["epoch"] + 1
model.train()                      # resume training; use model.eval() for inference

Always call model.eval() before inference and model.train() before continuing to train after loading. Loading restrictions, map_location and the weights_only default are covered in Saving & Loading Models. For multi-node jobs use the distributed checkpoint API (Distributed Checkpoint & Flight Recorder).

Logging and metrics

Keep per-epoch metrics in plain Python lists or dictionaries and log them to a tracker; TensorBoard Integration and Experiment Tracking & MLOps show how. Prefer accumulating sums and counts and dividing at the end over averaging averages. For metrics beyond accuracy (precision, recall, AUROC, F1) the separate TorchMetrics package handles correct accumulation across batches and devices; scikit-learn’s metrics (see Model Evaluation) work on collected predictions.

Common mistakes

  • No optimizer.zero_grad(): gradients from every batch pile up, the loss diverges or plateaus oddly.

  • model.eval() missing during validation, or model.train() missing after it.

  • Accumulating loss instead of loss.item() across batches keeps every graph alive and leaks memory; accumulate Python floats or detached tensors.

  • Moving the model to the GPU after creating the optimizer, which can leave optimizer state on the wrong device when resuming from a checkpoint.

  • Applying softmax before nn.CrossEntropyLoss, which expects raw logits.

  • Calling .item() or printing tensors every step, which serialises the GPU.

  • Evaluating with drop_last=True or shuffle=True, which changes or discards samples.

  • Using the test set for early stopping or hyper-parameter choices.

Large-scale and performance-oriented variants of the same loop continue in Performance Tuning Guide and torch.compile; a worked image-classification project is in Worked Example: CNN Image Classifier.