RuntimeError: non-empty 3D or 4D (batch mode) tensor expected for input

I get this error: “RuntimeError: non-empty 3D or 4D (batch mode) tensor expected for input” when passing a tensor of shape [1, 2, 3, 256, 256] to the layer AvgPool2d(kernel_size=3, stride=2, padding=[1, 1]).

I could not figure out what the problem is. From the research I have done it seems that this error is thrown when an empty tensor is passed to the pooling layer but the shape of my tensor is [1, 2, 3, 256, 256] meaning its not empty. Am I missing something? Thanks in advance.

By the way, this error only occurs in the inference time, the model trains with no errors.

I’m a bit confused about the error message and the information in your post.
While the error message suggests you are using nn.AvgPool3d and are passing a wrong input shape, you are mentioning nn.AvgPool2d for the posted input.

Anyway, these codes should work:

# 3D
x = torch.randn([1, 2, 3, 256, 256])
pool = nn.AvgPool3d(kernel_size=3, stride=2, padding=1)
out = pool(x)

# 2D
x = torch.randn([2, 3, 256, 256])
pool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
out = pool(x)
1 Like