Conv2D padding in TensorFlow and PyTorch
I am trying to convert TensorFlow model to PyTorch but having trouble with padding. My code for for relevant platforms are as follow:
TensorFlow
conv1 = tf.layers.conv2d(
                inputs=input_layer,
                filters=32,
                kernel_size=[5, 5],
                padding=&quot;same&quot;,
                activation=tf.nn.relu,
                name = &quot;conv1&quot;)

PyTorch
conv1 = nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2)

I have few questions:

Are the above codes equivalent?
How many paddings are added on left/right/top/bottom if we use same padding in tensorflow?
How many paddings are added on left/right/top/bottom if we use padding=2 in pytorch?
If the above two code snippets are not equivalent then how can we make the same conv layer?

Thanks in advance.

To answer your questions:
The reason why Pytorch doesn't have padding = 'same' to quite simply put it is due to its dynamic computation graph in comparison to Tensorflow static graph.

Both the codes are not equivalent as different padding is used.

'Same' padding tries to pad evenly on the left and right, but if the amount of columns to be added is odd, it will then add an extra column to the right.

'Padding = 2' in Pytorch applies 2 implicit paddings on either side.

Pytorch 1.9 has added padding = 'same' for un-strided or stride = 1 convolutions. Which will work for your use case.


But for stride &gt; 2 padding needs to be added manually.
Here is the good implementation to perform 'same' padding:-
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/padding.py#L28
