Hi 
Your gradients should be fine since you are using pytorch functions. I don’t know about that logic though, looks a bit weird. Try if it gives the same outputs as this function I found on SO.
def angle(angle1, angle2):
    a = angle1 - angle2
    a = (a + 180) % 360 - 180
    print(abs(a))


angle(359, 1)  # -> 2
angle(10, 100)  # -> 90
angle(10, 150)  # -> 140
angle(10, 200)  # -> 170