Stand-alone Dilation

Is there a simple way to do stand-alone dilation in pytorch? Ideally it would be using a layer, but a function is okay if there is no layer available. I am not looking for a custom solution.

In this example, we want to pass x to the function to produce y.

import torch

x = torch.tensor([[
    [1, 1, 1, 1],
    [1, 1, 1, 1],
    [1, 1, 1, 1],
    [1, 1, 1, 1],
]])

y = torch.tensor([[
    [1, 0, 1, 0, 1, 0, 1],
    [0, 0, 0, 0, 0, 0, 0],
    [1, 0, 1, 0, 1, 0, 1],
    [0, 0, 0, 0, 0, 0, 0],
    [1, 0, 1, 0, 1, 0, 1],
    [0, 0, 0, 0, 0, 0, 0],
    [1, 0, 1, 0, 1, 0, 1],
]])

Hi Joseph!

ConvTranspose2d with an appropriate kernel performs such a dilation:

>>> import torch
>>> torch.__version__
'1.10.2'
>>> dilate = torch.nn.ConvTranspose2d (1, 1, 2, 2, bias = False)
>>> dilate.weight.requires_grad = False
>>> dilate.weight[0, 0, :, :] = torch.tensor ([[1.0, 0.0], [0.0, 0.0]])
>>> x = torch.ones (1, 1, 4, 4)
>>> x
tensor([[[[1., 1., 1., 1.],
          [1., 1., 1., 1.],
          [1., 1., 1., 1.],
          [1., 1., 1., 1.]]]])
>>> dilate (x)
tensor([[[[1., 0., 1., 0., 1., 0., 1., 0.],
          [0., 0., 0., 0., 0., 0., 0., 0.],
          [1., 0., 1., 0., 1., 0., 1., 0.],
          [0., 0., 0., 0., 0., 0., 0., 0.],
          [1., 0., 1., 0., 1., 0., 1., 0.],
          [0., 0., 0., 0., 0., 0., 0., 0.],
          [1., 0., 1., 0., 1., 0., 1., 0.],
          [0., 0., 0., 0., 0., 0., 0., 0.]]]])

To work directly with 2d tensors, you may use squeeze() / unsqueeze()
to handle the leading singleton dimensions needed by ConvTranspose2d.
You may also trim off the last row and column, if desired.

Best.

K. Frank