As long as you are using PyTorch methods, the computation should be fine.
I can’t see any obvious error in your code.
As long as weights has some non-zero values, the division should also be fine.
What kind of strange behavior are you experiencing?