This Machine Learning concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.
Machine Learning
Practical Training Loop
A training loop is a reproducible contract: batches enter, losses produce gradients, the optimizer updates state, validation measures without training, and checkpoints preserve enough state to resume.
Concept Structure
Practical Training Loop
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learner Contract
What this page should let you do.
3 prerequisites listed; refresh them before leaning on the math or code.
Explain the mechanism, trace the main notation, and test one prediction in the live demo.
Read the intuition before the notation; the math should name a mechanism you already felt.
Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.
Claim/source review status
Substantive review recorded
1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
The training loop is where a neural network stops being an equation on a page and becomes an experiment you can reproduce. A good loop is not just "call fit." It is a contract: every batch must enter with the right shape and device, the model must be in the right mode, the loss must create the right scalar objective, gradients must be fresh, the optimizer must update parameters and its own state, validation must measure without accidentally training, and a checkpoint must preserve enough state to resume honestly.
That contract is why this page belongs before from-scratch Transformer work. If you cannot inspect one iteration, you cannot debug a 100-million-parameter run. The details get bigger later, but the grammar stays recognizable:
- Batch: a
Datasetdefines samples, and aDataLoaderturns them into minibatches. - Mode:
train()lets training-time layers behave as training-time layers;eval()changes dropout and normalization behavior for measurement. - Forward and loss: the model produces predictions, and the loss compresses a minibatch into one scalar.
- Gradient reset: accumulated gradients are useful in special microbatch setups, but the default contract resets them before the new backward pass.
- Backward: reverse-mode autodiff deposits parameter gradients.
- Optimizer step: the optimizer uses gradients and optimizer state to update parameters.
- Validation: measurement should usually run under
eval()andno_grad(). - Checkpoint: resuming training needs more than model weights if the optimizer, scheduler, scaler, RNG state, epoch, and config matter.
Mixed precision is a boundary, not magic dust. In a typical PyTorch AMP loop, autocast wraps the forward and loss computation, while scaling/unscaling and stepping live around backward and optimizer update. If you save a scaler or scheduler, it becomes part of the checkpoint contract.
The practical habit to build is simple: when a loss trace surprises you, do not start with folklore. Ask which part of the contract was broken.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let a training set contain examples , and let the model have parameters . For a minibatch at step , the loop estimates the empirical-risk gradient by averaging losses over that batch:
The backward pass computes
A plain SGD step would be
where is the learning rate. A practical optimizer such as AdamW is better viewed as a stateful update:
where is optimizer state such as moments, and contains hyperparameters such as learning rate and weight decay. That is why checkpointing only is not the same as checkpointing a resumable training run.
A serious checkpoint is a tuple like
where may include scheduler state, may include mixed-precision scaler state, is RNG/data-order state when exact continuation matters, stores metrics, and stores the run config. Different projects need different pieces, but the question is always the same: if you restart from , what hidden state did you silently reset?
Validation uses a separate measurement objective, often
computed without parameter updates. This number is not a gradient step. It is a measurement of the current model under validation-mode behavior.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
import torch
from torch import nn
device = "cuda" if torch.cuda.is_available() else "cpu"
model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
def run_epoch(loader, training: bool):
model.train(training)
total = 0.0
for xb, yb in loader:
xb, yb = xb.to(device), yb.to(device)
with torch.set_grad_enabled(training):
logits = model(xb)
loss = loss_fn(logits, yb)
if training:
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
total += loss.item() * xb.size(0)
return total / len(loader.dataset)
for epoch in range(5):
train_loss = run_epoch(train_loader, training=True)
val_loss = run_epoch(val_loader, training=False)
torch.save({
"epoch": epoch,
"model": model.state_dict(),
"optimizer": optimizer.state_dict(),
"train_loss": train_loss,
"val_loss": val_loss,
"config": {"lr": 3e-4, "weight_decay": 0.01},
}, "checkpoint.pt")
This is intentionally small. Real systems may add gradient accumulation, clipping, schedulers, mixed precision, distributed wrappers, logging, early stopping, and artifact versioning. The invariant is still inspectable: which state was read, which scalar was differentiated, which state was updated, and which state was saved?
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
Use the Practical Training Loop Lab as a diagnostic prediction check.
Choose a failure trace and commit to the missing contract step before reveal:
- Forgot
zero_grad: gradients accumulate across batches when the run intended one batch per update. - Skipped
optimizer.step: backward computes gradients, but parameters never move. - Stayed in
train()during validation: measurement is contaminated by training-time layer behavior. - Saved a weak checkpoint: model weights resume, but optimizer/scheduler/scaler/RNG state silently resets.
Before reveal, the answer-bearing stage, loss trace values, update norms, and checkpoint payload verdicts stay hidden. After reveal, inspect the highlighted contract stage, the toy trace, the checkpoint ledger, and the concrete reason the symptom follows from the broken step.
This is a diagnostic toy, not a full training framework. Its purpose is to make future labs easier to trust: when a larger model misbehaves, you have a compact checklist before you reach for guesses.
Live Concept Demo
Explore Practical Training Loop
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Commit to what Practical Training Loop should make visible before reading the result.
After The First Pass
Turn the concept into an inspected object.
Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.
Mechanism Storyboard
See the idea move before the page explains it
A training loop is a reproducible contract: batches enter, losses produce gradients, the optimizer updates state, validation measures without training, and checkpoints preserve enough state to resume.
Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change Practical Training Loop should make visible.
Visual Inquiry
Make the image answer a mathematical question
A training loop is a reproducible contract: batches enter, losses produce gradients, the optimizer updates state, validation measures without training, and checkpoints preserve enough state to resume.
Which visible object should carry the first intuition?
Pick the cue that should make Practical Training Loop easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Supports the epoch/iteration/minibatch training loop, train/eval mode split, gradient computation, zeroing, and optimizer step sequence.
Open sourceSupports the minibatch empirical-risk gradient and the computational/statistical reason for batching examples.
Open sourceSupports Dataset/DataLoader separation, minibatches, shuffling, and one-batch iteration shape checks.
Open sourceSupports train_loop/test_loop structure, model.train(), model.eval(), torch.no_grad(), zero_grad, loss.backward, and optimizer.step.
Open sourceSupports state_dict, checkpoint dictionaries, saving optimizer state for resuming, and train/eval mode after load.
Open sourceSupports autocast as a forward/loss-region context and GradScaler as the usual float16 AMP training companion.
Open sourceClaim Review
A training loop is a reproducible contract: batches enter, losses produce gradients, the optimizer updates state, validation measures without training, and checkpoints preserve enough state to resume.
Claims without a substantive review badge still need exact source-support review.
d2l-linear-regression-scratch-training, d2l-minibatch-sgd, pytorch-dataloaders, pytorch-optimization-loop, pytorch-saving-loading, pytorch-amp
Use equations, runnable code, and demos to check whether the source support is operational.
The sources jointly support minibatch objective estimates, DataLoader batching/shuffling, train and validation loop separation, zero/backward/step mechanics, state_dict checkpointing for resume, and mixed-precision forward/loss boundary caveats.
Sources: Dive into Deep Learning: Linear Regression Implementation from Scratch, Dive into Deep Learning: Minibatch Stochastic Gradient Descent, PyTorch Tutorials: Datasets and DataLoaders, PyTorch Tutorials: Optimizing Model Parameters, PyTorch Tutorials: Saving and Loading Models, PyTorch Documentation: Automatic Mixed Precision package - torch.ampToy diagnostic lab only; not distributed training, gradient accumulation over microbatches, DDP/FSDP, optimizer implementation internals, scheduler design, exact deterministic replay on every hardware stack, or GPT Pro publication approval.A bounded review summary is present; still check caveats and exact reference scope.Checked D2L for minibatch gradients and train/eval loop structure; PyTorch docs for DataLoader batching, zero_grad/backward/step, test_loop/no_grad, checkpoint state_dict resume, and AMP boundaries. Stanford CS336 supports the downstream from-scratch Transformer training motivation. GPT Pro/Oracle publication critique is still pending.
Reviewer: codex-local-primary-source-audit; reviewed 2026-07-02Source support candidates
book 2026Dive into Deep Learning: Linear Regression Implementation from ScratchSupports the epoch/iteration/minibatch training loop, train/eval mode split, gradient computation, zeroing, and optimizer step sequence.
book 2026Dive into Deep Learning: Minibatch Stochastic Gradient DescentSupports the minibatch empirical-risk gradient and the computational/statistical reason for batching examples.
documentation 2026PyTorch Tutorials: Datasets and DataLoadersSupports Dataset/DataLoader separation, minibatches, shuffling, and one-batch iteration shape checks.
documentation 2026PyTorch Tutorials: Optimizing Model ParametersSupports train_loop/test_loop structure, model.train(), model.eval(), torch.no_grad(), zero_grad, loss.backward, and optimizer.step.
Practice Loop
Try the idea before it explains itself
A training loop is a reproducible contract: batches enter, losses produce gradients, the optimizer updates state, validation measures without training, and checkpoints preserve enough state to resume.
Before touching the demo, predict one visible change that should happen in Practical Training Loop.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
Research Room
Attach the question to a claim, equation, code, or demo
Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.Open the draft below to save one note and next action in this browser.
Practical Training Loop
What is the smallest example that makes Practical Training Loop click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays in this browser, attached to the selected learning item.
- References to inspect: attached references on this page.
- Definition, prerequisite, and contrast concept links
- The equation or runnable code that makes the concept operational
- One demo state that shows the invariant instead of a slogan
- The learner can state the mechanism in their own words
- The learner can name the prerequisite that would repair confusion
- The learner can predict how the mechanism changes under one perturbation
I am working in Continuous Function's research reading room. Object: concept - Practical Training Loop Selected item key: recorded for copy. Context: Machine Learning Page anchor: recorded for copy. Open question: What is the smallest example that makes Practical Training Loop click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.
concept/concept-notebook/machine-learning/practical-training-loop
concept:machine-learning/practical-training-loop