You can add torch.autograd.set_detect_anomaly(True) at the beginning of your script to know where nan appear in the backward pass.
In your particular case, the problem is that in your dist1 function, you take the second derivative of the norm at 0. Since this derivative includes a division by the norm value, you get nans.
You will need to make sure that data - x != 0 before taking the norm.