fix: avoid NaN gradients for masked sqrt at zero - #3692
Closed
Lyxot wants to merge 2 commits into
Closed
Conversation
zcbenz
approved these changes
Jun 15, 2026
zcbenz
left a comment
Collaborator
There was a problem hiding this comment.
Looks good to me, thanks!
Contributor
Author
|
Pushed a formatting commit |
Member
|
I am sorry to say I will close this. First, all frameworks behave the same way. Secondly, I do think that the behavior is correct. The derivative of That being said all you have to do is put the mask before the rho_squared = x * x + y * y
rho_squared_safe = mx.maximum(rho_squared, 1e-20)
rho_safe = mx.sqrt(rho_squared_safe) |
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.
Fixes #3668
Proposed changes
Fixes NaN gradients when
sqrtreceives a zero cotangent at singular inputs.For expressions like:
the forward value is finite at
x = y = 0, but the VJP previously evaluated the inactivesqrt(0)path as0 / 0, producing NaN gradients.This updates
Sqrt::vjpto substitute a safe denominator when the incoming cotangent is zero, so masked-out paths contribute zero instead of NaN. The change is local toSqrt::vjpand preserves the singular gradient when the cotangent is nonzero.Tests
DEVICE=cpu python -m pytest -q python/tests/test_autograd.py::TestAutograd::test_masked_sqrt_grad_is_finiteDEVICE=gpu python -m pytest -q python/tests/test_autograd.py::TestAutograd::test_masked_sqrt_grad_is_finitepython -m pytest -q python/tests/test_autograd.py python/tests/test_ops.py::TestOps::test_where python/tests/test_ops.py::TestOps::test_maximum python/tests/test_ops.py::TestOps::test_minimumChecklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes