torch.nn.functional.conv2d for several channels/batches
I have an image with I want to pad (to maintain the same shape) and then perform a convolution with a given kernel. It works ok if I have only one channel and one image in the batch. But how to properly rewrite it for several batches &amp; channels? I suppose, for batches I can just duplicate the kernel along dimension 0. But what about channels? What is the proper way to do it in torch? See the toy example below.

import torch.nn.functional as f

x = torch.zeros((1,1,16,16))
x[...,6:10,6:10] = 1.
ker = torch.ones(3,3)
ker[1,1] = -4
padding = (ker.shape[1] // 2, ker.shape[1] // 2, 
           ker.shape[0] // 2, ker.shape[0] // 2)
x = f.pad(x, padding, mode='replicate')    
kernel = ker.reshape((1, 1, ker.shape[0], -1))
result = f.conv2d(x, ker, groups=1)


How to rewrite this piece of code to deal with multiple channels and batches? I read documentation but to be honest it did not seem very detailed to me.

The documentation at https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.conv2d seems to answer your question:

 input – input tensor of shape (minibatch,in_channels,iH,iW)
 weight – filters of shape (out_channels,in_channels/groups,kH,kW)


so your x must be size (batch_size, in_channels, 16, 16)

and your kernel (batch_size, out_channels/groups, kH, kW)
