Skip to content

Add Autograd Support for Low-Level Bessel Functions - #189872

Closed
colalb1 wants to merge 28 commits into
pytorch:mainfrom
colalb1:colalb1/bessel_backward
Closed

colalb1 wants to merge 28 commits into
pytorch:mainfrom
colalb1:colalb1/bessel_backward

Conversation

@colalb1

@colalb1 colalb1 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Makes the eight low-level Bessel special functions differentiable (backward + forward-mode AD), replacing their non_differentiable autograd entries.

Changes:

  • derivatives.yaml: auto_element_wise derivative formulas for special_bessel_{j0,j1,y0,y1} and special_modified_bessel_{i0,i1,k0,k1}
  • FunctionsManual.{cpp,h}: new bessel_j1_backward handling the 0/0 removable singularity of J1' at x = 0 (limit 1/2); I1 reuses the existing i1_backward
  • OpInfo (special.py): enable supports_forward_ad, supports_fwgrad_bwgrad, and backward_dtypes so the ops get gradcheck/gradgradcheck/forward-AD and SciPy reference coverage automatically.
  • test_autograd.py: add TestBesselAutograd.test_zero_limit, the one check OpInfo cannot express since gradcheck cannot differentiate 0/0 at x=0

Questions:

  • test_zero_limit currently lives in test_autograd.py. Should it move to its own file instead of sitting alongside the autograd engine tests?
  • The CPU forward Bessel kernels are only ~1e-7 accurate in float64, which constrains gradient tolerances. Should improving the CPU Bessel ops be a hard blocker for this PR, and should I implement that first before moving forward here?

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@colalb1
colalb1 requested review from albanD and soulitzer as code owners July 14, 2026 14:36
@pytorch-bot

pytorch-bot Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/189872

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (1 Unrelated Failure)

As of commit d7a7280 with merge base aa4f1ee (image):

CRCR (non-blocking) - The following CRCR downstream CI job failed but is non-blocking:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

Comment thread torch/csrc/autograd/FunctionsManual.cpp Resolved
Comment thread torch/csrc/autograd/FunctionsManual.cpp Resolved
@colalb1
colalb1 requested a review from Skylion007 July 14, 2026 18:10
# unsigned integer types. Skip the affected forward reference-numerics tests there.
_domain_uint_skips = tuple(
DecorateInfo(
unittest.skip("clamp_min unimplemented for unsigned int types"),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, this should DEFINITELY be an xfail

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also we should just implement clamp_min, it's easy enough to implement, probably just need a few more dispatches

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed this to an xfail. Will make a different PR for clamp_min.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Skylion007 PR for adding uints to the clamp functions on CPU and CUDA: #189953

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR makes the low-level Bessel special functions differentiable in autograd (backward + forward-mode AD) by adding derivative formulas, a manual backward helper for the J1' removable singularity at x=0, and enabling OpInfo coverage plus an explicit regression test for the x=0 limit.

Changes:

  • Add derivative formulas for special_bessel_{j0,j1,y0,y1} and special_modified_bessel_{i0,i1,k0,k1} in tools/autograd/derivatives.yaml.
  • Introduce bessel_j1_backward in FunctionsManual.{h,cpp} to special-case the x=0 gradient limit for J1'.
  • Update OpInfo definitions to enable autograd + forward AD testing for these ops, and add an explicit x=0 gradient-limit test.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
torch/testing/_internal/opinfo/definitions/special.py Enables autograd/forward-AD OpInfo coverage for Bessel ops; adds domain + uint skip plumbing for reference numerics tests.
torch/csrc/autograd/FunctionsManual.h Declares bessel_j1_backward for use by generated derivative code.
torch/csrc/autograd/FunctionsManual.cpp Implements bessel_j1_backward to handle the removable singularity at x=0.
tools/autograd/derivatives.yaml Replaces non_differentiable entries with differentiable formulas for the Bessel ops.
test/test_autograd.py Adds a targeted x=0 gradient-limit regression test and wires it into device-type instantiation.

Comment thread test/test_autograd.py Resolved
Comment thread test/test_autograd.py Resolved
@colalb1
colalb1 requested a review from mruberry as a code owner July 14, 2026 23:11
@colalb1
colalb1 requested a review from Skylion007 July 14, 2026 23:29
@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 15, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator

Ideally add the missing dtype coverage to the clamp tests in the other PR, then remove the xfails here. :)

ref=scipy.special.k0 if TEST_SCIPY else None,
supports_autograd=False,
backward_dtypes=floating_types(),
domain=(0, None),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, didn't know about the domain arg?

ref=scipy.special.y1 if TEST_SCIPY else None,
supports_autograd=False,
backward_dtypes=floating_types(),
domain=(0, None),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you need domain now, but not before?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Skylion007 I will look into this in the next couple of days and get back to you with a thorough explanation.

Could you review #189953 when you get the chance? This is the blocking clamp fix for this PR, just want to make sure this gets in before everything in this is addressed.

Thank you.

@colalb1 colalb1 Jul 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Skylion007 This addresses both comments about the domain args:

The four functions special.bessel_y0, special.bessel_y1, special.modified_bessel_k0, special.modified_bessel_k1 are only real-valued and finite for $x > 0$ since they all have singularities at $0$ and are complex/undefined for $x < 0$. The other Bessel functions (bessel_j0/j1, modified_bessel_i0/i1) are defined on the whole real line, so they require no domain restriction.

The domain restrictions are required now because supports_autograd is flipped to True in this PR, so before this, only forward-numeric tests ran. Forward numeric tests tolerate negative inputs because torch and scipy both return NaN there and the comparison treats NaN == NaN as equal. gradcheck/gradgradcheck draw sample inputs and perturb them with finite differences, so on negative or near-zero inputs, $Y_n/ K_n$ and their derivatives blow up to NaN/inf, so gradcheck would fail. domain=(0, None) keeps the samples in the region where the function and its derivatives are well-defined.

@colalb1 colalb1 Jul 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chapter 10 should support the math-related statements above

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this and double check the op tests are correct.

@claude

claude Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 14m 16s —— View job


PR Review: #189872 — Bessel autograd support

One sentence summary: The derivative math is all correct and the backward helper is sound, but the op tests have two problems — the last commit removed the uint xfails while keeping domain=(0, None), which will make the forward reference-numerics tests error on uint16/32/64 for y0/y1/k0/k1 (the clamp support they depend on isn't in this branch yet), and the new test_bessel_zero_limit_gradient hardcodes torch.double on a device-generic test so it breaks on backends without float64 (e.g. MPS).

Full review

Derivative formulas (derivatives.yaml) — all correct

Verified each against the standard identities:

  • j0' = -J1, y0' = -Y1, i0' = I1, k0' = -K1 ✓
  • j1' = J0 - J1/x (via bessel_j1_backward) ✓
  • y1' = Y0 - Y1/x ✓
  • i1' = I0 - I1/x (reuses i1_backward) ✓
  • k1' = -(K0 + K1/x) ✓

bessel_j1_backward correctly mirrors i1_backward: masked_fill keeps the reciprocal finite at the singular points and then overwrites the gradient there with the analytic limit 0.5. masked_fill (vs where) is the right double-backward-safe choice, so supports_fwgrad_bwgrad is fine.

Testing — blocker: uint xfails removed prematurely

Commit fc8f620 deleted _domain_uint_xfails but kept domain=(0, None) on special.bessel_y0/y1 and special.modified_bessel_k0/k1. Those four ops still list the barebones unsigned types in dtypes (all_types_and(torch.bool, *_unsigned_int_types)), and domain drives the reference-numerics sample generator through a.clamp_(min=low, ...) (opinfo/core.py:2680, :2728).

Both CPU and CUDA clamp/clamp_min dispatch via AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, ...) (cpu/TensorCompareKernel.cpp:343-389, cuda/TensorCompare.cu:45-62), which excludes uint16/uint32/uint64. So test_reference_numerics_small / test_reference_numerics_large will error (not xfail) on those dtypes for the four domain-restricted ops.

The commit message says this relies on "uint support on clamp functions will be added" (#189953), but that PR is not in this branch — git log 53e958d..HEAD shows no clamp change, and the last main merge (5b59f63) predates the xfail removal. So this matches exactly what @Skylion007 asked for ("add the dtype coverage to clamp in the other PR, then remove the xfails here") — but done in the wrong order. The pull CI job is still in progress; I expect it to fail here.

Fix: either restore _domain_uint_xfails until #189953 lands, or rebase this PR on top of #189953. Fix this →

Testing — should-fix: test_bessel_zero_limit_gradient hardcodes torch.double

test/test_unary_ufuncs.py:1217 is instantiated device-generically (instantiate_device_type_tests, line 2012) but hardcodes dtype=torch.double with no dtype guard. On a backend without float64 (MPS), torch.zeros(4, dtype=torch.double, device=device) raises. The neighboring precedent test_sinc (line 1195) uses @dtypes(torch.double), which both restricts instantiation to devices that support double and passes dtype in. Follow that pattern (add @dtypes(torch.double) and take the dtype arg), or add an explicit MPS skip. Fix this →

The test's assertions themselves are correct: it checks the gradient is 0.5 and non-NaN at x=0 for both bessel_j1 and modified_bessel_i1, which is exactly the OpInfo-uncovered corner. The comment (OpInfo sample gen doesn't emit exact zeros) is now accurate.

Answering @Skylion007's domain question

"Why do you need domain now, but not before?" — Before this PR the ops were supports_autograd=False, so no gradcheck ran and only forward reference-numerics were exercised (tolerant of the x<0 NaNs from Y/K). Now that backward/forward-AD is enabled, gradcheck's sample tensors must stay in the real domain x>0 for Y_n/K_n (they're complex/NaN for x<0, giving NaN gradients). domain=(0, None) is what constrains the generated samples to x>0. Note j0/j1/i0/i1 correctly do not set domain — they're entire on the real line and bessel_j1/i1 specifically need x=0 to remain in-sample so the backward helper's limit is exercised.

Minor

  • backward_dtypes=floating_types() (float32/float64 only) matches the existing special.i1 precedent, so consistent — no action.
· branch `colalb1/bessel_backward`

Comment thread test/test_unary_ufuncs.py Outdated
)
def test_bessel_zero_limit_gradient(self, device, name):
op = getattr(torch.special, name)
x = torch.zeros(4, dtype=torch.double, device=device, requires_grad=True)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Won't the torch.double fail on MPS?
@dtypes(torch.double) like the above would fix this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Addressed.

Comment thread torch/csrc/autograd/FunctionsManual.cpp Outdated
auto eps = std::numeric_limits<scalar_t>::epsilon();
auto self_is_tiny = self.abs() <= eps;

auto safe_self = self.masked_fill(self_is_tiny, eps);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why masked_fill and not where like the above?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used masked_fill() instead of where(~mask,...) because it avoids two-gradient branching that where contains. Also, I find it a bit more readable.

I will change it to the where function since this matches other local functions more closely.

@colalb1
colalb1 requested review from Skylion007 and albanD July 22, 2026 13:19
pytorchmergebot pushed a commit that referenced this pull request Aug 1, 2026
Adds `uint16`, `uint32`, and `uint64` support to `clamp` functions on CPU and CUDA. These ops previously rejected the barebones unsigned dtypes because their kernels dispatched through `AT_DISPATCH_ALL_TYPES_AND2`, which omits them.

## Relationship to #189872

Unblocks #189872 ("Add Autograd Support for Low-Level Bessel Functions"). That PR restricts the `x > 0` Bessel OpInfos (`special.bessel_y0`, `bessel_y1`, `modified_bessel_k0`, `modified_bessel_k1`) to `domain=(0, None)`, which makes the unary sample generator call `clamp_min` on the sample dtypes. For the barebones unsigned dtypes that call currently raises `NotImplementedError`, so #189872 marks the `uint16/uint32/uint64` forward reference-numerics tests as `expectedFailure`. With clamp supporting these dtypes, those tests pass and the xfails can be removed there.

Pull Request resolved: #189953
Approved by: https://github.com/Skylion007
@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) module: inductor labels Aug 16, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator

Fix the remaining tests.

@colalb1

colalb1 commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Fix the remaining tests.

@Skylion007
The three tests that are failing are: test_output_grad_match_special_i1e_mps_float16, test_output_grad_match_special_i1_mps_float16, test_comprehensive_special_i1{,e}_cuda_float16 (grad).

The order-1 derivatives have the form f0(x) - f1(x)/x, where the terms nearly cancel. With C = |term| / |result|, the fp16 backward has two half-ULP error sources, both amplified by C: intermediate rounding (every ATen op writes an fp16 tensor), and the saved forward result, which arrives already rounded. $C\approx 16$ at the failing i1e sample and is unbounded near the zeros of the derivative, leaving the backends ~1.7% apart against an fp16 rtol of 1e-3.

A few options to correct this:

  • Promote to float and recompute f1(x) at float, half/bfloat16 only. This removes both sources but costs one extra special-function eval and ignores the saved result.
  • Promote to float only. Smaller change, no extra eval; leaves the amplified result error, so j1/y1 stay wrong and i1 passes.
  • Drop half/bfloat16 backward. There is no numerics risk but removes the half support you asked for.

I'd like to have half-precision support, but I'd prefer not to push something unstable that will raise problems with further development. I recommend the first option; I wanted to run this by you before changing it so we can close this issue with no further changes. Please let me know your thoughts when you get the chance.

Thank you.

@Skylion007

Copy link
Copy Markdown
Collaborator

Nah, you can just raise the tolerance of the fp16 using a dtype override probably

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude show you can add the dtype precision override to the opinfo and other tests here for the new functionality

@claude

claude Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 23m 3s —— View job


Adding the fp16 grad tolerance overrides via OpInfo

  • Read the current diff and locate the existing tolerance overrides
  • Pull the exact error magnitudes from the CI logs
  • Write the DecorateInfo overrides for special.i1 / special.i1e on MPS
  • Commit
  • Push — blocked, see below

One sentence summary: Yes — the override can be expressed entirely as OpInfo DecorateInfos rather than another op.name branch in test_mps.py, and the patch below does that for the two remaining failures; I was unable to push it because the GitHub App token is rejected on this branch.

What the failures actually are, and the patch

The remaining failures are MPS-only, and there are two of them, not three

Worth correcting the list in your earlier comment before picking tolerances. I read the logs from the latest commit (a860b54):

test status on a860b54
test_output_grad_match_special_i1_mps_float16 FAILED (job 95199871251)
test_output_grad_match_special_i1e_mps_float16 FAILED (all four MPS shards)
test_comprehensive_special_i1{,e}_cuda_float16 already fixed by a860b54's inductor_override_kwargs["cuda"] entries

The CUDA inductor ones are green now; the only inductor failure left in that run is test_forward_ad_linalg_householder_product_cuda_float32, which DrCI classifies as flaky-on-trunk and is unrelated. The test_extremal_numerics_cross_entropy_cuda failure is likewise unrelated (DrCI agrees).

Note the two MPS failures land on different shards, which is why only i1e appeared in the DrCI summary — i1 fails on macos-m2-15's shard while i1e fails on all four.

Measured magnitudes

From the log output, deterministic across reruns and across runners:

special.i1   float16: greatest relative difference 1.0042e-3   (rtol 1e-3 allowed)  -> 1.004x over
special.i1e  float16: greatest relative difference 1.0590e-2   (rtol 1e-3 allowed)  -> 10.6x over
                      greatest absolute difference 9.9182e-5   (atol 1e-5 allowed)

i1 is only barely over — a single element at 1.004x the limit. i1e is the genuinely wide one, consistent with what you'd expect: the exponential scaling drags the sampled gradients an order of magnitude closer to zero, so the same absolute rounding reads as a much bigger relative error. That is why the two need different rtol.

The patch

Attaching this to the OpInfo (rather than test_mps.py's _compute_tolerances ladder) keeps the tolerance next to the backward_dtypes declaration that instantiates the test, and matches what special.bessel_j1 already does a few hundred lines down in the same file. Only rtol moves; atol stays pinned at the fp16 default 1e-5 so near-zero gradients keep their absolute floor — bumping atol to 1e-4 would swallow the i1e mismatch outright, which sits on a value of magnitude ~1e-2.

--- a/torch/testing/_internal/opinfo/definitions/special.py
+++ b/torch/testing/_internal/opinfo/definitions/special.py
@@ -160,6 +160,16 @@ op_db: list[OpInfo] = [
                     }
                 )
             ),
+            # I1' = I0 - I1/x nearly cancels, so in fp16 the backward amplifies
+            # both the rounding of each intermediate and the already-rounded
+            # saved forward result. Relax rtol only: the mismatch scales with
+            # the gradient, so an atol bump would mask near-zero errors.
+            DecorateInfo(
+                toleranceOverride({torch.float16: tol(atol=1e-5, rtol=5e-3)}),
+                "TestConsistency",
+                "test_output_grad_match",
+                device_type="mps",
+            ),
         ),
         skips=(
             DecorateInfo(
@@ -182,6 +192,17 @@ op_db: list[OpInfo] = [
         dtypesIfMPS=all_types_and(torch.bool, torch.half, torch.bfloat16),
         backward_dtypes=floating_types_and(torch.half, torch.bfloat16),
         sample_inputs_func=sample_inputs_i0_i1,
+        decorators=(
+            # Same near-cancellation as special.i1, but the exponential scaling
+            # puts the sampled gradients an order of magnitude closer to zero,
+            # so the same absolute rounding shows up as a larger relative error.
+            DecorateInfo(
+                toleranceOverride({torch.float16: tol(atol=1e-5, rtol=3e-2)}),
+                "TestConsistency",
+                "test_output_grad_match",
+                device_type="mps",
+            ),
+        ),
         supports_forward_ad=True,
         supports_fwgrad_bwgrad=True,
     ),

5e-3 clears the i1 gap by 5.0x; 3e-2 clears i1e by 2.8x. The margins are deliberately modest — these are single-sample deterministic gaps, not noisy ones, so there is no reason to leave a 10x headroom that would hide a future real regression.

One thing worth confirming before merging

toleranceOverride sets self.precision / self.rel_tol on the test instance, and TensorLikePair applies them as max(self.rtol, rtol_override) (common_utils.py:3461). But test_output_grad_match passes atol/rtol explicitly from _compute_tolerances (test_mps.py:16371), and when an explicit value is given the override still wins via the max(). So this works — but only because _compute_tolerances returns (None, None) for these ops, letting the dtype default apply and then be raised. If someone later adds an i1 branch to _compute_tolerances, the two mechanisms will interact through that max(). Not a problem today, just the reason special.bessel_y0/y1 currently carry their fp16 grad tolerance in both places.

Push blocked

I committed this locally as cdc937e but every push attempt is rejected:

! [remote rejected] HEAD -> colalb1/bessel_backward
  (Unable to determine if workflow can be created or updated due to timeout; `workflows` scope may be required.)

I retried three times with the same result. @colalb1 — the diff above applies cleanly on top of a860b54; the commit message I wrote is reproduced below if it's useful. I also could not run lintrunner in this sandbox (no built environment), so please run it before committing, though the change is only two DecorateInfo blocks formatted to match the existing special.bessel_j1 entry.

Commit message
Add fp16 grad tolerance overrides for special.i1 and special.i1e on MPS

Enabling half-precision backward for the order-1 Bessel functions made
test_output_grad_match_special_i1{,e}_mps_float16 run for the first time,
and both fail against the fp16 default rtol of 1e-3.

Root cause: I1' = I0 - I1/x is a near-cancellation. With
C = |I1/x| / |I1'| the fp16 backward carries two half-ULP error sources,
both amplified by C -- the rounding of every intermediate (each ATen op in
i1_backward writes an fp16 tensor) and the saved forward `result`, which
arrives already rounded. This is a property of evaluating the composite
formula at half precision, not a defect in the derivative, and it is the
same eager-vs-reference intermediate-precision gap the neighbouring
entries in this file already absorb.

The overrides are attached as OpInfo DecorateInfos scoped to
TestConsistency/test_output_grad_match on mps, rather than as another
op_name branch in test_mps.py, so the tolerance lives next to the dtype
declaration that instantiates the test. Only rtol is relaxed; grad atol
stays at the fp16 default of 1e-5 so near-zero gradients keep their
absolute floor. i1e needs the looser rtol because the exponential scaling
places the sampled gradients an order of magnitude closer to zero, so the
same absolute rounding reads as a larger relative error.

Values were taken from the CI logs of this PR (job 95199871251), which
report a maximum relative difference of 1.0042e-3 for special.i1 and
1.0590e-2 for special.i1e; the chosen 5e-3 and 3e-2 clear those by 5.0x
and 2.8x respectively.

Test Plan:

Not reproduced locally -- this checkout has no built PyTorch and no Metal
device, so the values are derived from the CI failure output rather than
measured here. To confirm on an Apple silicon machine:

    PYTORCH_TEST_WITH_SLOW=1 python test/test_mps.py -k output_grad_match_special_i1_mps_float16
    PYTORCH_TEST_WITH_SLOW=1 python test/test_mps.py -k output_grad_match_special_i1e_mps_float16

This commit was authored with the assistance of an AI coding assistant
(Claude Code).
· branch [`colalb1/bessel_backward`](https://github.com/pytorch/pytorch/tree/colalb1/bessel_backward)

colalb1 and others added 5 commits August 16, 2026 19:13
…ckward

Two follow-ups to the Bessel autograd work, both surfaced by the red Mac MPS jobs.

test_output_grad_match_special_modified_bessel_i1_mps_float16 failed on every MPS
runner with a 1.37e-4 absolute difference against the 1.31e-4 the default fp16
threshold allows. This is not a kernel bug: the one mismatching gradient element
has magnitude ~0.121, where an fp16 ulp is 6.1e-5, so the MPS result and the fp16
CPU reference land about two ulps apart. modified_bessel_i1 is added to the
existing fp16 grad-tolerance line that already covers bessel_y0 and bessel_y1,
rather than given a toleranceOverride DecorateInfo like special.i1/i1e, so that
the ops whose backward formulas this PR introduces are all tolerance-tuned in one
place.

The @dtypesIfMPS(float32, float16, bfloat16) on the two new corner-case tests in
test_unary_ufuncs.py never ran anywhere. dtypesIfMPS only writes fn.dtypes["mps"],
which is read exclusively by a generated class whose device_type is "mps", and
test_unary_ufuncs.py instantiates its device tests without allow_mps=True, so no
TestUnaryUfuncsMPS class is ever created (MPS is commented out of the generic
device test bases). PYTORCH_TESTING_DEVICE_ONLY_FOR=mps on that file collects zero
tests. Since CPU has no fp16/bf16 kernels for these Bessel forwards, MPS is the
only backend that can exercise the reduced-precision backward dispatch this PR
adds, so the half-precision half of that coverage moves to TestConsistency in
test_mps.py, which is instantiated with allow_mps=True. The alternative was to set
allow_mps=True on test_unary_ufuncs.py, which would make the decorator live but
instantiates the entire TestUnaryUfuncs class on MPS for the first time; that is
well out of scope for this PR.

Test Plan:

The previously failing test, now passing:

```
PYTORCH_TEST_WITH_SLOW=1 python test/test_mps.py TestConsistencyMPS.test_output_grad_match_special_modified_bessel_i1_mps_float16
```

The new MPS half-precision corner-case tests, none of which were collected before
this change (14 tests, all passing):

```
PYTORCH_TEST_WITH_SLOW=1 python test/test_mps.py -k bessel_zero_limit -k bessel_nan_input
```

Full related coverage, run on an M4 Pro (the -k flags are unittest's, since this
environment has no pytest installed):

```
PYTORCH_TEST_WITH_SLOW=1 python test/test_mps.py -k bessel -k special_i1            # 157 passed
PYTORCH_TEST_WITH_SLOW=1 python test/test_ops.py -k bessel -k special_i1            # 893 passed, 207 skipped
PYTORCH_TEST_WITH_SLOW=1 python test/test_unary_ufuncs.py -k bessel -k special_i1   # 2332 passed, 74 skipped
PYTORCH_TEST_WITH_SLOW=1 python test/functorch/test_ops.py -k bessel -k special_i1  # 182 passed, 42 skipped
PYTORCH_TEST_WITH_SLOW=1 python test/test_ops_gradients.py -k bessel -k special_i1  # 65 passed, 45 skipped
PYTORCH_TEST_WITH_SLOW=1 python test/test_meta.py -k bessel -k special_i1           # 908 passed, 467 skipped
PYTORCH_TEST_WITH_SLOW=1 python test/test_decomp.py -k bessel -k special_i1         # 173 passed
```

test/inductor/test_torchinductor_opinfo.py collects 119 tests for these ops and
skips all of them without a GPU, so the inductor_override_kwargs["cuda"] entries
are only exercised in CI.

The x = 0 limits and NaN propagation were also checked directly on MPS in fp16,
bf16 and fp32: grad(0) is 0.5 for bessel_j1 and modified_bessel_i1, inf for
bessel_y1, and a NaN input yields a NaN gradient for bessel_j1,
modified_bessel_i1, i1 and i1e.

The two remaining red CI jobs are unrelated to this PR:
test_reductions_large_half_tensors_mps_float16 (an MPS fp16 large reduction
returns NaN; it reproduces on a checkout with none of this PR's runtime changes
in play, and the PR touches no reduction or MPS kernel code) and
test_forward_ad_linalg_householder_product_cuda_float32 (a borderline fp32
tolerance miss, 1.34e-5 against 1e-5 allowed, on an op unrelated to Bessel).

This commit was authored with assistance from Claude Code (Claude Opus 5); the
changes and test results were reviewed by me.

Co-Authored-By: Claude Opus 5 <[email protected]>
@colalb1

colalb1 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor Author

@Skylion007 It seems that the tests are passing now. The one failure that Dr CI marked as "probably related" is due to a timeout in the test runner.

@Skylion007

Copy link
Copy Markdown
Collaborator

"The PR enables autograd support for 8 Bessel functions that previously had supports_autograd=False. This adds new gradient test cases to test_ops in the inductor shard, pushing the already-borderline MI350 ROCm job past its 30-minute timeout."

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude best way to fix this?

@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 17m 12s —— View job


Best way to fix the ROCm MI350 inductor timeout

  • Read this PR's inductor/opinfo diff
  • Pull the actual job log for the failing shard
  • Check whether the new gradient cases can explain the timeout
  • Compare the fix options and recommend one

One sentence summary: I don't think this is yours to fix — the numbers say test_ops shard 8/11 blew 3x its own sharding budget while producing zero test output, which a hash-uniform sprinkling of ~7 new gradient tests cannot do, so the right move is to rerun that single job rather than trim coverage or add skips.

Full analysis and the options

What the log actually shows

From job 95863307713, the shards this job ran (it's job-shard 2 of 2, so it gets the even test_ops pytest shards):

shard wall time
test_ops 2/11 12.39 min
test_ops 4/11 8.99 min
test_ops 6/11 15.99 min
test_ops 8/11 39.42 min → killed at the 30 min cap

The kill is retry_shell's per-invocation timeout, not the 300-min job timeout:

Command took >30min, returning 124 (test_ops 8/11)
Got exit code 124
No stepcurrent file found. Either pytest didn't get to run (e.g. import error) or file got deleted

Two details matter more than the raw duration.

1. The shard overran its own budget by 3x, not by a few minutes. The cap isn't arbitrary — run_test.py:672-684 sets timeout = THRESHOLD * 3 and THRESHOLD = 60 * 10 (tools/testing/test_selections.py:45). The same THRESHOLD is what chose 11 shards in the first place: num_shards = ceil(duration / THRESHOLD) (test_selections.py:98-103). So every test_ops shard is sized to land near 10 minutes and is then given 30 minutes before it's killed. Shard 8 didn't creep past a borderline limit; it ran 3x longer than the sharder predicted for it.

2. Nothing was printed between PRINTING LOG FILE and FINISHED PRINTING LOG FILE. Shards 2/4/6 each emitted the full --print-items collection line (I can grep individual bessel node IDs out of their log regions). Shard 8's piped log is empty, and No stepcurrent file found means the lastrun cache key was never written — i.e. pytest_runtest_protocol never fired for a single test (test/conftest.py:447-449). Caveat: pytest's stdout is block-buffered when redirected to a file, so a SIGINT-then-kill can lose the buffer, which makes this suggestive rather than conclusive on its own. Supporting it: the 9 extra minutes between the 30-min cap firing (22:17) and Finished (22:27) are unexplained by wait_for_process's 5-second SIGINT grace (common_utils.py:1218-1232) — a process that slow to die is the signature of a stuck GPU call in D state, not of a busy test loop.

Why the new gradient tests can't be the cause

filter_items_by_shard assigns tests by sha256(nodeid) % num_shards (test/pytest_shard_custom.py:50-57) — a uniform hash, with no locality by op name. So the tests this PR adds are sprinkled evenly across all 11 shards, roughly 8 ops x ~10 new grad/fwd-AD tests / 11 shards ≈ 7 per shard. For that to be the cause, ~7 compiled elementwise-unary tests would have to account for ~29 minutes on shard 8 (~4 min each) while adding nothing measurable to shards 2, 4, and 6, which all came in under their 30-min cap. Under a uniform hash that's not a coherent story.

The DrCI verdict ("already-borderline job pushed past its timeout") is a reasonable prior in general — compiled backward tests on ROCm genuinely aren't cheap — but it doesn't survive the per-shard breakdown. It also isn't a job-level timeout, which is what "borderline job" implies; the job had 300 minutes and used ~100.

Recommendation, in order

1. Rerun just that job. This is the cheapest discriminator and I'd do it before anything else. If it's the hang I think it is, it comes back green. Any push to the branch also retriggers.

2. If it comes back green, force-merge with the reason recorded. The MPS failures that blocked your 2026-08-14 merge attempt are fixed, and this would be the only red left:

@pytorchbot merge -f "ROCm MI350 test_ops shard 8/11 hung pre-collection; unrelated to this PR"

3. If it reproduces on the same shard, then hunt the hang — don't trim coverage. A reproducible 3x overrun on one hash-bucket means one specific test is hanging, and the actionable next step is to name it. The log can't today because the stepcurrent cache was never written; run that shard with output unbuffered so the collection list and per-test progress survive the kill:

PYTHONUNBUFFERED=1 python test/run_test.py --inductor --include test_ops \
    --shard 2 2 --verbose

Then compare the last-started node ID against shard 8's item list. If it lands on one of the new bessel grad tests, an xfail/skip scoped to ROCm is justified at that point — but scoped to the one op that hangs, with the hang filed as an issue, not as a blanket reduction.

What I would not do: raise the timeout or add a skipIfRocm over the new gradient coverage. Both would bury a 3x overrun that the sharder's own estimate says shouldn't exist, and the second would give up the autograd coverage that is the entire point of the PR.

One genuine adjacent observation, not a blocker

Shards 2 and 6 came in at 12.4 and 16.0 minutes against a 10-minute target. So test_ops's recorded timings are stale relative to how fast MI350 actually runs it, and the fleet-wide headroom on this job is thinner than the design intends. That's a dev-infra sharding-data matter (it self-corrects as timing data refreshes post-merge), not something to solve inside this PR — worth a heads-up to whoever owns the ROCm CI capacity if these timeouts keep recurring on unrelated PRs.

On the inductor tolerance entries already in the diff

Unrelated to the timeout, but confirming they're doing their job: the ("special.i1", f16) / ("special.i1e", f16) grad_atol/grad_rtol entries at test/inductor/test_torchinductor_opinfo.py:582-583 are what turned the earlier test_comprehensive_special_i1{,e}_cuda_float16 grad failures green. Those are gone from the current run; no further change needed there.

· branch [`colalb1/bessel_backward`](https://github.com/pytorch/pytorch/tree/colalb1/bessel_backward)

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
Makes the eight low-level Bessel special functions differentiable (backward + forward-mode AD), replacing their `non_differentiable` autograd entries.

Changes:
- `derivatives.yaml`: `auto_element_wise` derivative formulas for `special_bessel_{j0,j1,y0,y1}` and `special_modified_bessel_{i0,i1,k0,k1}`
- `FunctionsManual.{cpp,h}`: new `bessel_j1_backward` handling the `0/0` removable singularity of `J1'` at `x = 0` (limit `1/2`); `I1` reuses the existing `i1_backward`
- OpInfo (`special.py`): enable `supports_forward_ad`, `supports_fwgrad_bwgrad`, and `backward_dtypes` so the ops get gradcheck/gradgradcheck/forward-AD and SciPy reference coverage automatically.
- `test_autograd.py`: add `TestBesselAutograd.test_zero_limit`, the one check OpInfo cannot express since gradcheck cannot differentiate `0/0` at `x=0`

**Questions:**
- `test_zero_limit` currently lives in `test_autograd.py`. Should it move to its own file instead of sitting alongside the autograd engine tests?
- The CPU forward Bessel kernels are only ~1e-7 accurate in float64, which constrains gradient tolerances. Should improving the CPU Bessel ops be a hard blocker for this PR, and should I implement that first before moving forward here?

Pull Request resolved: pytorch#189872
Approved by: https://github.com/Skylion007

Co-authored-by: Claude Opus 5 <[email protected]>
pytorchmergebot pushed a commit to xuhancn/pytorch that referenced this pull request Sep 3, 2026
…or CUDA)

pytorch#189872 added the fp16 grad-tolerance override for special.i1/special.i1e under inductor_override_kwargs["cuda"], which makes the newly enabled fp16 gradient checks pass on CUDA. The same eager-vs-inductor intermediate-precision gap exists on XPU, but the xpu dict was missed, so test_comprehensive_special_i1_xpu_float16 and test_comprehensive_special_i1e_xpu_float16 fail on main.

This change mirrors the CUDA entries in the XPU dict with the same grad_atol=1e-5 and grad_rtol=1e-2 values.

Test Plan:

lintrunner -a test/inductor/test_torchinductor_opinfo.py

I authored this with the assistance of an AI coding assistant.,
pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
#194566)

…or CUDA)

#189872 added the fp16 grad-tolerance override for special.i1/special.i1e under inductor_override_kwargs["cuda"], which makes the newly enabled fp16 gradient checks pass on CUDA. The same eager-vs-inductor intermediate-precision gap exists on XPU, but the xpu dict was missed, so test_comprehensive_special_i1_xpu_float16 and test_comprehensive_special_i1e_xpu_float16 fail on main.

This change mirrors the CUDA entries in the XPU dict with the same grad_atol=1e-5 and grad_rtol=1e-2 values.

Test Plan:

lintrunner -a test/inductor/test_torchinductor_opinfo.py

I authored this with the assistance of an AI coding assistant.,

Pull Request resolved: #194566
Approved by: https://github.com/guangyey, https://github.com/jansel
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
pytorch#194566)

…or CUDA)

pytorch#189872 added the fp16 grad-tolerance override for special.i1/special.i1e under inductor_override_kwargs["cuda"], which makes the newly enabled fp16 gradient checks pass on CUDA. The same eager-vs-inductor intermediate-precision gap exists on XPU, but the xpu dict was missed, so test_comprehensive_special_i1_xpu_float16 and test_comprehensive_special_i1e_xpu_float16 fail on main.

This change mirrors the CUDA entries in the XPU dict with the same grad_atol=1e-5 and grad_rtol=1e-2 values.

Test Plan:

lintrunner -a test/inductor/test_torchinductor_opinfo.py

I authored this with the assistance of an AI coding assistant.,

Pull Request resolved: pytorch#194566
Approved by: https://github.com/guangyey, https://github.com/jansel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source release notes: autograd release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants