Repository navigation
Conversation
🔗 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 ( 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. |
| # 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"), |
There was a problem hiding this comment.
Okay, this should DEFINITELY be an xfail
There was a problem hiding this comment.
Also we should just implement clamp_min, it's easy enough to implement, probably just need a few more dispatches
There was a problem hiding this comment.
Changed this to an xfail. Will make a different PR for clamp_min.
There was a problem hiding this comment.
@Skylion007 PR for adding uints to the clamp functions on CPU and CUDA: #189953
There was a problem hiding this comment.
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}andspecial_modified_bessel_{i0,i1,k0,k1}intools/autograd/derivatives.yaml. - Introduce
bessel_j1_backwardinFunctionsManual.{h,cpp}to special-case thex=0gradient limit forJ1'. - Update OpInfo definitions to enable autograd + forward AD testing for these ops, and add an explicit
x=0gradient-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. |
|
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), |
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
Why do you need domain now, but not before?
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
@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 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, gradcheck would fail. domain=(0, None) keeps the samples in the region where the function and its derivatives are well-defined.
There was a problem hiding this comment.
Chapter 10 should support the math-related statements above
|
@claude review this and double check the op tests are correct. |
|
Claude finished @Skylion007's task in 14m 16s —— View job PR Review: #189872 — Bessel autograd supportOne 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 Full reviewDerivative formulas (
|
| ) | ||
| 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) |
There was a problem hiding this comment.
Won't the torch.double fail on MPS?
@dtypes(torch.double) like the above would fix this.
| 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); |
There was a problem hiding this comment.
Why masked_fill and not where like the above?
There was a problem hiding this comment.
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.
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
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
|
Fix the remaining tests. |
@Skylion007 The order-1 derivatives have the form A few options to correct this:
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. |
|
Nah, you can just raise the tolerance of the fp16 using a dtype override probably |
|
@claude show you can add the dtype precision override to the opinfo and other tests here for the new functionality |
|
Claude finished @Skylion007's task in 23m 3s —— View job Adding the fp16 grad tolerance overrides via OpInfo
One sentence summary: Yes — the override can be expressed entirely as OpInfo What the failures actually are, and the patchThe remaining failures are MPS-only, and there are two of them, not threeWorth correcting the list in your earlier comment before picking tolerances. I read the logs from the latest commit (
The CUDA inductor ones are green now; the only inductor failure left in that run is Note the two MPS failures land on different shards, which is why only Measured magnitudesFrom the log output, deterministic across reruns and across runners:
The patchAttaching this to the OpInfo (rather than --- 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,
),
One thing worth confirming before merging
Push blockedI committed this locally as I retried three times with the same result. @colalb1 — the diff above applies cleanly on top of Commit message |
…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]>
|
@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. |
|
"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." |
|
@claude best way to fix this? |
|
Claude finished @Skylion007's task in 17m 12s —— View job Best way to fix the ROCm MI350 inductor timeout
One sentence summary: I don't think this is yours to fix — the numbers say Full analysis and the optionsWhat the log actually showsFrom job 95863307713, the shards this job ran (it's job-shard 2 of 2, so it gets the even
The kill is 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 — 2. Nothing was printed between Why the new gradient tests can't be the cause
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 order1. 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: 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 --verboseThen compare the last-started node ID against shard 8's item list. If it lands on one of the new bessel grad tests, an What I would not do: raise the timeout or add a One genuine adjacent observation, not a blockerShards 2 and 6 came in at 12.4 and 16.0 minutes against a 10-minute target. So On the inductor tolerance entries already in the diffUnrelated to the timeout, but confirming they're doing their job: the |
|
@pytorchbot merge |
Merge startedYour 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 |
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]>
…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.,
#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
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
Makes the eight low-level Bessel special functions differentiable (backward + forward-mode AD), replacing their
non_differentiableautograd entries.Changes:
derivatives.yaml:auto_element_wisederivative formulas forspecial_bessel_{j0,j1,y0,y1}andspecial_modified_bessel_{i0,i1,k0,k1}FunctionsManual.{cpp,h}: newbessel_j1_backwardhandling the0/0removable singularity ofJ1'atx = 0(limit1/2);I1reuses the existingi1_backwardspecial.py): enablesupports_forward_ad,supports_fwgrad_bwgrad, andbackward_dtypesso the ops get gradcheck/gradgradcheck/forward-AD and SciPy reference coverage automatically.test_autograd.py: addTestBesselAutograd.test_zero_limit, the one check OpInfo cannot express since gradcheck cannot differentiate0/0atx=0Questions:
test_zero_limitcurrently lives intest_autograd.py. Should it move to its own file instead of sitting alongside the autograd engine tests?cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo