What would be the fastest most efficient way to pad an NCHW tensor with random values along it's H and W dimensions?

I’m thinking of something like torch.nn.ConstantPad2d() only instead a padding with a constant value, each value added by the padding is random.

Hi Pro!

At the cost of generating a full random tensor, you could use a sentinel
value and torch.where():

>>> torch.__version__
'1.7.1'
>>> t = torch.ones ((2, 1, 3, 3))
>>> sentinel = 999.9
>>> p = torch.nn.ConstantPad2d (1, sentinel)(t)
>>> torch.where (p == sentinel, torch.randn (p.shape), p)
tensor([[[[ 0.2294,  0.6565,  1.3840,  0.8816,  0.6239],
          [-0.1138,  1.0000,  1.0000,  1.0000,  1.4669],
          [-0.1995,  1.0000,  1.0000,  1.0000, -1.4677],
          [ 0.7898,  1.0000,  1.0000,  1.0000, -2.0605],
          [-1.1524, -0.6035, -0.0759,  0.7622,  0.0670]]],


        [[[-0.7629, -0.0068, -1.5791,  0.6111,  0.0061],
          [-2.1073,  1.0000,  1.0000,  1.0000,  0.3191],
          [-1.1106,  1.0000,  1.0000,  1.0000,  0.2106],
          [-0.1326,  1.0000,  1.0000,  1.0000,  0.3036],
          [ 0.0869, -0.6228, -0.0596, -2.4246,  1.1754]]]])

Best.

K. Frank

1 Like