How to check what is amount of padding used when we use padding = "same"?

Hello there,

I was wondering what is the amount of padding used when I put padding = “same” in conv2D!

I have an image.

import torch 

image = torch.randn((1, 3 ,224, 224))

conv2 = torch.nn.Conv2d(
    in_channels=3, 
    out_channels=5, 
    kernel_size=16,
    stride=1,
    padding='same'
)

conv2(image).shape  # 1, 5, 224, 224 

But how to know what amount of padding has been used?
Since I have manually checked using padding = 4,5,6,7,8.
None of the padding gives 224 as output shape.

So that means is it using fractional padding?

Jay

Yes!

Not sure unfortunately. Afaik, it’s been handled internally. There may be some way to print it.

I think this is a nice hardcoded way to check?

kernel_size = conv2.kernel_size
if isinstance(kernel_size, int):
    padding = kernel_size // 2
else:
    padding = (kernel_size[0] // 2, kernel_size[1] // 2)

print(f"Padding used: {padding}")

output = conv2(image)
print(f"Output shape: {output.shape}")

Thanks @Soumya_Kundu for your reply!

With the code you provided, value of padding is coming as 8, but if we put 8 back, its nor preserving the image dimension.
image

Jay

Can anyone please help here?

You could check conv2._reversed_padding_repeated_twice and use F.pad before applying the convolution to get the same output, but keep in mind it’s an internal attribute and could change in the future.