Topic 2 of 5 · 4 min read
Tracing a forward pass through layer shapes
Goal: Trace tensor shapes through a small multilayer network from an input batch to its softmax output.
A forward pass is a chain of matrix multiplies, bias additions and activations; if you can write the shape after each step, you can find most network bugs without running anything.
Check yourself · 1 of 3
A batch X of shape (64, 100) goes through a layer with weight matrix W of shape (100, 30). What is the shape of X @ W?
Why it matters
The most common error message in deep learning is a shape mismatch. The second most common problem is a model that runs but computes the wrong thing because a dimension was swapped. Tracing shapes on paper catches both.
How to trace one
Use batch size N, input features D, hidden width H and C classes. A network for 28 by 28 images flattened to 784 values, with 128 hidden units and 10 classes, and a batch of 32:
- Input X: (32, 784)
- First layer: X @ W1 + b1, with W1 of shape (784, 128) and b1 of shape (128). The result is (32, 128). The bias is added to every row (broadcasting).
- ReLU: applied per element, shape stays (32, 128).
- Second layer: @ W2 + b2, with W2 of shape (128, 10). The result is (32, 10). These raw scores are the logits.
- Softmax across the class axis turns each row into probabilities that sum to 1. Shape stays (32, 10).
The rule: the inner dimensions of a matrix multiply must match, and the outer ones become the result. (32, 784) @ (784, 128) works. (32, 784) @ (128, 784) does not.
Counting parameters
Layer one has 784 * 128 weights plus 128 biases, which is 100,480. Layer two has 128 * 10 + 10 = 1,290. The model has 101,770 parameters. Activations and softmax add none.
In PyTorch
import torch
from torch import nn
model = nn.Sequential(nn.Flatten(), nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))
x = torch.randn(32, 1, 28, 28)
logits = model(x) # (32, 10)
probs = logits.softmax(dim=1) # each row sums to 1
Note that nn.Linear(784, 128) stores its weight as (128, 784) and computes x @ W.T. The shapes you write in the constructor are (in, out); the stored tensor is (out, in).
Before and after
Weak: "The data goes through the layers and a prediction comes out."
Better: "(32, 1, 28, 28) is flattened to (32, 784), mapped to (32, 128), then to (32, 10) logits, then softmax over dim 1."
What goes wrong
- Softmax over the wrong axis. With dim=0 the columns sum to 1 across the batch, not the classes across each example. The code runs and the numbers are meaningless.
- Applying softmax and then a loss that expects logits. PyTorch's
CrossEntropyLossapplies log-softmax itself; feeding it probabilities trains badly. - Forgetting to flatten an image before a Linear layer.
Examples
Finding the shape bug on paper
model = nn.Sequential(
nn.Linear(784, 128), nn.ReLU(),
nn.Linear(64, 10),
)
The first layer outputs 128 features, but the second expects 64. Tracing gives (N, 784) to (N, 128), and then (N, 128) @ a layer expecting 64 inputs fails. Fix: nn.Linear(128, 10).
Softmax axis
logits = model(x) # (32, 10)
probs = logits.softmax(dim=0)
probs.sum(dim=1)[:3] # not 1.0
With dim=0 each column sums to 1 over the 32 examples. Use dim=1 so each example's 10 class probabilities sum to 1.
Key points
- Inner dimensions of a matrix multiply must match; the outer ones form the output shape.
- A batch adds a leading dimension N that passes through every layer unchanged.
- Logits are the raw scores of the last layer; softmax over the class axis turns each row into probabilities summing to 1.
- A Linear layer from D to H has D * H weights plus H biases.
- Softmax on the wrong axis runs without error and gives wrong results.
Common mistakes
- Applying softmax over the batch axis instead of the class axis.
- Passing softmax output into a loss function that expects raw logits.
- Skipping the flatten step between image tensors and Linear layers.
- Counting parameters without the bias vectors.
Check yourself · 2 of 3
What are logits in a classifier?
Check yourself · 3 of 3
A model has Linear(20, 50) then ReLU then Linear(50, 3). How many parameters does it have?
Practice items, not counted towards your mastery.
Start here
- Neural networks series (3Blue1Brown) (opens in a new tab)VideoFree
Animated walk through neurons, layers, gradient descent and backpropagation with the chain rule drawn out.
- Neural Networks and Deep Learning (Michael Nielsen) (opens in a new tab)BookFree
Free online book that derives backpropagation step by step and builds a digit classifier in Python.
- Deep Learning (Goodfellow, Bengio, Courville) (opens in a new tab)BookFree
The standard textbook; chapters on feedforward networks, optimization and regularization.
More for this topic
- Learn the Basics (PyTorch tutorials) (opens in a new tab)DocsFree
Official walkthrough of tensors, building a model, autograd and the training loop.