RuntimeError size mismatch m1 a x b, m2 c x d
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
The size mismatch runtime error in tensor frameworks usually means matrix multiplication was attempted with incompatible inner dimensions. In deep learning code, this often appears between flatten output and a linear layer, or after changing convolution settings without updating downstream shapes. The fastest fix is disciplined shape tracing, not trial-and-error edits.
Understand the Core Matrix Rule
For matrix multiplication between A and B:
Ashape ism x n,Bshape isn x p,- output shape is
m x p.
The inner dimensions must match. If they do not, frameworks raise errors such as size mismatch.
Minimal PyTorch example:
Most Common Deep Learning Cause
A very common failure path:
- convolution and pooling change feature map size,
- tensor is flattened,
nn.Linear(in_features, out_features)still uses oldin_features.
If flatten size is wrong, first linear layer fails immediately.
The 8 * 15 * 15 value depends on input resolution and upstream layer parameters.
Shape Debugging Workflow
Use explicit shape prints or assertions at module boundaries.
For production-quality checks, raise descriptive errors early.
This turns opaque runtime crashes into actionable diagnostics.
Robust Fix Patterns
Useful ways to avoid manual mistakes:
- compute flatten size with a dummy forward pass in model init,
- use adaptive pooling to normalize spatial dimensions,
- keep shape-transform logic in one helper method.
Dummy-pass pattern:
This is safer when upstream architecture changes often.
Batch and Sequence Shape Confusion
Another frequent source is swapped dimensions in sequence models.
Example confusion:
- expected
batch x features, - got
sequence x batch x features.
Always document expected shape convention per module and keep it consistent.
Quick Shape Assertions in Training Loops
In custom training loops, add lightweight assertions before forward pass and before loss computation. Early checks prevent long runs from failing deep in the stack.
These guards are especially useful when input preprocessing changes independently from model code.
Common Pitfalls
- Editing conv or pooling layers without updating linear input size.
- Using incorrect flatten call and collapsing batch dimension by accident.
- Assuming input image size never changes across data loaders.
- Ignoring dimension ordering conventions in sequence models.
- Debugging only final error line instead of tracing intermediate shapes.
Summary
- Size mismatch errors are shape-contract violations, not random runtime issues.
- Inner dimensions must align for matrix multiplication.
- Trace shapes at each stage, especially before linear layers.
- Use adaptive patterns or dummy-forward computation to prevent manual misconfiguration.
- Keep explicit shape conventions and assertions to make failures easy to diagnose.
Related reading
- Scaling an iterative, bitwise algorithm to solve the Towers of Hanoi using X discs and Y towers
- Scikit-Learn Decision Tree Probability of prediction being a or b?
- Scikit-learn Ridge classifier extracting class probabilities
- search for interval overlap in list of intervals?
- RuntimeError thread.__init__ not called when subclassing threading.Thread
- RuntimeError You cannot use AsyncToSync in the same thread as an async event loop
- RuntimeError Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graphTrue
- RuntimeError Unable to create link name already exists Keras

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.