How to add at specific but possibly repeating indices

I want to do something like

a = torch.tensor([0.0, 0.0, 0.0, 0.0, 0.0])
b = torch.tensor([1, 2, 2, 4, 0, 1, 3])
c = torch.tensor([0.3, 0.2, 0.4, 0.1, 1.0, 2.0, 0.4])

a[b] += c

expected result : tensor([1.0000, 2.0000, 0.6000, 0.4000, 0.1000])
actual result: tensor([1.0000, 2.0000, 0.4000, 0.4000, 0.1000])

at index 2 it is retaining last value 0.4 instead of adding 0.2 and 0.4
I want to do this without creating onehot vectors of b and then using scatter_ as it is taking too much memory.

a.put_(b, c, accumulate=True) should work.
I assume a[1] should have the value 2.3 after the addition.

1 Like