Ok the solution was to simply use torch.cat(data,dim=0). Doh. Answer from HaziqRazali on discuss.pytorch.org
🌐
Medium
medium.com › data-scientists-diary › pytorchs-stack-method-a-practical-guide-for-data-scientists-2af8088f40a5
PyTorch’s stack() Method: A Practical Guide for Data Scientists
January 19, 2025 - import torch # Sample features for a time series prediction model feature1 = torch.rand(10, 5) # 10 samples, 5 features feature2 = torch.rand(10, 5) feature3 = torch.rand(10, 5) # Stack features along a new dimension stacked_features = torch.stack([feature1, feature2, feature3], dim=1) print("Stacked Features Shape:", stacked_features.shape) # Output: torch.Size([10, 3, 5]) Explanation In this example, each feature tensor represents different time-series sequences.
🌐
PyTorch Forums
discuss.pytorch.org › t › stacking-a-list-of-tensors-whose-dimensions-are-unequal › 31888
Stacking a list of tensors whose dimensions are unequal - PyTorch Forums
December 11, 2018 - Hello, I have a simple problem where I am trying to stack a list of 2D tensors that have unequal number of rows. For example data is a list of 2D tensors and data[0].size() = (15,2) data[1].size() = (14,2) data[2].size() = (7,2) I tried using torch.stack(data, dim=0) and torch.stack(data, dim=1) ...
🌐
Python Guides
pythonguides.com › pytorch-stack
How to Use PyTorch Stack?
June 19, 2025 - Stacked along dim 0 shape: torch.Size([2, 2, 3]) Stacked along dim 1 shape: torch.Size([2, 2, 3]) Stacked along dim 2 shape: torch.Size([2, 3, 2]) You can refer to the screenshot below to see the output: The dimension we stack along determines where the new dimension is inserted. I often use dimension 1 stacking when working with sequence models like LSTMs. ... When working with real datasets, I sometimes need to combine tensors with different data types.
Top answer
1 of 2
3

If I understand correctly what you're trying to do is stack the outputted mini-batches together into a single batch. My bet is that your last batch is partially filled (only has 16 elements instead of 32).

Instead of using torch.stack (creating a new axis), I would simply concatenate with torch.cat on the batch axis (axis=0). Assuming matrices is a list of torch.Tensors.

torch.cat(matrices).cpu().detach().numpy()

As torch.cat concatenates on axis=0 by default.

2 of 2
1

When we have tensors that differ in size only on the first dimension, as of PyTorch v1.7.0, we can use torch.vstack() to stack it along axis 0. Using torch.stack() fails here because it expects all the tensors to be of same shape.

Here is a reproducible illustration matching your problem description:

# sample tensors (as per your size)
In [65]: t1 = torch.randn([32, 1, 600, 600])
In [66]: t2 = torch.randn([16, 1, 600, 600])

# vertical stacking (i.e., stacking along axis 0)
In [67]: stacked = torch.vstack([t1, t2])

# check shape of output
In [68]: stacked.shape
Out[68]: torch.Size([48, 1, 600, 600])

we get 48 (32 + 16) as the size of first dimension in the result because we're stacking tensors along that dimension.


Note:

You can also initialize the result tensor, say stacked, by explicitly calculating the shape and pass this tensor as a parameter to out= kwarg of torch.vstack() if you want to write the result to a specific tensor, for instance updating the values of existing tensor (of same shape). However, this is optional.

# calculate new shape of stacking
In [80]: newshape = (t1.shape[0] + t2.shape[0], *t1.shape[1:])

# allocate an empty tensor, filled with garbage values
In [81]: stacked = torch.empty(newshape)

# stack it along axis 0 and write the result to `stacked`
In [83]: torch.vstack([t1, t2], out=stacked)

# check shape/size
In [84]: stacked.shape
Out[84]: torch.Size([48, 1, 600, 600])
🌐
Sprintchase
sprintchase.com › home › torch.stack(): concatenating tensors along new dimension
torch.stack(): Concatenating Tensors Along New Dimension
May 12, 2025 - Since, torch.cat() does not have a reshape, it is slightly faster than torch.stack() method because .stack() adds a new dimension, which adds some performance overhead. Here is the code example that demonstrates the difference: import torch tensor1 = torch.tensor([19, 21]) tensor2 = torch.tensor([11, 18]) cat_result = torch.cat([tensor1, tensor2], dim=0) print(cat_result) # Output: tensor([19, 21, 11, 18]) print(cat_result.shape) # Output: torch.Size([4]) stack_result = torch.stack([tensor1, tensor2], dim=0) print(stack_result) # Output: tensor([[19, 21], # [11, 18]]) print(stack_result.shape) # Output: torch.Size([2, 2]) In the case of cat_result, it does not add a new dimension.
🌐
GeeksforGeeks
geeksforgeeks.org › python-pytorch-stack-method
Python PyTorch stack() method - GeeksforGeeks
February 28, 2022 - As the dimension of each input tensor is 2, we can stack the tensors with dimensions 0 and 2. See the differences among the final output tensors with dim = 0, 1, and 2. In this example, we join more than two tensors.
🌐
TutorialsPoint
tutorialspoint.com › how-to-join-tensors-in-pytorch
How to join tensors in PyTorch?
September 14, 2023 - Original tensors: t1: tensor([[1, ... 0, 4], [2, 3, 3]], [[3, 4, 2], [4, 1, 5]]]) Use torch.cat() to concatenate tensors along existing dimensions without changing dimensionality....
🌐
PyTorch Forums
discuss.pytorch.org › t › stack-expects-each-equal-size › 143012
Stack expects each equal size - PyTorch Forums
February 1, 2022 - stack expects each tensor to be equal size but got [7, 768] at entry 0 and [8, 768] at entry 1 ca_embedding = torch.stack(tns_embedding) embeddings.append(ca_embedding) the shape for the first is ca_embedding shape is torch.Size([7, 768]) the shape for the second is ca_embedding shape is torch.Size([8, 768])
Find elsewhere
Top answer
1 of 3
20

Imagine have n tensors. If we stay in 3D, those correspond to volumes, namely rectangular cuboids. Stacking corresponds to combining those n volumes on an additional dimension: here a 4th dimension is added to host the n 3D volumes. This operation is in clear contrast with concatenation, where the volumes would be combined on one of the existing dimensions. So concatenation of three-dimensional tensors would result in a 3D tensor.

Here is a possible representation of the stacking operations for limited dimensions sizes (up to three-dimensional inputs):

Where you chose to perform the stacking defines along which new dimension the stack will take place. In the above examples, the newly created dimension is last, hence the idea of "added dimension" makes more sense.

In the following visualization, we observe how tensors can be stacked on different axes. This in turn affects the resulting tensor shape

  • For the 1D case, for instance, it can also happen on the first axis, see below:

    With code:

    >>> x_1d = list(torch.empty(3, 2))     # 3 lines
    
    >>> torch.stack(x_1d, 0).shape         # axis=0 stacking
    torch.Size([3, 2])
    
    >>> torch.stack(x_1d, 1).shape         # axis=1 stacking
    torch.Size([2, 3])
    
  • Similarly for two-dimensional inputs:

    With code:

    >>> x_2d = list(torch.empty(3, 2, 2))   # 3 2x2-squares
    
    >>> torch.stack(x_2d, 0).shape          # axis=0 stacking
    torch.Size([3, 2, 2])
    
    >>> torch.stack(x_2d, 1).shape          # axis=1 stacking
    torch.Size([2, 3, 2])
    
    >>> torch.stack(x_2d, 2).shape          # axis=2 stacking
    torch.Size([2, 2, 3])
    

With this state of mind, you can intuitively extend the operation to n-dimensional tensors.

2 of 3
3

Very simple! I will use 4 varibles for this example. The function torch.stack is very similar to numpy (vstack and hstack). Example :

t1 = torch.tensor([1,2,3])
t2 = torch.tensor([4,5,6])
t3 = torch.tensor([7,8,9])
t4 = torch.tensor([10,11,12])

if you try this cmd

>> torch.stack((t1,t2,t3,t4),dim=1).size()
>> torch.Size([3, 4])

if you change dim=1 with dim=0

>> torch.stack((t1,t2,t3,t4),dim=0).size()
>> torch.Size([4, 3])

In first case you have a tensor with 3x4 dimensional but in last case you have a 4x3 tensor. Test this code without using .size() !

>> torch.stack((t1,t2,t3,t4),dim=1)
>> tensor([[ 1,  4,  7, 10],
        [ 2,  5,  8, 11],
        [ 3,  6,  9, 12]])

>> torch.stack((t1,t2,t3,t4),dim=0)
>> tensor([[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9],
        [10, 11, 12]])

Happy Coding!

🌐
PyTorch Forums
discuss.pytorch.org › vision
How to concatenate 3 tensors with different sizes as tensor - vision - PyTorch Forums
June 9, 2020 - x -> torch.Size([1, 512, 80, 80]) y -> torch.Size([1, 1024, 40, 40]) z -> torch.Size([1, 2048, 20, 20]) t = concatenate(x,y,z) # for example
🌐
PyTorch Forums
discuss.pytorch.org › t › stack-expects-each-equal-size › 143012 › 9
Stack expects each equal size - #9 by AlphaBetaGamma96 - PyTorch Forums
February 1, 2022 - torch.stack and torch.cat both ‘concatenate’ Tensors but the key different is that torch.stack applies this concatenation along a new dimenion, thereby stacking the Tensors whereas torch.cat does a direct concatenation along already existing dimensions For example, a = torch.randn(7,768) b = torch.randn(8,768) torch.cat((a,b)).shape #returns torch.Size([15, 768]) Trying torch.stack results in the error, RuntimeError: stack expects each tensor to be equal size, but got [7, 768] at entry 0 an...
🌐
PyTorch
docs.pytorch.org › reference api › torch.stack
torch.stack — PyTorch 2.14 documentation
January 1, 2023 - All tensors need to be of the same size. ... dim (int, optional) – dimension to insert. Has to be between 0 and the number of dimensions of concatenated tensors (inclusive). Default: 0 ... >>> x = torch.randn(2, 3) >>> x tensor([[ 0.3367, ...
🌐
GitHub
github.com › pytorch › pytorch › pull › 32931
Add size checks to `torch.stack` by Enealor · Pull Request #32931 · pytorch/pytorch
Got 2 and 3 in dimension 2 at (path)\aten\src\TH/generic/THTensor.cpp:612 ``` New error: ``` RuntimeError: stack expects each tensor to be equal size, but got [1, 2] at entry 0 and [1, 3] at entry 1 ``` Pull Request resolved: pytorch#32931 Differential Revision: D19700110 Pulled By: ezyang fbshipit-source-id: 7e18bb00fa2c137e418e340d719b6b76170b83e3 · ttumiel pushed a commit to ttumiel/pytorch that referenced this pull request ... Summary: Checks the size of each tensor passed to `torch.stack` before calling `cat` to address pytorch#29510.
Author: pytorch
🌐
APXML
apxml.com › courses › getting-started-with-pytorch › chapter-2-advanced-tensor-manipulations › joining-splitting-tensors
Join & Split PyTorch Tensors | Cat, Stack, Chunk
PyTorch offers torch.split and torch.chunk for these tasks. The torch.split function divides a tensor into chunks along a specified dimension. You can specify either the size of each chunk (if you want equal parts) or a list containing the sizes of each desired chunk.
🌐
PyTorch Forums
discuss.pytorch.org › vision
RuntimeError: stack expects each tensor to be equal size, but got [3, 224, 224] at entry 0 and [3, 224, 336] at entry 3 - vision - PyTorch Forums
June 28, 2020 - Im trying to implement pretrained resnet50 on a image classification task with 42 labels and received this error. I dont understand what caused the layer size to change. Below is my code, i stitched them up from different tutorials I can find. import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets from torchvision import transforms from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import Dataset clas...
🌐
Sling Academy
slingacademy.com › article › stacking-tensors-in-pytorch
Stacking Tensors in PyTorch: Tutorials & Examples - Sling Academy
July 23, 2023 - torch.stack() is a PyTorch function that joins or concatenates a sequence of tensors along a new dimension. It inserts a new dimension and concatenates the tensors along that dimension. The tensors must have the same shape and size to be stacked.
🌐
GitHub
github.com › pytorch › pytorch › issues › 1512
[feature request] Support tensors of different sizes as batch elements in DataLoader · Issue #1512 · pytorch/pytorch
May 8, 2017 - import torch.utils.data loader = torch.utils.data.DataLoader(dataset = [(torch.zeros(3, 128, 128), torch.zeros(i, 4)) for i in range(1, 3)], batch_size = 2) for batch in loader: print(batch) Currently this blows with a message below because collate wants to torch.stack batch elements, regardless if they have same size: File "...torch/utils/data/dataloader.py", line 188, in __next__ batch = self.collate_fn([self.dataset[i] for i in indices]) File ".../torch/utils/data/dataloader.py", line 110, in default_collate return [default_collate(samples) for samples in transposed] File ".../torch/utils/data/dataloader.py", line 92, in default_collate return torch.stack(batch, 0, out=out) File ".../torch/functional.py", line 56, in stack inputs = [t.unsqueeze(dim) for t in sequence] RuntimeError: cannot unsqueeze empty tensor at .../torch/lib/TH/generic/THTensor.c:530 ·
Author: pytorch