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?
- 1 · Clearzero_grad: clear old gradients.
- 2 · ForwardCompute predictions with current weights.
- 3 · LossCompare predictions with targets.
- 4 · BackwardCompute gradients; weights stay fixed.
- 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 / setting | What it does | What to check |
|---|---|---|
shape / dtype / device | Describe tensor layout, number type and location. | Images: [N,C,H,W]; class IDs: long; model and input on the same device. |
nn.Module / Linear / ReLU | Define trainable layers and nonlinear features. | Stacked linear layers alone still describe a linear map. ReLU zeros negative hidden values. |
CrossEntropyLoss | Compare raw class scores with correct IDs. | Logits [N,K] and targets [N]. Do not add softmax first. |
backward / optimizer.step | Compute gradients, then update weights. | Clear old gradients before each ordinary batch update. |
Conv2d / MaxPool2d / Flatten | Extract local features, reduce spatial size, prepare a head. | Trace channels, height and width before choosing a linear input size. |
eval / no_grad | Switch layer behavior and disable gradient recording. | Both are needed for ordinary validation; neither performs a weight update. |
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
CNN shape tracer
Broadcasting checker
Compare the train–validation relationship
Underfitting: both losses remain high.
Final train 0.7597; validation 0.84.
Balanced illustration: both losses fall, with a modest gap.
Final train 0.0937; validation 0.174.
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
- Confusing a sample and a batch: an RGB sample is
[3,H,W]; a batch addsNin front. - Assuming ReLU forbids negative predictions: a later linear output can still be negative.
- Trusting training loss alone: if training improves while validation worsens, check overfitting and split leakage.
- Guessing CNN dimensions: each 2× pooling stage roughly halves height and width; verify the actual output shape.
- File / indexDataset.__getitem__ selects one source and label.
- Decode + transformInside that access: decode pixels, resize, convert and normalize.
- Return sampleOne tensor [C,H,W] and its target.
- Collate in DataLoaderGroup samples into [N,C,H,W] and batch targets.
- Input[N,3,32,32]
- Conv + ReLU[N,32,32,32] with padding 1
- Pool 2×[N,32,16,16]
- Conv + ReLU[N,64,16,16] with padding 1
- Global pool + head[N,64,1,1] → [N,64] → [N,K]

