Fix torch.atan2 for y == 0 with negative x - #2769
Open
LeSingh1 wants to merge 1 commit into
Open
Conversation
`torch.atan2(0, x)` is `pi` for `x < 0`, but the quadrant correction only rotated
by `pi` when `y > 0` strictly, so those elements came back as `0`.
The shift that moves `x` away from zero to avoid dividing by it also flipped the
sign of any `x` in `(-1e-8, 0)`, which put `atan(y / x_safe)` in the opposite half
plane while the quadrant term still corrected for `x < 0`, giving a result off by
`pi`. Make the shift follow the sign of `x`.
>>> y = torch.tensor([0.0, 0.0, 1.0, -1.0])
>>> x = torch.tensor([-1.0, -3.0, -1e-9, -1e-9])
torch : [ 3.14159, 3.14159, 1.57080, -1.57080]
before: [ 0.00000, 0.00000, 4.71239, -4.71239]
after : [ 3.14159, 3.14159, 1.57080, -1.57080]
Collaborator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
torch.atan2returns the wrong quadrant in two cases.The rotation by π for
x < 0is gated on strictlyy > 0, soatan2(0, x)forx < 0returns0instead ofπ. Separately, the "avoid divide-by-zero" shift adds a fixed+2e-8, which flips the sign of anyxin(-1e-8, 0)— movingatan(y / x_safe)into the other half plane while the quadrant coefficients still correct forx < 0, giving another ±π error.Fix
Use
greater_equal(y, 0)for thex < 0rotation, and make the safe shift followsign(x).The
x == 0branches keep strict>/<, soatan2(0, 0) == 0is preserved to match PyTorch.Testing
Added
test_atan2_y0_xnegativeandtest_atan2_x_tiny_negative. Before:6 failed, 2 skipped. After:46 passed, 2 skipped, and the fullTestAtan2class passes 84.A 2000-element random sweep including zeros and tiny negatives shows 0 mismatches against eager PyTorch, max error 2.4e-7.
The existing
TestAtan2covers random inputs,x == 0, andy == 0 & x == 0— they == 0, x < 0quadrant was never exercised.