Repository navigation
[BE]: Update grid_sample bicubic impl for 5D - #194776
Closed
Skylion007 wants to merge 2 commits into
Closed
Skylion007 wants to merge 2 commits into
Skylion007 wants to merge 2 commits into
Conversation
Skylion007
requested review from
Aidyn-A,
albanD,
eqy,
jbschlosser and
syed-ahmed
as code owners
August 25, 2026 18:36
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194776
Note: Links to docs will display an error until the docs builds have been completed. ❌ 42 New Failures, 3 Unclassified FailuresAs of commit 16fc224 with merge base 48c8844 ( NEW FAILURES - The following jobs have failed:
UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Skylion007
marked this pull request as draft
August 25, 2026 18:43
Skylion007
marked this pull request as draft
August 25, 2026 18:43
Skylion007
force-pushed
the
skylion007/update-gs-bicubic-5d-2026-08-25
branch
from
August 25, 2026 18:51
45e6657 to
2bc1d11
Compare
Skylion007
commented
Aug 25, 2026
| const TensorBase& grad_output, | ||
| int64_t interpolation_mode | ||
| ) { | ||
| (void)interpolation_mode; |
Collaborator
Author
There was a problem hiding this comment.
Todo fix this too
4 tasks done
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 18, 2026
…ble backward (#194787) ## Issue Fixes #194738 ## Summary `grid_sample` accepts 4-D and 5-D input, but `mode='bicubic'` only worked for 4-D. This adds the 5-D case: the same separable Keys kernel (A = -3/4) applied over the third axis, with forward, backward and double backward on CPU and CUDA. The motivation is in the issue. Medical volumes are resampled through a stored transform or a displacement field, which is exactly what `grid_sample` does, and cubic is the usual interpolation order for intensity data (ITK uses `BSplineInterpolateImageFunction`, SimpleITK `sitkBSpline`). Until now a 3-D warp had to fall back to trilinear or gather the 64 neighbours by hand. This came up in [KonfAI](https://github.com/fideus-labs/KonfAI), a deep-learning framework for medical imaging, where that hand-written gather lives in `konfai/data/sampling.py`. #194776 adds the same feature. I had this ready before I saw it, and it differs in three ways that may be worth picking up either way: - **The double backward is implemented.** `grid_sampler_3d_double_backward` only handled bilinear, so second-order tests raise `NotImplemented` on the new mode. Here it handles bicubic like the 2-D version does, with 64 taps instead of 16. That keeps the new OpInfo samples in the autograd suites: `test_fn_gradgrad` and functorch's `vjpvjp` and `vmapvjpvjp` pass instead of being skipped. - **The forward resolves each axis's four taps once per output voxel**, instead of nesting `cubic_interp1d` over `get_value_bounded`. On one RTX PRO 5000, a 128^3 volume on a 64^3 grid, float32, best of five: 0.23 ms vs 0.43 ms for the nested form, which maps the padding per tap per channel instead of once per axis per voxel. - **`check_grid_sampler_3d` gains a form that only checks the rank.** CPU, CUDA and MPS call it; MPS still refuses bicubic in its own wrapper. The form that takes the mode stays for `torch-xpu-ops`, which calls it at the commit `third_party/xpu.txt` pins and whose 5-D sampler has bilinear and nearest only, with a TODO to drop it. All four kernels share one new helper, `resolve_cubic_taps`. It returns the four taps of one axis: their coefficients, the index each one reads, and (for the backward) each coefficient's derivative. A tap dropped by the padding carries a negative index, contributes zero and keeps its coefficient, so the 64-tap sum needs no per-tap bounds check. ## Testing `sample_inputs_grid_sample` now yields the mode for 5-D input on every backend, six samples. On mps and xpu, where eager refuses the mode, the tests those samples fail carry strict `expectedFailure` entries (plus one in `common_mps.py` for MPS `TestConsistency`), so each flips to a failure the moment a backend implements it. The set was derived per test: one that consumes only the first sample, swallows the raise, or folds a raising sample into "partially supported" keeps passing and is not marked, since a strict xfail on a passing test is itself a failure. Every suite that reads `sample_inputs` picks the samples up: `test_ops`, `test_ops_gradients` including `gradgrad`, `test_meta`, `test_proxy_tensor`, `test_decomp`, `test_autograd`, and functorch's `vjp`, `vjpvjp` and `vmapvjpvjp`. All pass locally. Three suites do not see them, none of it new to this mode. Anything reading `reference_inputs` gets the reference generator instead of the samples, since defining `reference_inputs_func` replaces the set rather than extending it: that is `test_vmap`'s batch-rule test, and `test_compare_cpu`, which carries `@skipCUDAIfNotRocm` and so does not run on CUDA for any op. Forward AD is not implemented for `grid_sampler_3d` at all, so the OpInfo leaves `supports_forward_ad` false and `test_ops_fwd_gradients` skips the op. And `nn.functional.grid_sample` is in `inductor_one_sample`, where only the first sample runs. `bicubic` also joins the mode loop in `test_grid_sample_3d`, which checks values, CPU/CUDA agreement, `gradcheck` on input and grid, and the empty and 1-voxel shapes. Two new `TestNNDeviceType` tests, parametrized over padding mode and `align_corners`, compare the 5-D kernel against the 4-D one on a volume that is constant along the third axis: `test_grid_sample_3d_bicubic_matches_2d` in float64 and float32, and `test_grid_sample_3d_bicubic_non_finite` on NaN, infinite and far coordinates. The error check that asserted the old refusal now asserts the one MPS raises itself. Outside the test suite, the forward matches an independent 64-tap reference to 1e-15 in double for all three padding modes and both `align_corners` settings, and agrees with a hand-written separable Keys A=-3/4 tricubic to 1.2e-13. ## Benchmarks float32, best of five, on one RTX PRO 5000 Blackwell and a 24-core host. The last column is a plain hand-written walk over the 64 neighbours, which is what a 3-D cubic warp needs today. Forward (ms): | case | bicubic | bilinear | 64-tap gather | |---|---|---|---| | CUDA 128^3 -> 64^3, 1 channel | 0.21 | 0.04 | 11.72 | | CUDA 128^3 -> 64^3, 3 channels | 0.55 | 0.08 | 10.13 | | CUDA 256^3 -> 128^3, 1 channel | 1.48 | 0.39 | 55.06 | | CPU 128^3 -> 64^3, 1 channel | 17.35 | 5.86 | 300.18 | | CPU 256^3 -> 128^3, 1 channel | 503.00 | 175.00 | 4058.43 | Backward, input and grid (ms): | case | bicubic | bilinear | |---|---|---| | CUDA 128^3 -> 64^3, 1 channel | 0.95 | 0.36 | | CUDA 256^3 -> 128^3, 1 channel | 17.15 | 4.09 | | CPU 128^3 -> 64^3, 1 channel | 75.70 | 18.11 | | CPU 256^3 -> 128^3, 1 channel | 2258.45 | 562.57 | ## Review follow-ups - A tap dropped by zero padding carries index -1 and contributes a zero value with its coefficient kept, matching the 4-D convention; the double backward masks dropped taps with `where()` before any product, so an aliased `Inf` can no longer turn into `NaN`, and it walks the taps four at a time instead of materialising 64 index tensors. - The CUDA mode keeps its own forward and backward kernels: sharing them cost the existing modes their registers (64 to 128, measured slowdowns on bilinear and nearest); split, `grid_sampler_3d_kernel` and its backward disassemble to the same SASS as main. - The tap extent stays in `index_t` through the padding on the 64-bit kernels and the reflection parity is taken with `fmod`, so no float reaches an integer conversion. - The meta gate keys on `device_hint`, so an mps or xpu fake tensor fails closed at trace time; single-sided `output_mask`, half/bfloat16 5-D bicubic, the `int64` kernel and non-finite inputs each have targeted tests. - Known and deferred: the double backward accumulates out of place for vmap and allocates per chunk (follow-up), and the three not-implemented wordings differ per backend. ## Checklist - [x] Passes lint (`spin fixlint`) - [x] Added/updated tests - [x] Updated documentation (if applicable) - [x] Included benchmark results (for PRs impacting perf) ## BC-breaking? No. A 5-D input with `mode='bicubic'` used to raise an error and now returns a sample. Backends that do not implement it still raise, in three wordings that predate this PR except the last: - `grid_sampler_3d: Unsupported Bicubic interpolation`, MPS forward, a `TORCH_CHECK` - `grid_sampler(): bicubic interpolation with 5D input is not implemented for <device>`, the MPS backward and the overload torch-xpu-ops calls, both `TORCH_CHECK_NOT_IMPLEMENTED` - `grid_sampler(): bicubic interpolation with 5D input is not supported on <device>`, the meta kernel The exception types differ where it matters: `TORCH_CHECK_NOT_IMPLEMENTED` reaches the fake-tensor fallback, a plain `TORCH_CHECK` propagates. Two behaviour changes outside the new mode: - The 4-D double backward masks dropped taps with `where()` instead of multiplying by 0, so an `Inf` or `NaN` at a dropped tap no longer turns the gradient into `NaN`. - Under reflection padding, far outside the grid (past 2^31 folds, around 1e9 in normalized coordinates), 5-D bicubic takes the fold parity with `fmod` while the 4-D helpers count folds in an int, so the two ranks can return different values there. Pull Request resolved: #194787 Approved by: https://github.com/Skylion007
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 ##194738