Skip to content

[CUDA] Fix AvgPool2d backward handling of zero-padding - #188494

Closed
eqy wants to merge 1 commit into
pytorch:mainfrom
eqy:avgpoolnhwc
Closed

eqy wants to merge 1 commit into
pytorch:mainfrom
eqy:avgpoolnhwc

Conversation

@eqy

@eqy eqy commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

To fix #188344

Original test from #35855 didn't actually pass padding which is why we didn't see it

authored with codex

cc @ptrblck @msaroufim @tinglvv @nWEIdia

@eqy
eqy requested review from Aidyn-A and syed-ahmed as code owners June 29, 2026 23:01
@eqy eqy added module: cuda Related to torch.cuda, and CUDA support in general open source module: correctness (silent) issue that returns an incorrect result silently release notes: cuda release notes category topic: bug fixes topic category labels Jun 29, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 3 New Failures

As of commit 349794f with merge base c1bbf1f (image):

NEW FAILURES - The following jobs have failed:

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

@eqy
eqy requested a review from ngimel June 29, 2026 23:06
@drisspg

drisspg commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

@claude this fix looks correct and makes sense to me, my curious question is why wasnt this noticed for so long / curious if you have any insights into this specific setup as well im curious if you can do a wider code base search and see if there are any other problems of a similar form that we have missed

@claude

claude Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Claude finished @drisspg's task in 2m 15s —— View job


Analysis

  • Understand the root cause of the bug
  • Explain why it went unnoticed for so long
  • Wider codebase search for similar issues

@drisspg Great questions. Here's what I found.

Root cause

The avg_pool2d backward kernels use a gather formulation: each thread owns one input element (h, w) and walks the set of output windows (ph, pw) that contributed to it. The mapping from an input element to its contributing windows assumes the input coordinate is expressed in the padded coordinate space, because the forward window start is hstart = ph * stride_h - pad_h. Inverting that to find which windows touch a given input element requires adding back pad:

const int phstart = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;
const int phend   = min(h / stride_h + 1, pooled_height);

The NCHW (avg_pool2d_backward_out_cuda_frame) kernel already did this correctly (AveragePool2d.cu:141-142 has + pad_w / + pad_h). The NHWC (..._nhwc) variant did not — it computed w/h straight from the flat index with no padding offset. So with non-zero padding the window range [phstart, phend) is shifted, and gradients get accumulated from the wrong output windows (and boundary input rows/cols silently receive no/incorrect gradient). With padding=0 the two are identical, which is why everything else worked. The fix just makes NHWC match NCHW.

Why it went unnoticed for so long

Two things lined up:

  1. The only broken path was NHWC backward + non-zero padding. Forward (both layouts) is a gather over outputs deriving input starts from output coords, so it never needed this inversion. NCHW backward was already correct. So the bug was confined to one narrow combination: channels-last and padding > 0 and the backward pass.
  2. The test that was supposed to cover it never actually enabled padding. The test added in Implement avg_pool2d kernel for channels_last  #35855 took a padding argument in its helper, but the nn.AvgPool2d(...) modules were constructed without forwarding padding=padding — so the module always ran with padding=0, and the grad tensor was sized for padding=0 too. The padded cases were dead code as far as the kernel was concerned. This PR's diff is exactly the fix for that gap: it threads padding=padding into both the test and reference module constructors and sizes the grad accordingly, which is what finally surfaced the bug. (The two padding=2 cases also had to drop to padding=1 because padding must be <= kernel_size/2.)

So it's the classic "the test exercised the happy path and the asserting test was itself subtly inert" situation, combined with the bug living only in the less-common memory format.

Wider codebase search for similar problems

I checked the sibling pooling kernels for the same gather/padded-coordinate hazard:

Kernel Backward formulation At risk?
AveragePool2d.cu NCHW backward gather, padded coords ✅ already correct
AveragePool2d.cu NHWC backward gather, padded coords ❌ this bug (fixed here)
AveragePool3d.cu backward (both _atomic and plain) scatter — thread owns an output element, derives input window from output coords (tstart = oFrame*dT - padT), writes/atomic-adds into input ✅ immune by construction
cpu/AvgPoolKernel.cpp backward scatter over output coords ✅ immune
AdaptiveAveragePooling*.cu no padding concept ✅ N/A
DilatedMaxPool*, FractionalMaxPool*, MaxUnpooling index-driven scatter (stored argmax indices) ✅ not affected

The key structural insight: only the 2D avg-pool backward uses the gather formulation that needs the explicit + pad coordinate translation. Everything else either scatters from output coords (where padding is naturally handled) or has no padding. So this looks like an isolated case rather than a systemic pattern — I did not find another kernel with the same latent bug.

If you want extra assurance, the one thing worth adding is an opcheck / gradcheck-style parametrized test that sweeps (memory_format, padding, stride, count_include_pad) for avg-pool so the NHWC+padding combination can't silently regress again — the current helper(...) enumeration is good but easy to under-cover.

The fix itself looks correct to me.
(branch: avgpoolnhwc)

@eqy

eqy commented Jun 30, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchmergebot merge

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

@pytorch-auto-revert

Copy link
Copy Markdown

@pytorchbot revert -m "Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable" -c autorevert

This PR is attributed to have caused regression in:

Note: This revert was accelerated by the AI advisor: AI advisor: related (confidence=0.98)

Please investigate and fix the issues.
@claude Can you please read this revert comment, follow the links and read the errors, to then give a brief diagnostics on the cause of the error? If you judge the error to be legitimate reason for a revert, please provide brief guidance on how the author could fix it.

@claude

claude Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Claude finished @pytorch-auto-revert[bot]'s task in 1m 17s —— View job


Autorevert diagnosis: legitimate, but a one-line fix

  • Read the failing job log (inductor test-osdc)
  • Diagnose whether the failure is caused by this PR
  • Provide fix guidance

Failing test: test_modules.py::TestModuleCUDA::test_memory_format_nn_AvgPool2d_cuda_float32 (job log)

Failure mode: Failed: Unexpected success (not a numeric/assertion failure):

FAILED test/test_modules.py::TestModuleCUDA::test_memory_format_nn_AvgPool2d_cuda_float32 - Failed: Unexpected success
== 1 failed, 179 passed, 37 skipped, 2 xfailed, 2 rerun in 167.45s ==
FAILED CONSISTENTLY: test/test_modules.py::TestModuleCUDA::test_memory_format_nn_AvgPool2d_cuda_float32

Is the revert legitimate?

Yes — this PR caused it, but it's a stale test annotation, not a real regression. In fact it's positive proof the fix works.

test_memory_format for nn.AvgPool2d on CUDA was marked unittest.expectedFailure in torch/testing/_internal/common_modules.py:4192-4197:

# The difference between channels last backward and
# channels first backward of AvgPool2d on CUDA is too large
# See https://github.com/pytorch/pytorch/issues/107201
DecorateInfo(
    unittest.expectedFailure,
    'TestModule',
    'test_memory_format',
    active_if=operator.itemgetter('training'),   # backward only
    device_type='cuda',),

That xfail describes exactly the bug this PR fixed: channels-last (NHWC) backward disagreeing with channels-first (NCHW) backward. Now that the NHWC kernel computes gradients correctly, the channels-last vs channels-first comparison matches, the test passes — and since it's still tagged expectedFailure, the harness reports an unexpected success (a hard failure). Note issue #107201 is the same family of "NHWC avg-pool backward is wrong with padding" symptom this PR resolves.

This combination isn't exercised on the PR's own CI signal because it lives on the inductor test-osdc job, which is why the PR went green and the autorevert tripped post-merge.

How to fix (so it can re-land)

Remove the now-obsolete expectedFailure decorator and close out the stale issue reference. In torch/testing/_internal/common_modules.py, the ModuleInfo(torch.nn.AvgPool2d, ...) skips=(...) entry at lines 4188-4198 should drop the DecorateInfo block entirely (the skips tuple then becomes empty, or just remove that single entry):

ModuleInfo(torch.nn.AvgPool2d,
           module_inputs_func=module_inputs_torch_nn_AvgPool2d),

Then re-run locally to confirm both the previously-xfailed case and the rest pass:

python test/test_modules.py TestModuleCUDA.test_memory_format_nn_AvgPool2d_cuda_float32

Worth double-checking the float64 / chalf variants of the same test on CUDA too, in case any of them were implicitly relying on the same skip. Since this PR's correctness change is already approved and validated, folding the decorator removal into the re-land is all that's needed.
(branch: claude/pr-188494-20260630-2026)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

pytorchmergebot added a commit that referenced this pull request Jun 30, 2026
…)"

This reverts commit 7f9c3fb.

Reverted #188494 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](#188494 (comment)))
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@eqy your PR has been successfully reverted.

@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Jun 30, 2026
@eqy

eqy commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

#188345 was merged

@eqy eqy closed this Jul 6, 2026
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
vishalgoyal316 pushed a commit to vishalgoyal316/pytorch that referenced this pull request Jul 16, 2026
…ch#188494)"

This reverts commit 7f9c3fb.

Reverted pytorch#188494 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#188494 (comment)))
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch#188494)"

This reverts commit 7f9c3fb.

Reverted pytorch#188494 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#188494 (comment)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/trunk Trigger trunk jobs on your pull request Merged module: correctness (silent) issue that returns an incorrect result silently module: cuda Related to torch.cuda, and CUDA support in general open source release notes: cuda release notes category Reverted topic: bug fixes topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

avg_pool2d backward returns wrong input gradients on CUDA for channels_last inputs when padding > 0

5 participants