Start with an example: What actually happens when a model learns?
Suppose you want to predict whether a flower belongs to one of two species using four numerical measurements. You could write rules yourself, or you could give examples to a neural network and let it adjust its weights.
In PyTorch, a training iteration usually follows a repeatable sequence: convert examples into tensors, run the model to get predictions, calculate a loss that measures the prediction error, use automatic differentiation to calculate gradients, and ask an optimizer to update the weights. The next iteration starts with the updated weights.
This is useful because you can inspect every step. PyTorch does not make a bad dataset good, and a falling training loss does not prove the model will work on unseen examples. Keeping a separate test set and choosing a task-appropriate metric remain your responsibility.
PyTorch is an open-source framework for numerical computing and machine learning. It provides multidimensional arrays called tensors, operations that can run on CPUs or supported accelerators, automatic differentiation for computing gradients, and modules for constructing and training neural networks.
A useful way to learn PyTorch is to follow one model from its inputs to its predictions and then through training, evaluation, and deployment preparation. The framework handles many mathematical and computational details, but it does not choose an appropriate dataset, model, loss function, or evaluation strategy for you.
1. The components of a PyTorch project
| Component | Purpose | Typical PyTorch API |
|---|---|---|
| Tensor | Store numerical data and learned parameters | torch.Tensor, torch.tensor |
| Dataset | Define how individual examples are accessed | torch.utils.data.Dataset |
| DataLoader | Organize examples into batches | torch.utils.data.DataLoader |
| Model | Define the transformations from input to output | torch.nn.Module |
| Layers | Provide reusable learnable operations | torch.nn.Linear, torch.nn.ReLU |
| Loss function | Measure the discrepancy between outputs and targets | torch.nn.CrossEntropyLoss |
| Autograd | Compute derivatives of tensor operations | loss.backward() |
| Optimizer | Update parameters using gradients | torch.optim.Adam, torch.optim.SGD |
| Evaluation mode | Control the behavior of certain layers | model.eval() |
| Checkpoint | Preserve model parameters for later use | state_dict(), torch.save() |
2. Tensors, shapes, and data types
A tensor is a multidimensional collection of values. A scalar has zero axes, a vector has one, and a matrix has two. Larger tensors can represent batches of images, sequences, or other structured numerical data.
import torch
scalar = torch.tensor(3.0)
vector = torch.tensor([2.0, 4.0, 6.0])
matrix = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(scalar.shape) # torch.Size([])
print(vector.shape) # torch.Size([3])
print(matrix.shape) # torch.Size([2, 2])
print(matrix.dtype) # torch.float32
The shape indicates the length along each axis. Shape compatibility matters: a network expecting four input features cannot directly process an input with five features.
For a dense classifier, the most common conventions are:
- Input features:
[batch_size, num_features]. - Model outputs, or logits:
[batch_size, num_classes]. - Integer class labels:
[batch_size], with values from0tonum_classes - 1.
PyTorch usually represents neural-network weights and inputs as floating-point tensors. For CrossEntropyLoss, class-index targets are integer tensors with dtype torch.long. Do not assume all data types are interchangeable.
Devices
A tensor resides on a device, typically the CPU or an available accelerator. Operations generally require their operands to be on compatible devices.
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = torch.randn(4, 3).to(device)
print(x.device)
This simple choice uses CUDA when available and otherwise falls back to CPU. Other supported backends, including Apple’s MPS, may be available on some installations. Accelerator availability depends on compatible hardware and how PyTorch was installed. For installation-specific commands, consult the official PyTorch installation instructions rather than assuming one command fits every computer.
3. Build a model with nn.Module
A module is a reusable model component. To define a network, subclass torch.nn.Module, construct its layers in __init__, and describe the forward computation in forward.
import torch
from torch import nn
class SmallClassifier(nn.Module):
def __init__(self, input_features=2, hidden_features=16, classes=2):
super().__init__()
self.network = nn.Sequential(
nn.Linear(input_features, hidden_features),
nn.ReLU(),
nn.Linear(hidden_features, classes),
)
def forward(self, x):
return self.network(x)
model = SmallClassifier()
example = torch.randn(5, 2)
logits = model(example)
print(logits.shape) # torch.Size([5, 2])
The first linear layer transforms two features into a 16-dimensional hidden representation. The ReLU activation introduces nonlinearity, allowing the network to learn more than a single linear decision boundary. The final layer produces two scores per example.
These scores are logits, not necessarily probabilities. nn.CrossEntropyLoss accepts logits directly and internally performs the log-softmax-related calculation needed for multiclass classification. Adding a softmax before that loss is unnecessary and can harm numerical stability.
Parameters and buffers
model.parameters() yields registered learnable parameters, such as weights and biases, for the optimizer. model.state_dict() holds the model’s registered parameter and persistent buffer state, such as running statistics in batch-normalization layers. Layers assigned as module attributes are registered automatically.
4. Automatic differentiation with autograd
During training, PyTorch records differentiable operations involving tensors that require gradients. Calling backward() on a scalar loss computes the gradients needed to update model parameters.
For a scalar parameter and loss , the quantity of interest is
A small example makes the mechanism visible:
import torch
w = torch.tensor(2.0, requires_grad=True)
loss = (w - 5.0) ** 2
loss.backward()
print(w.grad.item()) # -6.0
Here . Its derivative is , which is when . Autograd computes that gradient from the recorded operations.
Important: PyTorch usually accumulates gradients in each parameter’s .grad field. A training loop should clear old gradients before computing new ones, commonly with optimizer.zero_grad().
5. Datasets, batching, and data leakage
A Dataset describes how to obtain examples and their corresponding targets. A DataLoader creates batches and can shuffle the training order. Mini-batches allow parameter updates without processing the full dataset at once.
Split data before fitting preprocessing transformations. For real datasets, estimate scaling parameters only from the training portion, then apply them unchanged to validation and test data. Fitting a scaler on all observations leaks information from held-out data into model development.
The following complete example uses synthetic data generated directly in PyTorch. Because its features are already on comparable scales, no feature scaling step is necessary.
6. Complete example: train a two-class classifier
The task is to predict whether the sum of two numerical features is positive. This is a deliberately simple, synthetic problem designed to make the training mechanics easy to inspect, not a benchmark for real-world model performance.
Run the following script with PyTorch installed. It creates separate training and test examples, constructs a network, trains it, evaluates it, and saves its weights.
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
# Reproducible random-number generation for this demonstration.
torch.manual_seed(42)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Independent synthetic training and test sets.
x_train = torch.randn(1200, 2)
y_train = (x_train[:, 0] + x_train[:, 1] > 0).long()
x_test = torch.randn(300, 2)
y_test = (x_test[:, 0] + x_test[:, 1] > 0).long()
train_loader = DataLoader(
TensorDataset(x_train, y_train),
batch_size=64,
shuffle=True,
)
test_loader = DataLoader(
TensorDataset(x_test, y_test),
batch_size=128,
shuffle=False,
)
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(2, 16),
nn.ReLU(),
nn.Linear(16, 2),
)
def forward(self, x):
return self.layers(x)
model = Classifier().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# Training: compute predictions, loss, gradients, and updates.
for epoch in range(15):
model.train()
running_loss = 0.0
total = 0
for features, labels in train_loader:
features = features.to(device)
labels = labels.to(device)
optimizer.zero_grad()
logits = model(features)
loss = criterion(logits, labels)
loss.backward()
optimizer.step()
batch_size = labels.size(0)
running_loss += loss.item() * batch_size
total += batch_size
print(f"Epoch {epoch + 1:02d}: training loss = {running_loss / total:.4f}")
# Evaluation: no gradient updates and no training-specific behavior.
model.eval()
correct = 0
seen = 0
with torch.inference_mode():
for features, labels in test_loader:
features = features.to(device)
labels = labels.to(device)
logits = model(features)
predictions = logits.argmax(dim=1)
correct += (predictions == labels).sum().item()
seen += labels.size(0)
print(f"Test accuracy: {correct / seen:.2%}")
# Save model weights, not a serialized Python model object.
torch.save(model.state_dict(), "classifier-weights.pth")
Understand the training loop line by line
model.train()enables training behavior for modules that distinguish training from evaluation, such as dropout and batch normalization.optimizer.zero_grad()clears gradients left from earlier updates.model(features)performs forward propagation and returns logits.criterion(logits, labels)computes the classification loss using the true labels.loss.backward()computes derivatives of the loss with respect to model parameters.optimizer.step()uses those gradients to update the parameters.- The loop repeats for all batches and epochs.
The reported training loss is an example-weighted average across the epoch, rather than an unweighted mean of batch means. Weighting matters because the last batch may be smaller than the others.
Why evaluate on separate data?
A model can memorize training observations or learn dataset-specific patterns. The separate test set estimates how well it performs on new examples drawn from the same synthetic process. In a realistic project, use a validation set for model selection and hyperparameter tuning, reserving the test set for final evaluation.
Accuracy is easy to interpret for the balanced synthetic task. On imbalanced or high-stakes classification problems, also consider precision, recall, confusion matrices, probability calibration, and error costs.
7. Load the model and run inference
To reuse saved weights, create the same model architecture and load the state dictionary. Loading onto the CPU is a portable approach when a GPU is unavailable.
import torch
# This assumes the Classifier definition from the preceding example.
loaded_model = Classifier()
weights = torch.load(
"classifier-weights.pth",
map_location="cpu",
weights_only=True,
)
loaded_model.load_state_dict(weights)
loaded_model.eval()
new_example = torch.tensor([[0.8, -0.2]], dtype=torch.float32)
with torch.inference_mode():
logits = loaded_model(new_example)
probabilities = torch.softmax(logits, dim=1)
predicted_class = probabilities.argmax(dim=1).item()
print("Predicted class:", predicted_class)
print("Class probabilities:", probabilities.tolist())
model.eval() changes relevant module behavior; torch.inference_mode() disables autograd-related recording and can reduce inference overhead. They serve different purposes, so use both during ordinary inference.
weights_only=True is recommended for loading compatible weight checkpoints. Do not load untrusted serialized files casually: serialization formats and their loading mechanisms can present security risks.
8. Choose losses and output shapes correctly
The loss function must match the problem and the model’s outputs.
| Task | Typical model output | Common loss |
|---|---|---|
| Multiclass classification | One logit per class: [batch, classes] | nn.CrossEntropyLoss() |
| Binary classification with one logit | One logit per example: [batch, 1] | nn.BCEWithLogitsLoss() |
| Numerical regression | Continuous prediction: [batch, targets] | nn.MSELoss() or nn.L1Loss() |
For two-class classification, either two logits with cross-entropy or one logit with binary cross-entropy can be used, but they require different target formats. BCEWithLogitsLoss expects floating-point binary targets of a compatible shape and incorporates the sigmoid operation internally.
A probability is not the same as a raw logit. Apply softmax for interpreting multiclass logits as probabilities during inference, not before CrossEntropyLoss. Apply sigmoid when converting a single binary logit to a probability for inference, not before BCEWithLogitsLoss.
9. Common errors and how to diagnose them
| Symptom | Likely issue | First check |
|---|---|---|
| Shape mismatch | Incorrect input width or target shape | Print features.shape, logits.shape, and labels.shape |
| Device mismatch | Data and model on different devices | Check .device and move all tensors consistently |
| Dtype error | Labels or inputs use unsuitable types | Inspect .dtype; cross-entropy class indices need torch.long |
| Training loss does not decrease | Learning rate, architecture, labels, or gradient update problem | Check optimizer steps and gradient values |
| Training looks good but test results are poor | Overfitting or distribution mismatch | Compare train/validation metrics and inspect leakage |
| Out-of-memory error | Batch or model is too large | Reduce batch size or model size |
| Unstable evaluation | Training-mode layers remain active | Call model.eval() before inference |
A good debugging strategy is to make the network overfit a tiny clean batch. If it cannot learn even a handful of examples, inspect the labels, loss, shapes, gradients, and optimizer before attempting a large-scale experiment. Overfitting a tiny batch is a diagnostic technique, not a valid final evaluation method.
10. From a tutorial to a reliable training project
A real project adds practices that the demonstration deliberately leaves out:
- Data provenance: Document where examples came from, how labels were created, and whether collection and use are authorized.
- Appropriate splits: Split by time, user, or group when independent random splitting would cause leakage.
- Preprocessing: Fit transformations using training data only and save everything necessary to reproduce them.
- Validation: Track held-out metrics during development; use early stopping or model selection without repeatedly consulting the test set.
- Experiment tracking: Record the code version, configuration, random seeds, dataset version, and results.
- Checkpoints: Save model and optimizer state when resuming training is required, not just inference weights.
- Monitoring: Check accuracy, latency, failures, input distributions, and relevant operational constraints after deployment.
- Security: Validate inputs and control access to models, checkpoints, datasets, and inference endpoints.
A fixed random seed improves reproducibility but does not guarantee identical results across every machine, accelerator, library version, or operation.
CPU and GPU considerations
PyTorch can execute many workloads on CPUs and supported accelerators. GPUs are especially useful for large tensor operations and neural networks, but small examples may run adequately on a CPU. Hardware acceleration does not automatically improve model quality; it mainly changes execution speed and available computational capacity.
Batch size trades off memory use, update frequency, and computational efficiency. Larger batches are not universally better. Monitor the model’s evaluation performance and actual training behavior rather than choosing batch size solely by GPU capacity.
11. How PyTorch relates to other AI tools
NumPy is useful for numerical arrays and conventional scientific computing. PyTorch tensors offer accelerator support and automatic differentiation for many numerical operations. Scikit-learn provides a broad collection of conventional machine-learning estimators and utilities. PyTorch is commonly selected when defining custom differentiable models and training neural networks, including CNNs, RNNs, and Transformers.
You do not need to reimplement automatic differentiation or every layer from scratch to understand their mathematics. You should, however, recognize what the abstractions compute and know how to test the assumptions behind them.
12. Practice exercises
- Change the hidden-layer width from 16 to 4 and then to 64. Compare training loss and test performance across several runs.
- Replace Adam with
torch.optim.SGDand test several learning rates. Record which settings converge reliably. - Add a validation set and choose the number of epochs without inspecting the final test labels.
- Adapt the example to single-logit binary classification using
nn.BCEWithLogitsLoss; adjust the labels and output shape accordingly. - Modify the saved-checkpoint workflow so training can resume with the optimizer state and current epoch number.
13. Related PlainCS articles
Prerequisites
- Python for Artificial Intelligence
- NumPy, Arrays, and Tensors
- Neural Networks: Neurons, Layers, Weights, and Biases
- Forward Propagation and Backpropagation
- Training Neural Networks: Loss, Optimizers, and Regularization
- Data Splitting, Labeling, and Leakage
Continue learning
- Convolutional and Recurrent Neural Networks
- Computer Vision Fundamentals
- The Transformer Architecture
- Model Serving and Deployment
- Inference Optimization and Quantization
- AI Knowledge Map
Some continuation links lead to articles planned in the PlainCS knowledge map and will become active when those pages are published.
14. References and further reading
- PyTorch: Learn the Basics, official introduction to tensors, data loading, models, autograd, optimization, and saving.
- PyTorch: Quickstart, end-to-end model training and evaluation.
- PyTorch: Automatic Differentiation, computation graphs and gradient calculation.
- PyTorch: Saving and Loading Models, state dictionaries and checkpoints.
- PyTorch: CrossEntropyLoss, supported inputs, class targets, and loss behavior.
- PyTorch: Get Started, installation instructions for supported platforms and hardware.
Related articles in
- Convolutional and Recurrent Neural Networks — Understand convolutional networks for spatial data and recurrent networks for sequences, including CNN filters, RNN state, LSTMs, GRUs, and practical PyTorch examples.
- Forward Propagation and Backpropagation — Learn how neural networks compute predictions with forward propagation and calculate parameter gradients with backpropagation, using the chain rule and a worked example.
- Neural Networks: Neurons, Layers, Weights, and Biases — Understand the fundamental components of artificial neural networks, including neurons, weights, biases, layers, activation functions, and how networks represent learned patterns.