Skip to content

grid_sample: support mode='bicubic' with 5-D input, including its double backward - #194787

Closed
vboussot wants to merge 30 commits into
pytorch:mainfrom
vboussot:gridsample-tricubic
Closed

vboussot wants to merge 30 commits into
pytorch:mainfrom
vboussot:gridsample-tricubic

Conversation

@vboussot

@vboussot vboussot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

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, 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

  • Passes lint (spin fixlint)
  • Added/updated tests
  • Updated documentation (if applicable)
  • 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.

@pytorch-bot

pytorch-bot Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

🔗 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 (image):

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.

@pytorch-bot pytorch-bot Bot added the release notes: nn release notes category label Aug 25, 2026
@linux-foundation-easycla

linux-foundation-easycla Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread test/test_nn.py Resolved
Comment thread aten/src/ATen/native/GridSampler.cpp Resolved
Comment thread torch/csrc/autograd/FunctionsManual.cpp Resolved
static_cast<GridSamplerInterpolation>(interpolation_mode) ==
GridSamplerInterpolation::Bicubic),
"grid_sampler(): bicubic interpolation only supports 4D input");
static_cast<GridSamplerInterpolation>(interpolation_mode) !=

ghost Aug 25, 2026

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.

Wait, huh. I don't think this is right?

ghost Aug 25, 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.

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?

ghost Aug 26, 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.

Moved MPS to the two-argument form in 597fd77, so this overload is now torch-xpu-ops only.

Comment thread torch/csrc/autograd/FunctionsManual.cpp Outdated
-((((3 * (A + 2)) * t2) - (2 * (A + 3))) * t2),
(((-3 * A) * t3) + (10 * A)) * t3 - (8 * A)},
-1);
return std::make_pair(c, dc);

ghost Aug 25, 2026

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.

Suggested change
return std::make_pair(c, dc);
return std::make_pair(std::move(c), std::move(dc));

ghost Aug 25, 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.

Done.


// Overload for a backend whose 5D sampler implements bilinear and nearest only.
// See NOTE [ grid_sampler Native Functions ].
inline void check_grid_sampler_3d(

ghost Aug 25, 2026

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.

Do this in a overload here is nasty.

ghost Aug 25, 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.

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.

ghost Aug 26, 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.

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.

@Skylion007

ghost commented Aug 25, 2026

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

ghost commented Aug 25, 2026 •

Copy link
Copy Markdown

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 torch.compile traces clean then fails at runtime), and the non-finite-coordinate fix from b035d6b has no regression test.

Full review

PR Review: #194787

Summary

Adds mode='bicubic' for 5-D grid_sample (separable Keys A=-3/4 over the third axis) with forward, backward and double backward on CPU and CUDA. The numerics are sound — I verified resolve_cubic_taps against get_value_bounded, and the open-coded coefficients and their first and second derivatives in FunctionsManual.cpp against get_cubic_upsample_coefficients / get_cubic_coefficients_grad term by term, including the chain-rule sign flips on taps 2 and 3. The three follow-up commits genuinely address the earlier automated review. Remaining problems are in test instantiation, backend/meta parity, and missing regression coverage.


Testing

1. test_grid_sample_3d_bicubic_matches_2d will error on the MPS CI job. test/test_nn.py:11653

It is @onlyNativeDeviceTypes + @dtypes(torch.double). 'mps' is in NATIVE_DEVICES (common_utils.py:474, checked at common_device_type.py:1974), and get_desired_device_type_test_bases adds MPSTestBase when allow_mps and TEST_MPS (common_device_type.py:1126) — which holds on the Mac runners, where run_test.py:1832 additionally narrows to MPS only. There is no generic float64 filter: _get_dtypes (common_device_type.py:596-605) just returns test.dtypes[device_type], so a float64 MPS variant is generated, and line 11658's torch.randn(..., device=device, dtype=torch.double) hits TORCH_CHECK_TYPE(dtype != kDouble, ...) in aten/src/ATen/mps/EmptyTensor.cpp:45 → TypeError: ... the MPS framework doesn't support float64.

So the @expectedFailureMPS on the sibling tests is load-bearing, not belt-and-braces — see test_nn.py:9498, 9596, 9709, 11003, 11030, all with the same float64 comment. Add @expectedFailureMPS. It is also right on the merits: even at float32 the MPS variant would error, since GridSampler.mm:133 rejects 5-D bicubic — the dtype TypeError just fires first.

test_nn.py does run in the mps config (run_test.py:1843, .ci/pytorch/macos-test.sh:43, mac-mps.yml), so this is a real trunk break, not theoretical.

2. No regression test for the b035d6b fix — the headline correctness fix of the follow-ups. Nothing anywhere asserts (a) a NaN grid coordinate yields NaN in 5-D bicubic as it does in 4-D, or (b) that an infinite voxel at index 0 no longer poisons the sum through a zeroed coefficient. OpInfo cannot catch this: sample_inputs_grid_sample uses make_tensor(low=-2, high=2), which never produces NaN/Inf. test_grid_sample_nan_inf (test_nn.py:11675) is 4-D nearest only. A small device-generic test with inf at input[0,0,0,0,0] and a NaN grid coordinate, asserting the 5-D result matches the unsqueezed 4-D one across all three padding modes, would lock in the fix that motivated the commit. The checklist treats a bug fix without a regression test as blocking.

3. Adding 'bicubic' to test_grid_sample_3d's mode loop is redundant with the OpInfo change, and expensive. test_nn.py:4906

test_fn_grad already gradchecks all six 5-D bicubic padding x align_corners combinations via the OpInfo samples this PR adds. The loop adds 12 more double-precision 5-D gradchecks over 7 shapes x 2 input_requires_grad values, at 64 taps each. Per the CLAUDE.md/checklist "Use OpInfo" rule, operator numerics should come from OpInfo rather than manual loops. The only thing this loop adds over OpInfo is CPU-vs-CUDA equality, which test_compare_cpu covers. Recommend reverting the one-line change.

Note also that this test only ever calls gradcheck, never gradgradcheck — so the PR's headline feature, the 5-D bicubic double backward, gets no coverage from it.

4. The double backward's output_mask branches are untested. sample_inputs_grid_sample sets requires_grad on both input and grid, so gradgrad only exercises the all-True mask. The output_mask[0]-only and [1]-only paths of grid_sampler_3d_double_backward — which is where the new conditional B_dx/d2c* construction lives — never run.

5. The error-path test is now effectively unverified on PR CI. test_nn.py:4329-4333

The previously-unconditional assertion is now behind if torch.backends.mps.is_available(), so the new 3-arg check_grid_sampler_3d overload — its only in-tree caller is mps/operations/GridSampler.mm:133 — is asserted nowhere on pull. Since this is genuinely MPS-specific, it belongs in test/test_mps.py. If it stays here, use the TEST_MPS constant to match the adjacent if TEST_CUDA rather than calling is_available() directly.

6. @parametrize_test instead of nested loops. test_nn.py:11665-11666 nests for padding_mode / for align_corners. TestNNDeviceType already uses @parametrize_test extensively (e.g. 9810-9813, 11013), so it composes fine here and gives per-configuration failure reporting.


Infrastructure

7. The meta kernel now accepts 5-D bicubic unconditionally, so MPS/XPU lose trace-time errors. torch/_meta_registrations.py:5905, 5983, 6004

register_meta keys the global meta_table on the op alone, and FakeTensor prefers the meta kernel while only propagating the input device. Removing the check means torch.compile / torch.export of 5-D bicubic on an MPS or XPU fake tensor now traces successfully and then throws at runtime — a trace/eager divergence that used to be caught up front. Device-conditional meta kernels are an accepted pattern in this file (e.g. _meta_registrations.py:4246, 7555 branch on device.type), so gating on input.device.type in ("mps", "xpu") would restore parity.

Related: GridSamplerInterpolation (_meta_registrations.py:5888-5891) is now dead code — the removed check was its only consumer. Delete it.

8. check_grid_sampler_3d's 3-argument overload is redundant, which is the concern @Skylion007 raised. GridSamplerUtils.h:85-97

MPS is the only in-tree caller, and it already rejects bicubic two lines later with a better message: GridSampler.mm:151-152 ("Unsupported Bicubic interpolation") and GridSampler.mm:336-337 (TORCH_CHECK_NOT_IMPLEMENTED naming the backend). Both predate this PR. So the overload's TORCH_CHECK is unreachable in-tree — it fires only for out-of-tree grid_sampler_3d_xpu, and it does so with a generic "this backend" message the backend could state better itself. The two-overload split also gives check_grid_sampler_3d_backward a confusing pair where the 4-arg form calls the 3-arg form which calls the 2-arg form (GridSamplerUtils.h:141-149).

The cleaner shape is one 2-argument check_grid_sampler_3d plus an explicit TORCH_CHECK_NOT_IMPLEMENTED in each backend that lacks the mode — which is what MPS already does. If the overload is kept purely to hold torch-xpu-ops' hand, that motivation belongs in the comment, and it should use TORCH_CHECK_NOT_IMPLEMENTED (the checklist requires the specific variant for NotImplementedError).

Also note the error text changed from "bicubic interpolation only supports 4D input" to "...not supported by this backend". Any out-of-tree assertRaisesRegex on the old string breaks. Worth calling out in the BC section of the description, which currently says only "Backends that do not implement it still raise, with a message that says so."

9. XPU is unverified. grid_sampler_3d_xpu (native_functions.yaml:2876, 2887) lives in third_party/torch-xpu-ops and is not in this checkout. The PR description asserts it is safe because it calls the 3-arg overload; that is probably right, since the 3-arg form was the only signature before this PR. But the safety now rests on an out-of-tree call site keeping a signature choice, and if it ever moves to the 2-arg form it silently returns the uninitialized at::empty output. A comment on the overload naming torch-xpu-ops as the reason it exists would make that contract visible.


Performance

10. The double backward allocates 32 full-volume tensors where it needs 1. FunctionsManual.cpp:8781-8792

gs_scatter3d_bc_multi ends with at::zeros({N, C, D*H*W}, ...).scatter_add(...) (8324-8326), so each of the 16 chunks allocates a fresh [N,C,D,H,W], and d_input = d_input + contrib allocates another. At the 128^3 output the chunking was introduced to fix, that is 32 full-volume allocations and 16 out-of-place adds. Passing an accumulator into the scatter, or at minimum using add_ as the 2-D code does (8617), recovers most of it. Same pattern in d_grad_output + contrib (8773) and in the accumulate lambda (8803-8805), which uses total + part where 2-D uses .add_().

11. taps is gathered on all 16 chunks even when only d_input is requested. FunctionsManual.cpp:8753-8754

d_input needs grad_output and the weights, not the input values — output_mask[1]'s branch never reads taps. Guarding the gather on output_mask[0] || output_mask[2] skips 16 gathers in the grid-gradient-only case.

12. The 3-D forward kernel's launch bounds may now cost the bilinear path occupancy. cuda/GridSampler.cu:155

interpolation_mode is a runtime argument, so all three modes compile into one kernel, and C10_LAUNCH_BOUNDS_1(512) with a 512-thread launch (908, 919) caps it at 128 registers per thread — exactly the figure in your description. Register allocation is per-kernel (max over the CFG), so if the bicubic branch raises the peak, the 5-D bilinear path pays reduced occupancy for a branch it never takes. No spill instructions execute on the bilinear path, so this is an occupancy question only.

This is worth checking rather than asserting: the 2-D forward is C10_LAUNCH_BOUNDS_1(256) (line 25), which is above the 255-register hardware max and therefore effectively non-binding, so the pre-existing 2-D bicubic-in-a-shared-kernel precedent does not carry over to the 3-D forward's tighter budget. Could you post nvcc -Xptxas -v for grid_sampler_3d_kernel<float,int> before and after, plus a 5-D bilinear forward benchmark? The 3-D backward is bounded at 256 (line 552) and has headroom, so this applies to the forward only.


Code Quality

13. Non-ASCII characters in new comments. FunctionsManual.cpp:8297 (gs_scatter3d_bc_multi's header) uses a →. CLAUDE.md requires ASCII-only in newly added comments; use ->. The pre-existing arrows in the 2-D helpers are fine to leave alone.

14. std::make_pair(c, dc) should move. FunctionsManual.cpp:8719 — as @Skylion007 noted. The nearest analogue, gs_compute_coords, does move (8153).

15. Dead work in both bicubic branches. The bicubic paths recompute the coordinate from the raw x/y/z, so ix/iy/iz and gix_mult/giy_mult/giz_mult computed above are calculated and discarded — GridSampler.cpp:131-133 and 381-383, cuda/GridSampler.cu:201-203 and 617-619. The 4-D code avoids this by reusing those variables. Minor, but the rename from ix to x in this PR is what made the dead stores possible.

16. Undocumented invariant in resolve_cubic_taps. GridSampler.cpp:51-72

It inverts the 4-D order: get_value_bounded truncates then bounds-checks the integer, while this bounds-checks the float then casts. These agree only because compute_coordinates maps integer-valued inputs to integer-valued outputs for every padding mode — including the reflection path, where |in - min| on a half-integer folds back to an integer. If that were not so, a tap landing in (-1, 0) would read voxel 0 in 4-D and be dropped in 5-D. The comment explains the non-finite motivation but not this load-bearing invariant; it is worth a line since it is exactly the kind of global context a local reader cannot infer.

17. Note the half/bfloat16 divergence from 4-D. The 5-D path accumulates in opmath_t and sums 64 terms flat, where the 4-D path uses scalar_t and nests two cubic_interp1d stages. The 5-D result is the more accurate one, but it will not match a 4-D reduction of the same problem in reduced precision — which is why test_grid_sample_3d_bicubic_matches_2d passes at torch.double only. Worth stating in the description, and worth adding a torch.float variant of that test with a tolerance, since fp32 64-tap accumulation is exactly where this would surface.

18. The OpInfo device branch silently excludes backends with no signal. common_methods_invocations.py:8799

Branching on torch.device(device).type is an accepted pattern here (precedent at 2577, 8353, 9463), and including ROCm via cuda is right. But XPU, MPS, MTIA and privateuse1 get zero coverage with nothing that fires when they implement the mode — unlike an xfail, which flips to a failure. A TODO naming the backends would at least leave a marker.


Recommendation

Request Changes

Blocking: (1) the MPS variant of the new test errors on trunk, (2) no regression test for the b035d6b non-finite fix, (7) the meta kernel drops trace-time rejection for MPS/XPU.

Worth resolving before merge: (8) the redundant check_grid_sampler_3d overload @Skylion007 flagged, (10)/(11) the double backward's per-chunk allocations, and (12) a -Xptxas -v check that the shared 3-D forward kernel did not cost the bilinear path occupancy.

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.

| Branch: `gridsample-tricubic`

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) {

ghost Aug 25, 2026

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.

I think you might simplify these loops a bit using the utility to compute bounds?

ghost Aug 25, 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.

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.

Comment thread test/test_nn.py Outdated
self.assertTrue(torch.equal(out1, out2))

@onlyNativeDeviceTypes
@dtypes(torch.double)

ghost Aug 25, 2026

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.

Use pytest parameterize or at least subtest.

ghost Aug 25, 2026 •

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 not use OpInfo for coverage?

ghost Aug 25, 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.

Use pytest parameterize or at least subtest.

Done, @parametrize_test on padding_mode and align_corners.

ghost Aug 25, 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.

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.

@vboussot

ghost commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

On the shared-kernel question from the review: it does cost. Same build, only GridSampler.cu/.cuh
swapped between main and this branch, 200 launches amortised, best of 5 rounds, RTX PRO 5000,
5-D forward:

case main this branch
bilinear 128^3 -> 64^3 0.0210 ms 0.0273 ms
bilinear 256^3 -> 128^3 0.2905 ms 0.2978 ms
nearest 128^3 -> 64^3 0.0195 ms 0.0236 ms
nearest 256^3 -> 128^3 0.1390 ms 0.1712 ms

ptxas -v for grid_sampler_3d_kernel, every dtype and index type: 62-64 registers on main,
110-128 on this branch. Allocation is per kernel and the three modes share one, so bilinear and
nearest pay for a branch they never take.

Fixing it by giving bicubic its own kernel, forward and backward, leaving the existing one
byte-identical to main. I'll post the numbers again once that is in.

@vboussot
vboussot force-pushed the gridsample-tricubic branch from c49ad2f to 597fd77 Compare August 25, 2026 22:55
@vboussot
vboussot requested a review from malfet as a code owner August 25, 2026 22:55
@pytorch-bot pytorch-bot Bot added the ciflow/mps Run MPS tests (subset of trunk) label Aug 25, 2026
@pytorch-bot

ghost commented Aug 25, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@vboussot
vboussot requested a review from Skylion007 August 25, 2026 22:57
@vboussot

ghost commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

Split is in, forward and backward.

I built three libraries from the same tree, differing only in GridSampler.cu and
GridSampler.cuh, and measured them interleaved: six passes each, every pass the best of eight
batches of 200 launches. fp32, one channel, align_corners=False, zeros padding, on an RTX PRO 5000
Blackwell laptop.

5-D forward main one shared kernel bicubic split out
bilinear 128^3 -> 64^3 0.0213 ms 0.0294 ms 0.0216 ms
bilinear 256^3 -> 128^3 0.3566 ms 0.3885 ms 0.3663 ms
nearest 128^3 -> 64^3 0.0158 ms 0.0211 ms 0.0161 ms
nearest 256^3 -> 128^3 0.1386 ms 0.1647 ms 0.1390 ms

grid_sampler_3d_kernel<float, int> uses 64 registers and no stack frame on main, 128 registers and
32 B of frame when bicubic shares it, and 64 with no frame again once bicubic has its own. That
kernel and grid_sampler_3d_backward_kernel<float, int> also disassemble to the same 1968 and 2712
SASS instructions as the build carrying main's kernels, so bilinear and nearest are untouched.

The bicubic kernels use 108 and 123 registers, no stack frame, on the int32 instantiations.

@Skylion007

ghost commented Aug 26, 2026

Copy link
Copy Markdown
Collaborator

@claude review this PR

@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 26, 2026
@Skylion007

ghost commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

ghost commented Aug 27, 2026 •

Copy link
Copy Markdown

Re-review in progress

  • Fetch base and read the incremental diff (c870e824..597fd779)
  • Verify the MPS test instantiation fix — expectedFailureMPS is correct, holds for both dtypes
  • Review the restructured check_grid_sampler_3d
  • Verify the meta-kernel parity fix — found a problem, verifying
  • Review the new split CUDA bicubic kernels
  • Review the chunked double backward
  • Consolidate and fact-check findings
  • Post the review

View job run | Branch: gridsample-tricubic

@Skylion007

ghost commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

@codex-connector review this PR

@chatgpt-codex-connector

ghost commented Aug 27, 2026

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/mps Run MPS tests (subset of trunk) ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: autograd release notes category release notes: nn 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.

grid_sample: bicubic supports 4-D input only, no volumetric (tricubic) mode

5 participants