Same padding equivalent in Pytorch

Hi,

PyTorch does not support same padding the way Keras does, but still you can manage it easily using explicit padding before passing the tensor to convolution layer. Here, symmetric padding is not possible so by padding only one side, in your case, top bottom of tensor, we can achieve same padding.

import torch
import torch.nn.functional as F

x = torch.randn(64, 32, 100, 20)
x = F.pad(x, (0, 0, 2, 1))  # [left, right, top, bot]
nn.Conv2d(32, 32, (4, 1))(x).shape

Please see these post about calculations Converting tensorflow model to pytorch: issue with padding

Bests

4 Likes