Skip to content

[CUDA] Add deterministic bilinear2d backward - #197714

Closed
shuo-ouyang wants to merge 7 commits into
pytorch:mainfrom
shuo-ouyang:feature/deterministic-bilinear2d-backward
Closed

shuo-ouyang wants to merge 7 commits into
pytorch:mainfrom
shuo-ouyang:feature/deterministic-bilinear2d-backward

Conversation

@shuo-ouyang

@shuo-ouyang shuo-ouyang commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Issue

Fixes #166114

Summary

This change adds a deterministic CUDA implementation for non-antialiased 2D bilinear interpolation backward.

The deterministic path assigns one CUDA thread to each grad_input element, gathers all contributing grad_output elements in a fixed order, accumulates using the existing accscalar_t policy, and writes each input gradient once. It does not use global atomics or temporary workspace.

When deterministic algorithms are enabled, CUDA uses the native forward and the new deterministic backward kernel. The existing atomic implementation remains the default non-deterministic path. HIP keeps its existing deterministic decomposition fallback.

Implementation

  • Reuse the existing ROCm input-centric scalar gather helper for common coordinate and weight semantics.
  • Add a CUDA NCHW scalar gather kernel.
  • Add a CUDA NHWC gather kernel with memory::aligned_vector loads and stores.
  • Dispatch 16-byte channel vectors when alignment and channel divisibility allow it: 4-element FP32, 8-element FP16/BF16, or 2-element FP64 aligned vectors. Otherwise, use the scalar NHWC path.
  • Keep the NHWC vector kernel and deterministic CUDA host dispatch under #ifndef USE_ROCM.
  • Preserve the existing HIP deterministic decomposition fallback in torch.nn.functional.interpolate.
  • Leave antialiased bilinear backward and other interpolation modes unchanged.

Correctness

The tests cover align_corners=True/False, upsampling, downsampling, degenerate spatial dimensions, explicit size, scalar and tuple scale_factor, NCHW, NHWC, and repeated deterministic execution.

Results verified locally:

  • Targeted PyTorch tests: 44 passed, 12 skipped.
  • CPU reference comparisons passed for FP16, BF16, FP32, and FP64 within dtype-appropriate tolerances.
  • NHWC tests passed for channel counts 6, 19, and 64 across FP16, BF16, FP32, and FP64.
  • Repeated CUDA deterministic executions were bitwise identical with torch.equal.
  • Explicit scale-factor cases and recompute_scale_factor behavior passed.

Performance

Measurements were collected on an NVIDIA GeForce RTX 3050 Laptop GPU with CUDA 13.0 (sm_86). The input shape is (1, C, 256, 256) and the output shape is (1, C, 512, 512), with align_corners=False. Each path used 20 warmup iterations and 100 timed iterations; timings use synchronized time.perf_counter boundaries and are reported in milliseconds per operation. Results are grouped by channel count, layout, and dtype.

Forward compares the non-deterministic F.interpolate path, the old _upsample_linear_vec decomposition with deterministic algorithms enabled, and the current deterministic F.interpolate path. The current CUDA forward remains on the native implementation.

Channels Layout Dtype Non-deterministic (baseline) Deterministic (baseline) Deterministic (this PR)
64 NCHW FP16 0.493 ms 17.635 ms 0.452 ms
64 NCHW BF16 0.452 ms 17.647 ms 0.450 ms
64 NCHW FP32 0.596 ms 16.702 ms 0.596 ms
64 NCHW FP64 1.962 ms 27.227 ms 1.965 ms
64 NHWC FP16 1.291 ms 21.362 ms 1.310 ms
64 NHWC BF16 1.315 ms 21.362 ms 1.310 ms
64 NHWC FP32 1.424 ms 20.409 ms 1.417 ms
64 NHWC FP64 8.128 ms 31.708 ms 8.129 ms
384 NCHW FP16 2.719 ms 104.319 ms 2.739 ms
384 NCHW BF16 2.704 ms 104.320 ms 2.715 ms
384 NCHW FP32 3.844 ms 98.599 ms 3.843 ms
384 NCHW FP64 11.291 ms OOM 11.320 ms
384 NHWC FP16 7.759 ms 134.993 ms 7.838 ms
384 NHWC BF16 7.934 ms 134.518 ms 7.958 ms
384 NHWC FP32 9.091 ms 129.163 ms 9.090 ms
384 NHWC FP64 48.162 ms OOM 48.188 ms

The current deterministic forward stays close to the non-deterministic native path. The old decomposition is substantially slower across the tested dtypes and layouts. For C=384 FP64, the deterministic decomposition ran out of GPU memory in both layouts.

Backward compares the non-deterministic atomic baseline, the old deterministic decomposition with deterministic algorithms enabled, and the current deterministic gather. Each measurement includes the F.interpolate forward followed by its backward call, matching the end-to-end method used for the trilinear benchmark.

Channels Layout Dtype Non-deterministic (baseline) Deterministic (baseline) Deterministic (this PR)
64 NCHW FP16 3.520 ms 168.670 ms 1.904 ms
64 NCHW BF16 27.077 ms 169.850 ms 1.956 ms
64 NCHW FP32 2.595 ms 168.822 ms 2.115 ms
64 NCHW FP64 10.372 ms 207.387 ms 27.676 ms
64 NHWC FP16 4.172 ms 180.251 ms 1.674 ms
64 NHWC BF16 7.657 ms 180.156 ms 1.679 ms
64 NHWC FP32 2.974 ms 178.842 ms 2.031 ms
64 NHWC FP64 17.282 ms 222.350 ms 21.048 ms
384 NCHW FP16 22.163 ms 1018.923 ms 11.834 ms
384 NCHW BF16 169.814 ms 1022.661 ms 11.970 ms
384 NCHW FP32 15.887 ms 1013.163 ms 13.124 ms
384 NCHW FP64 61.455 ms OOM 163.627 ms
384 NHWC FP16 24.625 ms 1075.850 ms 10.065 ms
384 NHWC BF16 48.449 ms 1076.616 ms 9.976 ms
384 NHWC FP32 18.571 ms 1070.862 ms 14.215 ms
384 NHWC FP64 103.754 ms OOM 125.203 ms

The deterministic kernel is substantially faster than the decomposition baseline for FP16, BF16, and FP32. Its FP64 path remains slower than the non-deterministic atomic baseline for both channel counts and layouts tested. The deterministic decomposition baseline OOMed for C=384 FP64 in both layouts and both operations.

Scope and limitations

  • The new native deterministic gather path is CUDA-only; HIP keeps the existing fallback and dispatch behavior.
  • antialias=True still uses the existing antialiased backward implementation and remains outside this change.
  • Linear, bicubic, trilinear, nearest, and area interpolation are not changed.

Test plan

python test/test_torch.py -k test_deterministic_interpolate_bilinear
python test/test_nn.py -k test_upsamplingBiMode2d

Worked with codex

@pytorch-bot

pytorch-bot Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

🔗 Helpful Links

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

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

✅ No Failures

As of commit 45de6d9 with merge base 6d5f66b (image):
💚 Looks good so far! There are no failures yet. 💚

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

@shuo-ouyang
shuo-ouyang marked this pull request as ready for review September 19, 2026 14:56
@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 21, 2026
@shuo-ouyang

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: nn"

Comment thread test/test_torch.py Resolved
@shuo-ouyang
shuo-ouyang force-pushed the feature/deterministic-bilinear2d-backward branch from 31bfccd to ffcc2e8 Compare September 29, 2026 15:20
@shuo-ouyang

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase -b main

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased feature/deterministic-bilinear2d-backward onto refs/remotes/origin/main, please pull locally before adding more changes (for example, via git checkout feature/deterministic-bilinear2d-backward && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the feature/deterministic-bilinear2d-backward branch from 8219f9f to 65700e9 Compare October 4, 2026 15:01

@eqy eqy left a comment

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.

CI failures look related

Also if this is the same performance as the old non-deterministic path, can that be removed?

@shuo-ouyang

Copy link
Copy Markdown
Contributor Author

@eqy Thanks for checking. The failures I inspected occur in CPU gradcheck under dynamo_wrapped, with an “Expected IntList but got GenericList” assertion in compiled autograd. They do not exercise the new CUDA kernel, but my changes to the shared test may be triggering them. I’ll investigate and adjust the test changes accordingly.

Regarding removing the atomic path, the new implementation is faster for the tested FP16/BF16/FP32 cases, but FP64 is slower—for example, 27.676 ms vs 10.372 ms for NCHW with C=64, including forward and backward. The benchmarks also cover only 2× upsampling on one GPU, so I’d prefer to retain the atomic path for now until broader benchmarks establish that replacing it would not cause performance regressions.

@kurtamohler
kurtamohler self-requested a review October 9, 2026 18:02
Comment thread torch/nn/functional.py Resolved
@shuo-ouyang

Copy link
Copy Markdown
Contributor Author

Hi @kurtamohler, I've addressed all the review comments, and all review threads are now resolved.

Would you mind taking another look when you have a chance?

@shuo-ouyang

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase -b main

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

The CUDA bilinear2d backward path accumulated gradients with atomic adds,
which made deterministic execution unavailable and routed the high-level
CUDA path through a slow decomposition. Add input-centric NCHW and NHWC
gather kernels that assign one thread to each input gradient, accumulate
contributions in a fixed order, and write each result once. Keep the HIP
fallback and existing non-deterministic atomic path unchanged.
Preserve per-corner contributions when interpolation coordinates alias at boundaries, so zero-weight non-finite terms retain IEEE-754 behavior. Keep the merged-weight fast path for distinct corners to avoid a common-case performance regression.

Test Plan:

```bash
/mnt/code-repos/pytorch/.venv/bin/cmake --build build --target torch_cuda --parallel 8
LD_LIBRARY_PATH=/mnt/code-repos/pytorch/build/lib /mnt/code-repos/pytorch/.venv/bin/python test/test_torch.py -k test_deterministic_interpolate_bilinear_nonfinite_zero_weight
LD_LIBRARY_PATH=/mnt/code-repos/pytorch/build/lib /mnt/code-repos/pytorch/.venv/bin/python test/test_torch.py -k test_deterministic_interpolate_bilinear
PATH="/mnt/code-repos/pytorch/.venv/bin:$PATH" /mnt/code-repos/pytorch/.venv/bin/lintrunner -a
```

Authored with assistance from an AI assistant.

Signed-off-by: shuo-ouyang <[email protected]>
Authored with assistance from an AI assistant.

Signed-off-by: shuo-ouyang <[email protected]>
@shuo-ouyang
shuo-ouyang force-pushed the feature/deterministic-bilinear2d-backward branch from a39078f to 45de6d9 Compare October 26, 2026 03:08
@shuo-ouyang

Copy link
Copy Markdown
Contributor Author

@eqy hi, I’ve resolved the merge conflicts and pushed the changes.

@shuo-ouyang

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 5, 2026
@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

@shuo-ouyang
shuo-ouyang deleted the feature/deterministic-bilinear2d-backward branch November 6, 2026 06:12
anatoliylitv added a commit to anatoliylitv/pytorch that referenced this pull request Nov 6, 2026
…atio 6

On ROCm, channels_last backward with C >= 4 and at least six atomics per
grad_input address takes the vectorized NHWC gather from pytorch#197714 instead of
the atomic scatter, and skips the zero-fill. The gather kernels and a shared
launcher are compiled on both platforms; the CUDA deterministic path calls
the same launcher. The ROCm gate sits at function scope so MSVC no longer
sees a directive inside AT_DISPATCH.
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
## Issue
Fixes pytorch#166114

## Summary

This change adds a deterministic CUDA implementation for non-antialiased 2D bilinear interpolation backward.

The deterministic path assigns one CUDA thread to each `grad_input` element, gathers all contributing `grad_output` elements in a fixed order, accumulates using the existing `accscalar_t` policy, and writes each input gradient once. It does not use global atomics or temporary workspace.

When deterministic algorithms are enabled, CUDA uses the native forward and the new deterministic backward kernel. The existing atomic implementation remains the default non-deterministic path. HIP keeps its existing deterministic decomposition fallback.

## Implementation

- Reuse the existing ROCm input-centric scalar gather helper for common coordinate and weight semantics.
- Add a CUDA NCHW scalar gather kernel.
- Add a CUDA NHWC gather kernel with `memory::aligned_vector` loads and stores.
- Dispatch 16-byte channel vectors when alignment and channel divisibility allow it: 4-element FP32, 8-element FP16/BF16, or 2-element FP64 aligned vectors. Otherwise, use the scalar NHWC path.
- Keep the NHWC vector kernel and deterministic CUDA host dispatch under `#ifndef USE_ROCM`.
- Preserve the existing HIP deterministic decomposition fallback in `torch.nn.functional.interpolate`.
- Leave antialiased bilinear backward and other interpolation modes unchanged.

## Correctness

The tests cover `align_corners=True/False`, upsampling, downsampling, degenerate spatial dimensions, explicit `size`, scalar and tuple `scale_factor`, NCHW, NHWC, and repeated deterministic execution.

Results verified locally:

- Targeted PyTorch tests: 44 passed, 12 skipped.
- CPU reference comparisons passed for FP16, BF16, FP32, and FP64 within dtype-appropriate tolerances.
- NHWC tests passed for channel counts 6, 19, and 64 across FP16, BF16, FP32, and FP64.
- Repeated CUDA deterministic executions were bitwise identical with `torch.equal`.
- Explicit scale-factor cases and `recompute_scale_factor` behavior passed.

## Performance

Measurements were collected on an NVIDIA GeForce RTX 3050 Laptop GPU with CUDA 13.0 (`sm_86`). The input shape is `(1, C, 256, 256)` and the output shape is `(1, C, 512, 512)`, with `align_corners=False`. Each path used 20 warmup iterations and 100 timed iterations; timings use synchronized `time.perf_counter` boundaries and are reported in milliseconds per operation. Results are grouped by channel count, layout, and dtype.

Forward compares the non-deterministic `F.interpolate` path, the old `_upsample_linear_vec` decomposition with deterministic algorithms enabled, and the current deterministic `F.interpolate` path. The current CUDA forward remains on the native implementation.

| Channels | Layout | Dtype | Non-deterministic (baseline) | Deterministic (baseline) | Deterministic (this PR) |
| ---: | --- | --- | ---: | ---: | ---: |
| 64 | NCHW | FP16 | 0.493 ms | 17.635 ms | 0.452 ms |
| 64 | NCHW | BF16 | 0.452 ms | 17.647 ms | 0.450 ms |
| 64 | NCHW | FP32 | 0.596 ms | 16.702 ms | 0.596 ms |
| 64 | NCHW | FP64 | 1.962 ms | 27.227 ms | 1.965 ms |
| 64 | NHWC | FP16 | 1.291 ms | 21.362 ms | 1.310 ms |
| 64 | NHWC | BF16 | 1.315 ms | 21.362 ms | 1.310 ms |
| 64 | NHWC | FP32 | 1.424 ms | 20.409 ms | 1.417 ms |
| 64 | NHWC | FP64 | 8.128 ms | 31.708 ms | 8.129 ms |
| 384 | NCHW | FP16 | 2.719 ms | 104.319 ms | 2.739 ms |
| 384 | NCHW | BF16 | 2.704 ms | 104.320 ms | 2.715 ms |
| 384 | NCHW | FP32 | 3.844 ms | 98.599 ms | 3.843 ms |
| 384 | NCHW | FP64 | 11.291 ms | OOM | 11.320 ms |
| 384 | NHWC | FP16 | 7.759 ms | 134.993 ms | 7.838 ms |
| 384 | NHWC | BF16 | 7.934 ms | 134.518 ms | 7.958 ms |
| 384 | NHWC | FP32 | 9.091 ms | 129.163 ms | 9.090 ms |
| 384 | NHWC | FP64 | 48.162 ms | OOM | 48.188 ms |

The current deterministic forward stays close to the non-deterministic native path. The old decomposition is substantially slower across the tested dtypes and layouts. For C=384 FP64, the deterministic decomposition ran out of GPU memory in both layouts.

Backward compares the non-deterministic atomic baseline, the old deterministic decomposition with deterministic algorithms enabled, and the current deterministic gather. Each measurement includes the `F.interpolate` forward followed by its backward call, matching the end-to-end method used for the trilinear benchmark.

| Channels | Layout | Dtype | Non-deterministic (baseline) | Deterministic (baseline) | Deterministic (this PR) |
| ---: | --- | --- | ---: | ---: | ---: |
| 64 | NCHW | FP16 | 3.520 ms | 168.670 ms | 1.904 ms |
| 64 | NCHW | BF16 | 27.077 ms | 169.850 ms | 1.956 ms |
| 64 | NCHW | FP32 | 2.595 ms | 168.822 ms | 2.115 ms |
| 64 | NCHW | FP64 | 10.372 ms | 207.387 ms | 27.676 ms |
| 64 | NHWC | FP16 | 4.172 ms | 180.251 ms | 1.674 ms |
| 64 | NHWC | BF16 | 7.657 ms | 180.156 ms | 1.679 ms |
| 64 | NHWC | FP32 | 2.974 ms | 178.842 ms | 2.031 ms |
| 64 | NHWC | FP64 | 17.282 ms | 222.350 ms | 21.048 ms |
| 384 | NCHW | FP16 | 22.163 ms | 1018.923 ms | 11.834 ms |
| 384 | NCHW | BF16 | 169.814 ms | 1022.661 ms | 11.970 ms |
| 384 | NCHW | FP32 | 15.887 ms | 1013.163 ms | 13.124 ms |
| 384 | NCHW | FP64 | 61.455 ms | OOM | 163.627 ms |
| 384 | NHWC | FP16 | 24.625 ms | 1075.850 ms | 10.065 ms |
| 384 | NHWC | BF16 | 48.449 ms | 1076.616 ms | 9.976 ms |
| 384 | NHWC | FP32 | 18.571 ms | 1070.862 ms | 14.215 ms |
| 384 | NHWC | FP64 | 103.754 ms | OOM | 125.203 ms |

The deterministic kernel is substantially faster than the decomposition baseline for FP16, BF16, and FP32. Its FP64 path remains slower than the non-deterministic atomic baseline for both channel counts and layouts tested. The deterministic decomposition baseline OOMed for C=384 FP64 in both layouts and both operations.
## Scope and limitations

- The new native deterministic gather path is CUDA-only; HIP keeps the existing fallback and dispatch behavior.
- `antialias=True` still uses the existing antialiased backward implementation and remains outside this change.
- Linear, bicubic, trilinear, nearest, and area interpolation are not changed.

## Test plan

```text
python test/test_torch.py -k test_deterministic_interpolate_bilinear
python test/test_nn.py -k test_upsamplingBiMode2d
```

Worked with codex
Pull Request resolved: pytorch#197714
Approved by: https://github.com/eqy
pytorchmergebot pushed a commit to anatoliylitv/pytorch that referenced this pull request Nov 17, 2026
…atio 6

On ROCm, channels_last backward with C >= 4 and at least six atomics per
grad_input address takes the vectorized NHWC gather from pytorch#197714 instead of
the atomic scatter, and skips the zero-fill. The gather kernels and a shared
launcher are compiled on both platforms; the CUDA deterministic path calls
the same launcher. The ROCm gate sits at function scope so MSVC no longer
sees a directive inside AT_DISPATCH.
anatoliylitv added a commit to anatoliylitv/pytorch that referenced this pull request Nov 19, 2026
…atio 6

On ROCm, channels_last backward with C >= 4 and at least six atomics per
grad_input address takes the vectorized NHWC gather from pytorch#197714 instead of
the atomic scatter, and skips the zero-fill. The gather kernels and a shared
launcher are compiled on both platforms; the CUDA deterministic path calls
the same launcher. The ROCm gate sits at function scope so MSVC no longer
sees a directive inside AT_DISPATCH.
pytorchmergebot pushed a commit to anatoliylitv/pytorch that referenced this pull request Nov 19, 2026
…atio 6

On ROCm, channels_last backward with C >= 4 and at least six atomics per
grad_input address takes the vectorized NHWC gather from pytorch#197714 instead of
the atomic scatter, and skips the zero-fill. The gather kernels and a shared
launcher are compiled on both platforms; the CUDA deterministic path calls
the same launcher. The ROCm gate sits at function scope so MSVC no longer
sees a directive inside AT_DISPATCH.
anatoliylitv added a commit to anatoliylitv/pytorch that referenced this pull request Nov 30, 2026
…atio 6

On ROCm, channels_last backward with C >= 4 and at least six atomics per
grad_input address takes the vectorized NHWC gather from pytorch#197714 instead of
the atomic scatter, and skips the zero-fill. The gather kernels and a shared
launcher are compiled on both platforms; the CUDA deterministic path calls
the same launcher. The ROCm gate sits at function scope so MSVC no longer
sees a directive inside AT_DISPATCH.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source 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.

[BUG]interpolate operator triggers severe performance degradation when enabling deterministic computation

6 participants