stack vs cat in PyTorch
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
torch.stack and torch.cat both combine tensors, but they solve different shape problems. cat joins tensors along an existing dimension, while stack creates a new dimension and therefore increases the tensor rank by one.
This difference sounds small, but it changes the meaning of the result. Many model-shape bugs in PyTorch come from using stack when the code really needed cat, or vice versa.
cat Joins Along an Existing Dimension
Use torch.cat when the tensors already have the right rank and you want to extend one of their existing axes:
Here the tensors stay rank-2. Only the chosen dimension grows.
stack Creates a New Dimension
Use torch.stack when you want to bundle same-shaped tensors into a new axis:
The rank increases from 2 to 3 because a new dimension is inserted.
One useful mental model is that stack is like applying unsqueeze to each tensor first and then concatenating.
Know the Input Rules
The compatibility rules differ:
- '
catrequires all shapes to match except on the concatenation dimension' - '
stackrequires all tensors to have exactly the same shape'
This explains why stack is often used to build batches from equal-sized samples, while cat is more common for feature fusion.
Common Deep Learning Use Cases
Batch assembly from equal-size samples:
Channel-wise feature fusion:
If you used stack in that second case, you would introduce an unwanted extra dimension instead of expanding the channel axis.
Think About Performance and Memory
Both operations allocate a new tensor. That means repeatedly calling cat or stack inside a loop is usually inefficient:
This is much better than growing the result incrementally with one concatenation per iteration. The same advice applies to stack: collect first, merge once.
Also remember that merged tensors must agree on device and dtype. Shape compatibility alone is not enough.
Common Pitfalls
The biggest mistake is choosing based on what "seems to work" rather than on the shape contract of the next layer. Always check the output shape explicitly.
Another common issue is using stack to fuse features when the correct operation was concatenation along an existing channel or time dimension.
People also build tensors incrementally in loops and pay repeated allocation costs. Both cat and stack are much happier when called once on a collected list.
Finally, debug merge problems by inspecting shape, dtype, and device together. A mismatch in any one of those can cause a runtime failure.
Summary
- '
torch.catjoins tensors along an existing dimension.' - '
torch.stackcreates a new dimension and increases rank.' - Use
stackfor batch assembly from equal-shaped samples. - Use
catfor extending channels, time steps, or other existing axes. - Collect tensors first and merge once to avoid unnecessary allocation overhead.
Related reading
- Stateful LSTM - Hidden State transfer between and within batches Keras
- Stateful LSTM and stream predictions
- Stateful LSTM When to reset states?
- Stopping and starting a deep learning google cloud VM instance causes tensorflow to stop recognizing GPU
- Suboptimal convergence in PyTorch compared to TensorFlow when using Adam optimizer
- Taking subsets of a pytorch dataset
- Stack with find-min/find-max more efficient than On?
- Stackless pre-order traversal in a binary tree

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.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.