smartyfy.mrindigi.com

Python Master Course V2 — 145. Training Diagnostics, Checkpoints and Reproducibility

Purpose and learning outcomes

A long run is not reliable merely because its loss usually decreases. You need to detect broken gradients, select a checkpoint without consulting test data, and recover from an interruption. This lesson builds a small CPU training script with a latest-state checkpoint for resuming and a separate best-validation state for inference. Both are saved only as trusted local artifacts.

  • Detect underfitting, overfitting and broken learning loops
  • Save and restore trusted state dictionaries and run metadata
  • Apply early stopping without consulting the test set

Prerequisites: 143–144: training and optimization; 119: reproducible checks.

Environment and run order

Use the isolated Python 3.11 or 3.12 environment from lesson 142. All tensors and models below run on the CPU. No pretrained weights or external datasets are downloaded. For first-time setup install the numerical packages, then use the official PyTorch installer selector for your operating system. The CPU wheel command below is for Linux or Windows; macOS uses python -m pip install torch. Run Python blocks sequentially in a single file.

Shell

python -m pip install numpy pandas scikit-learn matplotlib
# Linux/Windows CPU installation:
python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

Diagnostics begin with a falsifiable expectation

Before changing the architecture, verify finite inputs, matching shapes, nonzero parameter updates, and finite gradients. A one-batch overfit test isolates basic learning mechanics. A flat curve can mean underfitting, an ineffective learning rate, frozen parameters, detached tensors, or misaligned labels. A growing train-validation gap may indicate overfitting, but distribution differences and evaluation-mode errors should be checked first.

Early stopping is model selection

Early stopping chooses an epoch using validation loss. patience is the number of consecutive epochs without a sufficiently large improvement before stopping; min_delta defines what counts as improvement. This turns validation into an explicit selection signal. The test set must remain untouched until the selected state and all other choices are frozen. A best state must be copied, because a shallow reference to current parameters can change as training continues.

Latest and best are different artifacts

The latest state contains the current model and optimizer states and supports continuing the same training trajectory. The best state contains the parameter values selected by validation and supports final inference. Resuming from the best weights while retaining optimizer moments from a later epoch creates a mismatched state. Store the optimizer, epoch, patience counter, random generator states, preprocessing, and selected-best state together for a coherent continuation.

Reproducibility has a declared scope

Saving random-number states can reproduce the next draws in the same environment, but does not guarantee bit-identical behavior across hardware or releases. This full-batch example avoids shuffled minibatch state; a DataLoader run would also need its generator state and any sampler progress. torch.load with weights_only=True reduces the permitted unpickling surface but is not a license to load unknown files. Only restore artifacts with trusted provenance.

Incremental worked example

1. Initialize a resumable synthetic experiment

The script uses no pre-existing checkpoint: it creates a new run, saves after eight epochs, and immediately restores that file to demonstrate resumption. Input standardization learns from training only. Test data are created but remain sealed.

Python

from pathlib import Path
import copy
import torch
from torch import nn

torch.set_num_threads(1)
torch.manual_seed(45)
X = torch.randn(300, 4)
y = (X[:, 0] + 0.7 * X[:, 1] * X[:, 2] > 0).long()
ids = torch.randperm(len(X))
train, valid, test = ids[:180], ids[180:240], ids[240:]
mean, scale = X[train].mean(0), X[train].std(0).clamp_min(1e-6)
Z = (X - mean) / scale
def build_model():
    return nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 2))
model = build_model()
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
loss_fn = nn.CrossEntropyLoss()
best_loss, best_state, stale = float("inf"), None, 0
patience, min_delta = 6, 1e-4
checkpoint = Path("lesson145-latest-trusted.pt")
def train_one_epoch(net, opt):
    net.train()
    opt.zero_grad(set_to_none=True)
    loss = loss_fn(net(Z[train]), y[train])
    if not torch.isfinite(loss):
        raise RuntimeError("Non-finite training loss")
    loss.backward()
    norm = torch.nn.utils.clip_grad_norm_(net.parameters(), max_norm=5.0,
                                          error_if_nonfinite=True)
    opt.step()
    net.eval()
    with torch.no_grad():
        value = loss_fn(net(Z[valid]), y[valid]).item()
    return loss.item(), value, float(norm)
def pack(epoch):
    return {"model": model.state_dict(), "optimizer": optimizer.state_dict(),
        "epoch": epoch, "best_loss": best_loss, "best_state": best_state,
        "stale": stale, "rng": torch.get_rng_state(), "mean": mean, "scale": scale,
        "patience": patience, "min_delta": min_delta, "torch_version": str(torch.__version__)}

2. Save, restore, and continue the same stopping rule

The norm is measured before clipping; clipping is a safeguard rather than a substitute for diagnosing exploding gradients. Restoration recreates the architecture and optimizer before loading their states. Restoring the random state occurs after construction, since initialization itself consumes randomness.

Python

for epoch in range(8):
    train_loss, value, grad_norm = train_one_epoch(model, optimizer)
    if value < best_loss - min_delta:
        best_loss, best_state, stale = value, copy.deepcopy(model.state_dict()), 0
    else:
        stale += 1
    print(epoch, train_loss, value, grad_norm)
    if stale >= patience:
        break
torch.save(pack(epoch), checkpoint)
state = torch.load(checkpoint, map_location="cpu", weights_only=True)
model = build_model()
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
model.load_state_dict(state["model"])
optimizer.load_state_dict(state["optimizer"])
best_loss, best_state, stale = state["best_loss"], state["best_state"], state["stale"]
mean, scale = state["mean"], state["scale"]
Z = (X - mean) / scale
torch.set_rng_state(state["rng"])
for epoch in range(state["epoch"] + 1, 60):
    if stale >= patience:
        break
    train_loss, value, grad_norm = train_one_epoch(model, optimizer)
    if value < best_loss - min_delta:
        best_loss, best_state, stale = value, copy.deepcopy(model.state_dict()), 0
    else:
        stale += 1
    torch.save(pack(epoch), checkpoint)
model.load_state_dict(best_state)
model.eval()
with torch.no_grad():
    restored_best_loss = loss_fn(model(Z[valid]), y[valid]).item()
assert abs(restored_best_loss - best_loss) < 1e-6
print("selected validation loss", best_loss, "stale epochs", stale)

Expected output / interpretation

The script prints initial diagnostic rows and the selected validation loss.
A trusted latest-state file is saved locally and restored with weights_only=True.
The final assertion checks that the copied best state reproduces its recorded validation loss.

Guided lab and acceptance criteria

  1. Add an epoch-by-epoch history of training loss, validation loss, gradient norm, and best epoch. Plot the curves and annotate the patience window. Make clear that the selected epoch is chosen by validation.
  2. Compare an uninterrupted run with the save-and-resume version under the same environment and full-batch setup. Check parameter tensors with a stated tolerance. Report actual results rather than promising equivalence across machines.
  3. Extend the checkpoint schema with split indices, the data-generation seed, feature names, and a configuration version. If switching to shuffled minibatches, also save and restore the DataLoader generator state; a global seed alone does not restore its current position.
  4. Deliver the resumable script, best-checkpoint audit, and a trust warning in the README. A passing result restores a coherent latest model/optimizer pair and applies early stopping without using test labels.

Common mistakes and repairs

  • Assigning best_state=model.state_dict without copying: its tensors can continue to reflect later updates; take a deep copy for an in-memory best snapshot.
  • Resuming best weights with unrelated latest optimizer moments: restore a matched checkpoint or intentionally start a new optimization phase and document it.
  • Using gradient clipping to hide persistently non-finite updates: fail visibly, then inspect inputs, objective, and learning rate.

Questions that test understanding

Why does the checkpoint include optimizer state?

Adam maintains moving gradient summaries. Restoring weights alone starts a different optimization trajectory because those summaries are missing. A weights-only restart can be legitimate for fine-tuning, but it is not equivalent to resuming the same run and should be described accordingly.

Why is best_state deep-copied?

A state dictionary contains tensors representing current parameter values. Keeping a shallow reference can allow subsequent updates to alter the supposed best snapshot. A deep copy preserves the actual values at the selected epoch, making the later restoration meaningful.

Does weights_only=True make every .pt file safe?

No. It narrows what the loader accepts and is preferable for compatible state dictionaries, but provenance and resource risks still matter. Load only trusted artifacts. Do not automatically disable the restriction or allowlist unknown classes just because a downloaded file fails to load.

Why log the gradient norm before clipping?

The pre-clipping norm reveals whether updates are repeatedly trying to become excessive. If you logged only the clipped norm, every bad step could appear comfortably bounded and hide an underlying problem. Clipping is an intervention, so retain evidence about why it was needed.

Why does initialization happen before restoring the RNG state?

Constructing layers consumes random draws. Restoring the saved generator state first and then initializing would advance the generator beyond the intended resume point. Recreate objects, load states, and finally restore random state before continuing stochastic operations.

Can early stopping overfit validation?

Yes. Epoch selection uses validation information, and extensive architecture and patience tuning uses even more. Keep a final test independent and report the full selection procedure. Early stopping helps manage one form of overfitting; it does not eliminate selection bias.

Exercises with worked solutions

Exercise 1: Test that evaluation leaves parameters unchanged

Reveal the worked solution and reasoning

Clone parameters before an eval/no-grad pass and compare afterward. This verifies a basic phase boundary independently of metric quality. It would catch an accidental optimizer update inserted into evaluation.

Python

before = [p.detach().clone() for p in model.parameters()]
model.eval()
with torch.no_grad():
    _ = model(Z[valid])
assert all(torch.equal(a, b) for a, b in zip(before, model.parameters()))
print("evaluation preserved parameters")

Exercise 2: Explain what a shuffled-loader checkpoint additionally needs

Reveal the worked solution and reasoning

Save the loader’s torch.Generator state and restore it before the next iterator is created. For exact mid-epoch resumption, also track sampler order and consumed batches, plus worker randomness if workers are used. An epoch-boundary checkpoint is simpler. State the supported resume boundary rather than claiming a generic exact restart.

Recap and next step

Diagnostics tell you whether learning mechanics behave sensibly; validation chooses the best epoch; a latest checkpoint supports coherent continuation. These are distinct responsibilities. Next we retain them while changing the architecture to a convolutional network for tiny images, where tensor layout and spatial shape become additional contracts.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.