title: PyTorch add to tensor at indices with degenerate indices
body: <p>This question may be seen as an extension to <a href="https://stackoverflow.com/questions/58012586/how-to-add-to-pytorch-tensor-at-indices">this one</a>.</p>
  <p>I have two 1D tensors, <code>counts</code> and <code>idx</code>. Counts is length 20 and stores the occurrences of events that fall into 1 of 20 bins. <code>idx</code> is very long, and each entry is an integer which corresponds to the occurrence of 1 of the 20 events, and each event can occur multiple times. I'd like a vectorized or very fast way to add the number of times event <code>i</code> occurred in <code>idx</code> to the <code>i</code>'th bucket in <code>counts</code>. Furthermore, it would be ideal if the solution was compatible with operation on batches of <code>count</code>'s and <code>idx</code>'s during a training loop.</p>
  <p>My first thought was to simply use this strategy of indexing <code>counts</code> with <code>idx</code>:</p>
  <pre><code>counts = torch.zeros(5)
  
  idx = torch.tensor([1,1,1,2,3])
  
  counts[idx] += 1
  </code></pre>
  <p>But it did not work, with counts ending at</p>
  <pre><code>tensor([0., 1., 1., 1., 0.])
  </code></pre>
  <p>instead of the desired</p>
  <pre><code>tensor([0., 3., 1., 1., 0.])
  </code></pre>
  <p>What's the fastest way I can do this? My next best guess is</p>
  <pre><code>for i in range(20):
     counts[i] += idx[idx == i].sum()
  </code></pre>