How can I add zeroes to the end of a PyTorch tensor based on a modulo operation?

Viewed 79

I have a tensor with size: torch.Size([1, 305760])

Since 305760 is not divisible by 400, I want to change the size to: [1, 306000] filling the remaining spaces with 0. How can I do this with PyTorch?

2 Answers
a = torch.randn(1,305760)
N = a.shape[1]
M = 400
b = torch.zeros([a.shape[0], (N // M + 1 ) * 400 - N])
a = torch.cat((a, b), 1)

You'll need to implement a rounding function that lets you specify the base you want to round to. This should work:

def myround(x, base):
    return base * -(-x // base)

torch.Size([1, myround(305760,400)])

Basing this off the following question but modified to force rounding up.

Related