Summing tensor values with the same index from an index tensor

I have a data tensor and an index tensor:

d = torch.Tensor([ 0.0300,  0.1000, -0.0500,  0.0600])
idxs = torch.LongTensor([0, 1, 1, 3])

I want to sum all values in the data tensor where the values in the index tensor are equal. For example 0.1 and -0.05 should be summed because the second and third value of idxs are equal. I know this can be done for a single value, for example index 1:

torch.sum(d[idxs == 1])

which will give:


How can I apply this for a range of indices without using a for loop?
With a for loop it could look like this:

torch.Tensor([torch.sum(d[idxs == i]) for i in range(len(idxs))])

which will give (expected result):

tensor([0.0300, 0.0500, 0.0000, 0.0600])

Hi @maartenvds!. Since you want to do it for a range of indices, I guess for loop is the best option. BTW, what’s your concern on using Loops?

Thanks for the response @Gilf641 . ‘d’ is in fact a gradient tensor and its calculated inside a backward function of an autograd.Function. Since this function is used many times in my network, I wanted to make sure its as fast as possible (without writing custom C++/cuda code). I guess this is as efficient as it goes.