Skip to content

[MPS] Fix roi_align backward gradient over-accumulation - #9510

Merged
NicolasHug merged 4 commits into
mainfrom
malfet/mps-fix-roi-align-backward
Jul 15, 2026
Merged

NicolasHug merged 4 commits into
mainfrom
malfet/mps-fix-roi-align-backward

Conversation

@malfet

@malfet malfet commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

The backward kernel ran a grid-stride loop dispatched over multiple threadgroups but strided by only one threadgroup's width, so every threadgroup re-processed overlapping output elements and atomic-added each gradient repeatedly.
This is harmless for the forward (idempotent writes, fixed for perf in #9100) but the backward over-accumulated input gradients by a factor that grows with the RoI count (~100x at 512 RoIs), making detection training diverge to NaN on MPS.
Fix mirrors #9100: one thread per pooled-output element via dispatchThreads.

Test Plan:
python -m pytest test/test_ops.py -k "test_backward_mps_consistency"

Authored with assistance from Claude.

The backward kernel ran a grid-stride loop dispatched over multiple threadgroups but strided by only one threadgroup's width, so every threadgroup re-processed overlapping output elements and atomic-added each gradient repeatedly.
This is harmless for the forward (idempotent writes, fixed for perf in #9100) but the backward over-accumulated input gradients by a factor that grows with the RoI count (~100x at 512 RoIs), making detection training diverge to NaN on MPS.
Fix mirrors #9100: one thread per pooled-output element via dispatchThreads.

Test Plan:
  python -m pytest test/test_ops.py -k "test_backward_mps_consistency"

Authored with assistance from Claude.
@pytorch-bot

pytorch-bot Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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

@meta-cla meta-cla Bot added the cla signed label Jun 9, 2026

@NicolasHug NicolasHug left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @malfet , this LGTM, I'll merge once the CI is kind enough to be green (macos jobs are failing on a new conda issue right now, I'm looking into it)

@meta-cla

meta-cla Bot commented Jun 19, 2026

Copy link
Copy Markdown

Hi @malfet!

Thank you for your pull request.

We require contributors to sign our Contributor License Agreement, and yours needs attention.

You currently have a record in our system, but the CLA is no longer valid, and will need to be resubmitted.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@NicolasHug

Copy link
Copy Markdown
Member

I was able to get the CI back to green, I'll be able to merge this once you sign the CLA @malfet (🥲!)

@jveitchmichaelis

jveitchmichaelis commented Jul 13, 2026 •

Copy link
Copy Markdown

I believe this fix should also be applied to roi_pool, ps_roi_align and ps_roi_pool which have the same issue in forward + backward passes.

e.g.

import torch
from torchvision.ops import roi_pool

def grad_sum(dev):
    x = torch.ones(1, 64, 8, 8, device=dev, requires_grad=True)
    rois = torch.tensor([[0.0, 0, 0, 7, 7]], device=dev) # 1 box 
    roi_pool(x, rois, [4, 4]).sum().backward()
    return x.grad.sum()

assert torch.isclose(grad_sum("cpu"), grad_sum("mps"))   # Fails, 1024.0  != 1536.0

@NicolasHug
NicolasHug merged commit 3aadb2d into main Jul 15, 2026
28 of 40 checks passed
@NicolasHug
NicolasHug deleted the malfet/mps-fix-roi-align-backward branch July 15, 2026 09:23
rysk-t added a commit to rysk-t/DeepLabCut that referenced this pull request Sep 2, 2026
Detectors may only run on MPS when all of the following hold: MPS is
built into torch and available, the installed torch is a release
>= 2.12, and the detector variant is in the registry for what it is
about to do. DETECTOR_MPS_VALIDATED_VARIANTS (training and inference)
holds ssdlite; DETECTOR_MPS_INFERENCE_VALIDATED_VARIANTS additionally
holds fasterrcnn_resnet50_fpn and fasterrcnn_resnet50_fpn_v2, whose
predictions matched the CPU. Older torch versions are known to hang or
return corrupted detections on MPS (DeepLabCut#3155, DeepLabCut#2853). Training the Faster
R-CNN variants on MPS hung the GPU (fasterrcnn_resnet50_fpn on the
first iteration, fasterrcnn_resnet50_fpn_v2 hard enough to trigger a
macOS watchdog kernel panic): torchvision's roi_align backward kernel
over-accumulates gradients on MPS (pytorch/vision#9510, not in any
released torchvision yet), which does not affect the forward pass, so
those variants stay off the training registry only.

resolve_device() now applies this gate to detector configs left on
`auto` instead of never selecting MPS for detectors, using the training
registry unless called with for_training=False. The new
resolve_detector_device() helper applies the same gate to an explicit
MPS request, warning with the reason and falling back to the CPU; it is
wired into training and inference in the following commits, so this
commit does not change behaviour on its own.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
rysk-t added a commit to rysk-t/DeepLabCut that referenced this pull request Sep 3, 2026
Detectors may only run on MPS when all of the following hold: MPS is
built into torch and available, the installed torch is a release
>= 2.12, and the detector variant is in the registry for what it is
about to do. DETECTOR_MPS_VALIDATED_VARIANTS (training and inference)
holds ssdlite; DETECTOR_MPS_INFERENCE_VALIDATED_VARIANTS additionally
holds fasterrcnn_resnet50_fpn and fasterrcnn_resnet50_fpn_v2, whose
predictions matched the CPU. Older torch versions are known to hang or
return corrupted detections on MPS (DeepLabCut#3155, DeepLabCut#2853). Training the Faster
R-CNN variants on MPS hung the GPU (fasterrcnn_resnet50_fpn on the
first iteration, fasterrcnn_resnet50_fpn_v2 hard enough to trigger a
macOS watchdog kernel panic): torchvision's roi_align backward kernel
over-accumulates gradients on MPS (pytorch/vision#9510, not in any
released torchvision yet), which does not affect the forward pass, so
those variants stay off the training registry only.

resolve_device() now applies this gate to detector configs left on
`auto` instead of never selecting MPS for detectors, using the training
registry unless called with for_training=False. The new
resolve_detector_device() helper applies the same gate to an explicit
MPS request, warning with the reason and falling back to the CPU; it is
wired into training and inference in the following commits, so this
commit does not change behaviour on its own.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
rysk-t added a commit to rysk-t/DeepLabCut that referenced this pull request Sep 3, 2026
Detectors may only be trained on MPS when all of the following hold: MPS
is built into torch and available, the installed torch is a release
>= 2.12, and the detector variant is in DETECTOR_MPS_VALIDATED_VARIANTS
(currently ssdlite, the default detector). Older torch versions are
known to hang when running detectors on MPS (DeepLabCut#3155), and training the
Faster R-CNN variants on MPS has hung the GPU hard enough to trigger a
macOS watchdog kernel panic (torchvision's roi_align backward kernel
over-accumulates gradients on MPS, pytorch/vision#9510, fixed in
torchvision 0.29.0 but not validated here yet), so those stay off the
registry.

resolve_device() now applies this gate to detector configs left on
`auto` instead of never selecting MPS for detectors. The new
resolve_detector_device() helper applies the same gate to an explicit
MPS request, warning with the reason and falling back to the CPU. It is
wired into training in the next commit, so this commit does not change
behaviour on its own.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
rysk-t added a commit to rysk-t/DeepLabCut that referenced this pull request Sep 4, 2026
Detectors may only be trained on MPS when all of the following hold: MPS
is built into torch and available, the installed torch is a release
>= 2.12, and the detector variant is in DETECTOR_MPS_VALIDATED_VARIANTS
(currently ssdlite, the default detector). Older torch versions are
known to hang when running detectors on MPS (DeepLabCut#3155), and training the
Faster R-CNN variants on MPS has hung the GPU hard enough to trigger a
macOS watchdog kernel panic (torchvision's roi_align backward kernel
over-accumulates gradients on MPS, pytorch/vision#9510, fixed in
torchvision 0.29.0 but not validated here yet), so those stay off the
registry.

resolve_device() now applies this gate to detector configs left on
`auto` instead of never selecting MPS for detectors. The new
resolve_detector_device() helper applies the same gate to an explicit
MPS request, warning with the reason and falling back to the CPU. It is
wired into training in the next commit, so this commit does not change
behaviour on its own.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
rysk-t added a commit to rysk-t/DeepLabCut that referenced this pull request Sep 4, 2026
Detectors may only be trained on MPS when all of the following hold: MPS
is built into torch and available, the installed torch is a release
>= 2.12, and the detector variant is in DETECTOR_MPS_VALIDATED_VARIANTS
(currently ssdlite, the default detector). Older torch versions are
known to hang when running detectors on MPS (DeepLabCut#3155), and training the
Faster R-CNN variants on MPS has hung the GPU hard enough to trigger a
macOS watchdog kernel panic (torchvision's roi_align backward kernel
over-accumulates gradients on MPS, pytorch/vision#9510, fixed in
torchvision 0.29.0 but not validated here yet), so those stay off the
registry.

resolve_device() now applies this gate to detector configs left on
`auto` instead of never selecting MPS for detectors. The new
resolve_detector_device() helper applies the same gate to an explicit
MPS request, warning with the reason and falling back to the CPU. It is
wired into training in the next commit, so this commit does not change
behaviour on its own.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants