Guides
Common PyTorch shape errors and how to fix them
Almost every PyTorch shape error means that a layer was built for one tensor shape and receives another: print x.shape before the failing line, compare it with what the layer expects (in_features, in_channels, the target of the loss) and change the layer or the reshape before it. Below are the most common messages, each with its cause, the fix and what Brick DNN shows before anything runs.
How to read a shape error
PyTorch tensors carry the batch as their first dimension: a batch of 32 grey images of 28 × 28 pixels is [32, 1, 28, 28], and the output of a classifier for 10 classes is [32, 10]. Layers know only the sizes they were created with, so a mismatch shows up when data first flows through them, in the forward pass or in the loss. Add print(x.shape) in forward before the failing layer, and the numbers in the message usually tell you which side is wrong.
In Brick DNN every layer shows its output shape while you build: the editor checks the network again a quarter of a second after every change, marks the layer that does not fit with a message, and the layers after it have no shape until it is fixed.
mat1 and mat2 shapes cannot be multiplied (32x1568 and 784x10)
Cause: the in_features of an nn.Linear (784 here, the first number of the second matrix) differ from the size of the last dimension of its input (1568 = 32 channels × 7 × 7 after two poolings), usually after a change to the convolutions before it.
Fix: set in_features to the second number of the first matrix, here nn.Linear(1568, 10), and flatten the tensor first (nn.Flatten()). nn.LazyLinear(10) infers it from the first batch instead.
In Brick DNN: Input features of a Linear layer is left empty and inferred from the incoming shape, so this cannot happen. If you type a value that does not fit, the layer is marked: Input features is set to 784, but the incoming tensor has 1568 features in its last dimension. Clear the field to infer it automatically.
Expected input batch_size (128) to match target batch_size (32)
Cause: the output of the network has a different first dimension than the targets. Almost always a reshape such as x.view(-1, 784) moved features into the batch: a batch of 32 feature maps [32, 16, 14, 14] holds 32 × 3136 values, and view(-1, 784) turns them into 128 rows.
Fix: flatten everything except the batch, with x.flatten(1), x.view(x.size(0), -1) or nn.Flatten(), and set the next Linear layer to the resulting size (3136).
In Brick DNN: Flatten and Reshape always keep the batch: the generated code uses nn.Flatten() and x.reshape(x.size(0), …). A Reshape whose target has a different number of values is marked: Cannot reshape (16, 14, 14) (3136 values) into (784) (784 values).
When an output has more dimensions than the data allows (a Linear layer after a convolution without Flatten gives (32, 7, 10)), the check before training refuses it with a message that begins The network outputs shape (32, 7, 10), but
and says how many values the last layer should output.
Given groups=1, weight of size [16, 1, 3, 3], expected input[32, 3, 28, 28] to have 1 channels, but got 3 channels instead
Cause: the in_channels of an nn.Conv2d (1, the second number of the weight) differ from the channel dimension of its input (3): colour images reach a network built for grey ones, or a convolution follows one with a different out_channels. Its relative Expected 3D (unbatched) or 4D (batched) input to conv2d, but got input of size: [32, 784]
means that flat vectors reach a convolution.
Fix: set in_channels to the channels of the input (or to the out_channels of the layer before), or convert the images, e.g. with transforms.Grayscale(). A flat input must be reshaped to [N, C, H, W] first.
In Brick DNN: Input channels is inferred like Input features; a typed value that does not fit gives Input channels is set to 1, but the incoming tensor has 3 channels. Clear the field to infer it automatically.
A flat input is marked with Conv2d expects a 3-D (channels, height, width) input, but got shape (784).
For training, images are converted to the channels of the Input layer and resized to its height and width.
expected scalar type Long but found Float
Cause: nn.CrossEntropyLoss got its class targets as floating-point numbers. With one score per class it expects the index of the right class as an integer (torch.long).
Fix: convert the targets with y.long(), or create them as torch.tensor(labels, dtype=torch.long). If the targets really are decimal numbers, the task is a regression: one output and nn.MSELoss.
In Brick DNN: the training makes the targets itself, one class index per row (text labels are numbered in alphabetical order). A target column of decimal numbers for a network with one output per class is refused before the start: The target column 'price' contains decimal numbers, which is a regression task. Give the last layer 1 output, or use class indices 0..9 as targets.
0D or 1D target tensor expected, multi-target not supported
Cause: the class targets have the shape [32, 1] instead of [32], often because they were read as a column of a table. Its relative IndexError: Target 10 is out of bounds.
means that a class index is not below the number of outputs, e.g. labels 1 to 10 for 10 outputs.
Fix: drop the extra dimension with y.squeeze(1) or y.view(-1). Class indices run from 0 to the number of classes − 1: subtract 1 from labels that start at 1, or give the last layer more outputs.
In Brick DNN: the targets always have one index per row, and their range is checked before training: The target column 'label' holds values from 1 to 10, but with 10 outputs the class indices must be between 0 and 9. Set the last layer to 11 outputs or relabel the classes.
view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
Cause: .view() never copies data, so it only works on a tensor whose values lie in memory in the order of the new shape. After transpose, permute or some slices they do not.
Fix: use .reshape(), which copies when it must, or call .contiguous() before .view(). To flatten, x.flatten(1) does the right thing.
In Brick DNN: the generated code does not call .view(): Flatten becomes nn.Flatten() and Reshape x.reshape(…), so the exported script does not raise this error. It can still appear when you add a transpose and a view to the script by hand.
Questions
Why does PyTorch report shape errors only when the code runs?
A layer such as nn.Linear(784, 10) stores only its own sizes; the shape of the data it receives is known only when a tensor flows through it. So a mismatch shows up in the forward pass or in the loss, often after the data has been loaded.
How do I find the shape after every layer?
Print x.shape after each step of forward, or register a forward hook on the modules and print the shapes of their outputs. In Brick DNN every layer shows its output shape and parameter count on the canvas while you build.
Does Brick DNN need PyTorch to check the shapes?
No. The check computes every shape from the layers and their settings, without running a tensor through the network. The exported script is plain PyTorch with the same layers and settings.
Examples to start from
Small CNN for MNIST
Two convolution blocks and a classifier head: about 99 % test accuracy on MNIST.
Tabular regression
Predicts one number from 8 numeric features; the script trains on a CSV file.
Residual CNN for CIFAR-10
A ResNet-style block with a skip connection merged by Add, then global average pooling.
More guides
Build a neural network without code and export it to PyTorch
Connect layers on a canvas, let Brick DNN check every shape, and download a PyTorch script that runs on its own.
Tabular data: gradient boosting vs. MLP, and when to use which
How trees and neural networks see a table, what each needs, and how to compare them fairly on the same split.
Image segmentation with a U-Net: from masks to a trained model
From a ZIP file of images and masks to a trained U-Net, with mean IoU, Dice and the predicted masks.
Imbalanced classes: class weights, focal loss, oversampling and the decision threshold
Why accuracy misleads when one class is rare, and the four levers against it: weights, focal loss, oversampling and the threshold.
GDPR-compliant deep learning: training neural networks with data in Europe
Which data needs care under the GDPR, where brickdnn.com stores and trains in Switzerland, and what to do with data that has to stay personal.