Sequential modification to a tensor

Hi,
I want to see if someone know how to implement this in pytorch:

Suppose there is a tensor M of size [h,w]. And I have a vector F of size [k], and an integer tensor D denoting its corresponding location of size [k,2], where each row of D store the index to M. I want to add each value of F to M, and also do averaging if there is multiple entry in F point to the same location in M. How should I do this efficiently in pytorch?

Thanks!