PyTorch stops at a Linear layer because the feature count is wrong
Your error
RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x9216 and 4096x128)2 more lines it can showFix it fast
Most common cause, 1 of 3in_features does not match what the layers before it produce
Use the second number from the message as in_features.
self.fc1 = nn.Linear(9216, 128) # B from the error message
# or let PyTorch infer it:
self.fc1 = nn.LazyLinear(128)Short answer
RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x9216 and 4096x128) means the tensor reaching an nn.Linear layer has 9216 features per sample while the layer was built for in_features=4096. Set in_features to the second number, use nn.LazyLinear, or fix the input size or flatten call. Applies to PyTorch 2.x; 2.15 prefixes the op name, such as addmm:.
Which cause do you have?
Print the shape that arrives at the Linear layer next to the size the layer expects. In the error (AxB and CxD), A is the number of rows, B the features that arrived, C the layer's in_features and D its out_features. A equal to your batch size points to cause 1 or 2; A equal to 1 points to cause 3.
# inside forward(), on the line before self.fc1(x)
print("into fc1:", tuple(x.shape), "fc1 expects:", self.fc1.in_features)Then find the line you see in this list and open its fix:
- 1in_features does not match what the layers before it produce
The first number equals your batch size, and the error shows up on the very first batch, even with inputs of the size the model was designed for - 2The images are a different size from the ones the model was built for
Training or a dummy batch works, and the error appears with new images; the second number changes when the image size changes - 3torch.flatten merged the batch dimension into the features
The first number in the message is 1 and the second is the batch size times the per-sample feature count
What does the error look like?
RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x9216 and 4096x128)RuntimeError: addmm: mat1 and mat2 shapes cannot be multiplied (64x9216 and 4096x128)RuntimeError: mm: mat1 and mat2 shapes cannot be multiplied (1x589824 and 9216x128)
Cause 1 of 3
in_features does not match what the layers before it produce
You seeThe first number equals your batch size, and the error shows up on the very first batch, even with inputs of the size the model was designed for
Check
The shapes cannot be multiplied because nn.Linear only accepts input whose last dimension equals in_features; its weight has the shape (out_features, in_features). A number copied from a tutorial, or one computed for a different stack of conv and pooling layers, leaves the two sizes apart.
python -c "import torch; from model import Net; m = Net(); print(m.fc1)"Fix
Use the second number from the message as in_features. When you are still changing the layers above it, nn.LazyLinear works out in_features from input.shape[-1] on the first forward pass, so only out_features is needed.
self.fc1 = nn.Linear(9216, 128) # B from the error message
# or let PyTorch infer it:
self.fc1 = nn.LazyLinear(128)Verify
A forward pass with a dummy batch returns shape (batch, out_features).
python -c "import torch; from model import Net; print(Net()(torch.randn(2, 1, 28, 28)).shape)"Confirmed by docs.pytorch.org
Cause 2 of 3
The images are a different size from the ones the model was built for
You seeTraining or a dummy batch works, and the error appears with new images; the second number changes when the image size changes
Check
Each Conv2d output height and width is computed from the input height and width, so a larger image leaves more values per sample after flattening. A checkpoint trained on 28x28 inputs therefore fails on 32x32 ones even though the code did not change.
# just before model(images) in the failing script
print("input batch:", tuple(images.shape))Fix
Send every input through the same resize step used for the training data, so height and width match what the model was built for. Changing in_features instead would not fit the trained weights. A guard in forward() turns a silent size drift into a clear message.
def forward(self, x):
assert x.shape[-2:] == (28, 28), f"expected 28x28 input, got {tuple(x.shape)}"
...Verify
The shape printed before fc1 is the same for training and new data, and the forward pass completes.
python predict.py sample.pngConfirmed by docs.pytorch.org
Cause 3 of 3
torch.flatten merged the batch dimension into the features
You seeThe first number in the message is 1 and the second is the batch size times the per-sample feature count
Check
torch.flatten starts at dimension 0 by default, so calling it with only the tensor turns a whole batch into one long vector. PyTorch then treats that vector as a single row, which is why the message starts with 1 and carries batch-size times more values than the layer expects.
grep -n "flatten(" model.pyFix
Pass start_dim=1 so dimension 0, the batch, stays as it is and each sample keeps its own row.
x = torch.flatten(x, 1)Verify
The shape printed before fc1 now starts with the batch size.
python train.py --epochs 1Confirmed by docs.pytorch.org
How do I stop it coming back?
- Add a unit test that runs one dummy batch of the real input size through the model and asserts the output shape.
- Keep the input size in one config value used by both the transforms and the model definition.
- Prefer nn.LazyLinear for the first fully connected layer while the convolutional part is still changing.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.