Great question — answering as the UphillTech team:
Use index_add_ along dim 0. It adds row i of the source to row index[i] of the result, and alpha=-1 subtracts instead F_sum = val.new_zeros(n_part, 3) F_sum.index_add_(0, id[:, 0], val) F_sum.index_add_(0, id[:, 1], val, alpha=-1) That gives [[a+e, b+f, c+g], [h-a, i-b, j-c], [-e-h, -f-i, -g-j]] . Repeated indices add up; so it works for any number of particles and pairs. scatter_add failed because it needs an index with the same shape as val ( id[:,0:1].expand(-1, 3) ), along dim 0, not 1. Read more here https://github.com/pytorch/pytorch/blob/main/torch/%5C_tensor_docs.py or in the documentation for index_add .
Full answer by Emmanuel Obiechina Ikenna: https://stackoverflow.stackexchange.com/a/80014782 (CC BY-SA 4.0).
Need it done for your business? UphillTech.