Conv2d Output Size Calculator

Calculate the output height, width, and channels of a PyTorch Conv2d layer. Enter input shape, kernel size, stride, padding, and dilation to get the exact output tensor shape instantly.

Built by Michael Lip

PyTorch Conv2d Code Example

import torch
import torch.nn as nn

# Define Conv2d layer
conv = nn.Conv2d(
    in_channels=3,      # RGB input
    out_channels=64,     # 64 filters
    kernel_size=3,       # 3x3 kernel
    stride=1,
    padding=1            # same padding
)

# Input: batch=1, channels=3, height=224, width=224
x = torch.randn(1, 3, 224, 224)
output = conv(x)
print(output.shape)  # torch.Size([1, 64, 224, 224])

# Output formula:
# H_out = floor((H_in + 2*padding - kernel_size) / stride + 1)
# W_out = floor((W_in + 2*padding - kernel_size) / stride + 1)

# Parameters: out_channels * (in_channels * kernel_h * kernel_w + 1)
print(sum(p.numel() for p in conv.parameters()))  # 1792

Frequently Asked Questions

What is the Conv2d output size formula?

The formula is: H_out = floor((H_in + 2*padding - dilation*(kernel_size-1) - 1) / stride) + 1. The same formula applies to the width dimension. The batch size and number of output channels (out_channels parameter) determine the remaining dimensions.

How does dilation affect Conv2d output size?

Dilation spreads the kernel elements apart, effectively increasing the receptive field without adding parameters. A dilation of 2 means there is one gap between each kernel element. The effective kernel size becomes dilation*(kernel_size-1)+1, which reduces the output spatial dimensions.

What padding should I use to keep the same spatial size?

For 'same' padding with stride=1 and dilation=1, use padding = (kernel_size - 1) / 2. For a 3x3 kernel, that's padding=1. For a 5x5 kernel, padding=2. This only works with odd kernel sizes.

What happens if Conv2d output size is zero or negative?

If the formula produces zero or a negative number, PyTorch will raise a RuntimeError. This means your kernel is larger than the input spatial dimensions (after padding). Fix it by increasing padding, decreasing kernel size, or decreasing dilation.

Is this tool free?

Yes. All HeyTensor tools are free, run in your browser, and require no signup.

About This Tool

This tool is part of HeyTensor, a free suite of PyTorch and deep learning utilities. All calculations run entirely in your browser — no data is sent to any server. The source code is open on GitHub.

Contact

HeyTensor is built and maintained by Michael Lip. For questions or feedback, email [email protected].

📊 Based on real data from our PyTorch Error Database — 52 errors analyzed from Stack Overflow