Here is an example using F.unfold and tensor.unfold for the 4D case (you can add another unfold call for the additional dimension):
B, C, H, W = 2, 3, 4, 4
x = torch.arange(1, 1+(B*C*H*W)).float().view(B, C, H, W)
kernel_size = 2
dilation = 1
padding = 1
stride = 2
x_unf = torch.nn.functional.unfold(
    input=x, kernel_size=kernel_size, dilation=dilation, padding=padding, stride=stride)
x_unf.shape # [2, 12, 9]

x_pad = F.pad(x, [1, 1, 1, 1])
out = x_pad.unfold(2, kernel_size, stride).unfold(3, kernel_size, stride)
out.shape
out = out.contiguous().permute(0, 2, 3, 1, 4, 5).contiguous().view(out.size(0), -1, kernel_size*kernel_size*x.size(1))
out = out.permute(0, 2, 1)
print((out == x_unf).all())
> tensor(True)

(thanks @tom for finding an initial error  )