Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194787
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit 9287da6 with merge base 81deebd ( CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c870e8248e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| static_cast<GridSamplerInterpolation>(interpolation_mode) == | ||
| GridSamplerInterpolation::Bicubic), | ||
| "grid_sampler(): bicubic interpolation only supports 4D input"); | ||
| static_cast<GridSamplerInterpolation>(interpolation_mode) != |
There was a problem hiding this comment.
Wait, huh. I don't think this is right?
There was a problem hiding this comment.
CPU/CUDA call the 2-arg one above, so they get the mode. I kept the 3-arg one for backends that don't have it. MPS turns out not to need it, it already raises at GridSampler.mm:152, so I can move MPS to the 2-arg form and this is XPU-only. Want me to?
There was a problem hiding this comment.
Moved MPS to the two-argument form in 597fd77, so this overload is now torch-xpu-ops only.
| -((((3 * (A + 2)) * t2) - (2 * (A + 3))) * t2), | ||
| (((-3 * A) * t3) + (10 * A)) * t3 - (8 * A)}, | ||
| -1); | ||
| return std::make_pair(c, dc); |
There was a problem hiding this comment.
| return std::make_pair(c, dc); | |
| return std::make_pair(std::move(c), std::move(dc)); |
|
|
||
| // Overload for a backend whose 5D sampler implements bilinear and nearest only. | ||
| // See NOTE [ grid_sampler Native Functions ]. | ||
| inline void check_grid_sampler_3d( |
There was a problem hiding this comment.
Do this in a overload here is nasty.
There was a problem hiding this comment.
Yeah, it's ugly. It's compat, though: at the commit we pin in third_party/xpu.txt (2c058ad), torch-xpu-ops calls the 3-arg form from sycl/GridSampler.cpp:1195 and :1775, and neither its 3D forward nor backward functor has a bicubic branch. Dropping the overload is what the XPU build on #194776 is failing on: GridSampler.cpp:1775:3: error: no matching function for call to 'check_grid_sampler_3d'. Happy to put a TODO on it and drop it at the next pin bump.
There was a problem hiding this comment.
Restructured in 597fd77. CPU, CUDA and MPS now call check_grid_sampler_3d(input, grid), which only
checks the rank. MPS already refused bicubic in its own wrapper, forward and backward, so nothing
changes for it. That leaves torch-xpu-ops as the only caller of the form that takes the mode, and it
left the backward form with no caller at all, so I dropped that one. The form that remains has a TODO.
commented
Aug 25, 2026
|
@claude review this PR |
|
Claude finished @Skylion007's task in 37m 27s —— View job Reviewed the tricubic implementation — the kernel math and the double-backward formula check out against the 4-D convention, but there are three things I'd want fixed before merge: the new device-generic test will error on the MPS CI job, the meta kernel now accepts a mode that MPS/XPU still reject (so Full reviewPR Review: #194787SummaryAdds Testing1. It is So the
2. No regression test for the 3. Adding
Note also that this test only ever calls 4. The double backward's 5. The error-path test is now effectively unverified on PR CI. The previously-unconditional assertion is now behind 6. Infrastructure7. The meta kernel now accepts 5-D bicubic unconditionally, so MPS/XPU lose trace-time errors.
Related: 8. MPS is the only in-tree caller, and it already rejects bicubic two lines later with a better message: The cleaner shape is one 2-argument Also note the error text changed from 9. XPU is unverified. Performance10. The double backward allocates 32 full-volume tensors where it needs 1.
11.
12. The 3-D forward kernel's launch bounds may now cost the bilinear path occupancy.
This is worth checking rather than asserting: the 2-D forward is Code Quality13. Non-ASCII characters in new comments. 14. 15. Dead work in both bicubic branches. The bicubic paths recompute the coordinate from the raw 16. Undocumented invariant in It inverts the 4-D order: 17. Note the half/bfloat16 divergence from 4-D. The 5-D path accumulates in 18. The OpInfo device branch silently excludes backends with no signal. Branching on RecommendationRequest Changes Blocking: (1) the MPS variant of the new test errors on trunk, (2) no regression test for the Worth resolving before merge: (8) the redundant The core numerics are in good shape and the perf case for the fused-tap forward is well made — this is mostly about test instantiation and backend parity rather than the algorithm. |
| for (const auto k : c10::irange(4)) { | ||
| for (const auto j : c10::irange(4)) { | ||
| const opmath_t weight_zy = z_coeffs[k] * y_coeffs[j]; | ||
| if (every_tap_reads) { |
There was a problem hiding this comment.
I think you might simplify these loops a bit using the utility to compute bounds?
There was a problem hiding this comment.
Tried that first: get_value_bounded_3d + nested cubic_interp1d, same shape as #194776. That maps the padding per tap per channel instead of once per axis per voxel: 0.43ms vs 0.23ms on 128^3 -> 64^3 fp32 on an RTX PRO 5000, 101 registers no spill vs 128 with ~250B. The every_tap_reads split is separate, without it the per-tap test blocks the CPU vectorizer, 21ms vs 16.4ms. Can switch if you prefer the simpler shape.
| self.assertTrue(torch.equal(out1, out2)) | ||
|
|
||
| @onlyNativeDeviceTypes | ||
| @dtypes(torch.double) |
There was a problem hiding this comment.
Use pytest parameterize or at least subtest.
There was a problem hiding this comment.
Why not use OpInfo for coverage?
There was a problem hiding this comment.
Use pytest parameterize or at least subtest.
Done, @parametrize_test on padding_mode and align_corners.
There was a problem hiding this comment.
Why not use OpInfo for coverage?
Good question. The OpInfo samples are in this PR, so the mode does get the full battery there:
dtypes, autograd, meta, compile.
These two tests cover something OpInfo can't express. They compare 5-D against 4-D on the same
data rather than an op against a reference, and sample_inputs_grid_sample draws from
make_tensor(low=-2, high=2), so it never produces the NaN or Inf that the second one checks.
Happy to drop either one if you'd rather keep the coverage in OpInfo alone.
commented
Aug 25, 2026
|
On the shared-kernel question from the review: it does cost. Same build, only
Fixing it by giving bicubic its own kernel, forward and backward, leaving the existing one |
c49ad2f to
597fd77
Compare
|
|
commented
Aug 26, 2026
|
Split is in, forward and backward. I built three libraries from the same tree, differing only in
The bicubic kernels use 108 and 123 registers, no stack frame, on the int32 instantiations. |
commented
Aug 26, 2026
|
@claude review this PR |
commented
Aug 27, 2026
|
@claude review this PR |
Re-review in progress
|
commented
Aug 27, 2026
|
@codex-connector review this PR |
commented
Aug 27, 2026
|
To use Codex here, create a Codex account and connect to github. |

Issue
Fixes #194738
Summary
grid_sampleaccepts 4-D and 5-D input, butmode='bicubic'only worked for 4-D. This adds the 5-Dcase: 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_sampledoes, and cubic is the usual interpolationorder for intensity data (ITK uses
BSplineInterpolateImageFunction, SimpleITKsitkBSpline).Until now a 3-D warp had to fall back to trilinear or gather the 64 neighbours by hand. This came up
in 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:
grid_sampler_3d_double_backwardonly handled bilinear,so second-order tests raise
NotImplementedon the new mode. Here it handles bicubic like the 2-Dversion does, with 64 taps instead of 16. That keeps the new OpInfo samples in the autograd
suites:
test_fn_gradgradand functorch'svjpvjpandvmapvjpvjppass instead of being skipped.cubic_interp1doverget_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_3dgains a form that only checks the rank. CPU, CUDA and MPS call it; MPSstill 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.txtpins and whose 5-D sampler has bilinear andnearest 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_samplenow yields the mode for 5-D input on every backend, six samples. On mpsand xpu, where eager refuses the mode, the tests those samples fail carry strict
expectedFailureentries (plus one in
common_mps.pyfor MPSTestConsistency), so each flips to a failure themoment 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_inputspicks the samples up:test_ops,test_ops_gradientsincludinggradgrad,test_meta,test_proxy_tensor,test_decomp,test_autograd, and functorch'svjp,vjpvjpandvmapvjpvjp. All pass locally.Three suites do not see them, none of it new to this mode. Anything reading
reference_inputsgetsthe reference generator instead of the samples, since defining
reference_inputs_funcreplaces theset rather than extending it: that is
test_vmap's batch-rule test, andtest_compare_cpu, whichcarries
@skipCUDAIfNotRocmand so does not run on CUDA for any op. Forward AD is not implementedfor
grid_sampler_3dat all, so the OpInfo leavessupports_forward_adfalse andtest_ops_fwd_gradientsskips the op. Andnn.functional.grid_sampleis ininductor_one_sample,where only the first sample runs.
bicubicalso joins the mode loop intest_grid_sample_3d, which checks values, CPU/CUDA agreement,gradcheckon input and grid, and the empty and 1-voxel shapes. Two newTestNNDeviceTypetests,parametrized over padding mode and
align_corners, compare the 5-D kernel against the 4-D one on avolume that is constant along the third axis:
test_grid_sample_3d_bicubic_matches_2din float64 andfloat32, and
test_grid_sample_3d_bicubic_non_finiteon 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_cornerssettings, and agrees with a hand-written separableKeys 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):
Backward, input and grid (ms):
Review follow-ups
where()before any product, so an aliasedInfcan no longer turn intoNaN, and it walks the taps four at a time instead of materialising 64 index tensors.grid_sampler_3d_kerneland its backward disassemble to the same SASS as main.index_tthrough the padding on the 64-bit kernels and the reflection parity is taken withfmod, so no float reaches an integer conversion.device_hint, so an mps or xpu fake tensor fails closed at trace time; single-sidedoutput_mask, half/bfloat16 5-D bicubic, theint64kernel and non-finite inputs each have targeted tests.Checklist
spin fixlint)BC-breaking?
No. A 5-D input with
mode='bicubic'used to raise an error and now returns a sample. Backends thatdo not implement it still raise, in three wordings that predate this PR except the last:
grid_sampler_3d: Unsupported Bicubic interpolation, MPS forward, aTORCH_CHECKgrid_sampler(): bicubic interpolation with 5D input is not implemented for <device>, the MPSbackward and the overload torch-xpu-ops calls, both
TORCH_CHECK_NOT_IMPLEMENTEDgrid_sampler(): bicubic interpolation with 5D input is not supported on <device>, the meta kernelThe exception types differ where it matters:
TORCH_CHECK_NOT_IMPLEMENTEDreaches the fake-tensorfallback, a plain
TORCH_CHECKpropagates.Two behaviour changes outside the new mode:
where()instead of multiplying by 0, so anInforNaNat a dropped tap no longer turns the gradient intoNaN.fmodwhile the 4-D helpers count folds in an int, so the two ranks can return different values there.