DaZu / PyTorchDaZu home

1 · Fundamentals / Quick guide

Tensors and the training loop

Understand what enters a PyTorch model, how its weights change, and how to check its predictions.

This is the foundation for the other five guides. Training changes the experiment settings; Vision and Text change how the input is represented.

How it works

When do weights change?

One batch · five stages
  1. 1 · Clearzero_grad: clear old gradients.
  2. 2 · ForwardCompute predictions with current weights.
  3. 3 · LossCompare predictions with targets.
  4. 4 · BackwardCompute gradients; weights stay fixed.
  5. 5 · StepUse gradients to update weights.

backward changes gradients; optimizer.step changes weights.

Read all five stages together: backward computes gradients, then the optimizer changes weights. This is a conceptual flow, not a training benchmark.

A model learns by repeatedly predicting a batch, measuring error, and changing its weights. A Dataset supplies one sample and label; a DataLoader groups them. Follow the complete flow above to see when weights change.

Code and functions

Function / settingWhat it doesWhat to check
shape / dtype / deviceDescribe tensor layout, number type and location.Images: [N,C,H,W]; class IDs: long; model and input on the same device.
nn.Module / Linear / ReLUDefine trainable layers and nonlinear features.Stacked linear layers alone still describe a linear map. ReLU zeros negative hidden values.
CrossEntropyLossCompare raw class scores with correct IDs.Logits [N,K] and targets [N]. Do not add softmax first.
backward / optimizer.stepCompute gradients, then update weights.Clear old gradients before each ordinary batch update.
Conv2d / MaxPool2d / FlattenExtract local features, reduce spatial size, prepare a head.Trace channels, height and width before choosing a linear input size.
eval / no_gradSwitch layer behavior and disable gradient recording.Both are needed for ordinary validation; neither performs a weight update.
One classification training batch · inside an epoch
model.train()
for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad(set_to_none=True)
    logits = model(images)
    loss = loss_fn(logits, labels)
    loss.backward()
    optimizer.step()

The architecture, loaders, optimizer and loss are prepared first. This excerpt shows their order inside training; it is not a standalone script.

Check your understanding

Read the three illustrative loss patterns together. For your own batch counts, pooling sizes or tensor shapes, open the optional calculators below. These curves are not measured training results.

Try your own numbers

Batch calculator

CNN shape tracer

Broadcasting checker

Compare the train–validation relationship

Underfitting
Loss
0Illustrative epoch29

Underfitting: both losses remain high.

Final train 0.7597; validation 0.84.

Balanced illustration
Loss
0Illustrative epoch29

Balanced illustration: both losses fall, with a modest gap.

Final train 0.0937; validation 0.174.

Overfitting
Loss
0Illustrative epoch29

Overfitting: training falls while validation turns upward.

Final train 0.0937; validation 0.534.

Solid teal: training · Dashed orange: validation. Read each pair on the same axes; these are three situations, not a continuous regularization law.

Synthetic curves, not measured Nature CNN or other model results.

Common mistakes

A sample is prepared inside Dataset access
  1. File / indexDataset.__getitem__ selects one source and label.
  2. Decode + transformInside that access: decode pixels, resize, convert and normalize.
  3. Return sampleOne tensor [C,H,W] and its target.
  4. Collate in DataLoaderGroup samples into [N,C,H,W] and batch targets.
Original-size reference diagramConceptual image-to-transform-to-dataset-to-batch pathOpen full-size diagram
Preparation ends with tensors the model can consume.
Follow an illustrative image batch
  1. Input[N,3,32,32]
  2. Conv + ReLU[N,32,32,32] with padding 1
  3. Pool 2×[N,32,16,16]
  4. Conv + ReLU[N,64,16,16] with padding 1
  5. Global pool + head[N,64,1,1] → [N,64] → [N,K]
Original-size reference diagramConceptual CNN shapes through convolution, pooling and the classification headOpen full-size diagram
Convolution changes feature channels; pooling reduces spatial dimensions.