Skip to content

[CUDA] Fix reentrant deadlock in torch.cuda._lazy_call - #182948

Closed
iupaikov-amd wants to merge 4 commits into
pytorch:mainfrom
iupaikov-amd:iupaikov_lazy_call_random_fix_upstream
Closed

iupaikov-amd wants to merge 4 commits into
pytorch:mainfrom
iupaikov-amd:iupaikov_lazy_call_random_fix_upstream

Conversation

@iupaikov-amd

@iupaikov-amd iupaikov-amd commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes a deadlock where a callback passed to torch.cuda._lazy_call re-enters _lazy_call, e.g. via torch.cuda.set_rng_state or torch.cuda.manual_seed. _initialization_lock is a non-reentrant threading.Lock, so the nested acquisition blocks forever. Originally encountered on ROCm while running larger models under torch.compile.

There are two reentrancy paths, both fixed here:

  1. Already initialized: callbacks used to run while holding _initialization_lock, so a nested _lazy_call deadlocked. Callbacks now run outside the lock: a fast path runs them immediately when CUDA is initialized, and otherwise the lock is held only for the queue-or-run decision, with the callback invoked after release if initialization won the race.
  2. Queued callback during initialization: _lazy_init drains _queued_calls while holding the lock and with _initialized still False, so a queued callback that re-enters _lazy_call deadlocked on its own thread's lock. _lazy_call now mirrors _lazy_init's reentrancy guard and runs the callback immediately when _tls.is_initializing is set; torch._C._cuda_init() has already completed at that point, so this is safe.

Regression tests test_lazy_call_reentrant_set_rng_state_does_not_deadlock and test_lazy_call_reentrant_queued_does_not_deadlock run each scenario in a subprocess with a generous timeout. Both fail with a deadlock timeout before the fix and pass after (verified on a ROCm gfx90a host).

torch/mtia/__init__.py and torch/xpu/__init__.py have the same callback-under-lock pattern and would need the same treatment in a follow-up.

Parts of this PR (the queued-path fix, second regression test, and this description) were drafted with the assistance of Claude Code and reviewed by a human.

@pytorch-bot

pytorch-bot Bot commented May 8, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (9 Unrelated Failures)

As of commit 8e86afd with merge base 2472115 (image):

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@iupaikov-amd

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label May 8, 2026
@jithunnair-amd jithunnair-amd added ciflow/inductor ciflow/inductor-rocm Trigger "inductor" config CI on ROCm ciflow/trunk Trigger trunk jobs on your pull request ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 labels May 8, 2026
@pytorch-bot

pytorch-bot Bot commented May 8, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/inductor-rocm.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/dtensor
  • ciflow/dynamo
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi355
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/inductor-rocm-mi355
  • ciflow/mps
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/periodic-rocm-mi355
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-mi355
  • ciflow/rocm-navi31
  • ciflow/rocm-nightly
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/tsan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/unstable
  • ciflow/vllm
  • ciflow/win-arm64
  • ciflow/xpu

Please add the new label to .github/pytorch-probot.yml

@pytorch-bot

pytorch-bot Bot commented May 11, 2026 •

Copy link
Copy Markdown

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

@iupaikov-amd iupaikov-amd changed the title [DO NOT MERGE] [TESTING] Added a guard in _lazy_call to avoid deadlocks [CUDA] Fix reentrant deadlock in torch.cuda._lazy_call May 11, 2026
@iupaikov-amd
iupaikov-amd marked this pull request as ready for review May 11, 2026 14:53
@liangel-02 liangel-02 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 11, 2026
@iupaikov-amd

Copy link
Copy Markdown
Contributor Author

@liangel-02 Hello, can you tell me if the triaged tag on this PR is signaling that it is ready to be merged or should we ping additional people to take a look at this?

@iupaikov-amd

Copy link
Copy Markdown
Contributor Author

cc @jeffdaily

@jataylo
jataylo requested review from jeffdaily, malfet and suo June 26, 2026 15:20
jataylo pushed a commit to ROCm/pytorch that referenced this pull request Jul 24, 2026
This fixes deadlock with torch.compile while running bigger models in
MAD engine.

This is a cherry-pick of upstream PR:
pytorch#182948

Made with [Cursor](https://cursor.com)
jataylo pushed a commit to ROCm/pytorch that referenced this pull request Jul 24, 2026
This fixes deadlock with torch.compile while running bigger models in
MAD engine.

This is a cherry-pick of upstream PR:
pytorch#182948

Made with [Cursor](https://cursor.com)
jataylo pushed a commit to ROCm/pytorch that referenced this pull request Jul 24, 2026
This fixes deadlock with torch.compile while running bigger models in
MAD engine.

This is a cherry-pick of upstream PR:
pytorch#182948

Made with [Cursor](https://cursor.com)
jataylo pushed a commit to ROCm/pytorch that referenced this pull request Jul 24, 2026
This fixes deadlock with torch.compile while running bigger models in
MAD engine.

This is a cherry-pick of upstream PR:
pytorch#182948

Made with [Cursor](https://cursor.com)
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

iupaikov-amd and others added 4 commits August 18, 2026 11:11
The earlier commits on this PR fix the reentrant deadlock only for the already-initialized path. The queued path still deadlocks: if _lazy_call(outer) runs before CUDA is initialized, outer lands in _queued_calls and is later invoked by _lazy_init, which drains the queue while holding _initialization_lock and with _initialized still False. When outer re-enters _lazy_call (e.g. via torch.cuda.set_rng_state or torch.cuda.manual_seed), the nested call falls through the is_initialized() fast path and blocks on the non-reentrant lock its own thread already holds.

Fix by mirroring _lazy_init's own reentrancy guard: also run the callback immediately when _tls.is_initializing is set. torch._C._cuda_init() has already completed at that point, so immediate execution is safe and matches what the drain would do anyway.

Also refactor the regression test into a shared helper, add a queued-path variant, and raise the subprocess timeout from 15s to 60s: the pass path exits quickly regardless of the limit, and 15s is tight for torch import plus CUDA init on slow CI.

Test Plan:

On a ROCm host (gfx90a), ran the new tests against a pre-fix build; both fail with the deadlock timeout, confirming they catch both bug variants:

    cd test && python test_cuda.py -v -k lazy_call_reentrant

Then exec'd the patched _lazy_call from this branch into the installed torch and ran both subprocess scenarios directly; both complete without deadlock. CI runs the tests against the fully built fix.

Authored with the assistance of Claude Code.
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased iupaikov_lazy_call_random_fix_upstream onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout iupaikov_lazy_call_random_fix_upstream && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the iupaikov_lazy_call_random_fix_upstream branch from 5b648fa to 8e86afd Compare August 18, 2026 11:11
@iupaikov-amd

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 3 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@jithunnair-amd jithunnair-amd added ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 ciflow/rocm-navi31 Trigger "default" config CI on ROCm Navi31 ciflow/inductor-rocm-mi350 Trigger "inductor" config CI on ROCm MI350 ciflow/inductor-rocm-mi300 Trigger "inductor" config CI on ROCm MI300/MI325 ciflow/inductor-rocm-mi200 Trigger "inductor" config CI on ROCm MI200 keep-going Don't stop on first failure, keep running tests until the end labels Aug 18, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 18, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/inductor-rocm-mi350.
Currently recognized labels are

  • ciflow/b200
  • ciflow/b200-distributed
  • ciflow/b200-symm-mem
  • ciflow/binaries
  • ciflow/binaries_libtorch
  • ciflow/binaries_wheel
  • ciflow/docker
  • ciflow/dtensor
  • ciflow/h100
  • ciflow/h100-cutlass-backend
  • ciflow/h100-distributed
  • ciflow/h100-symm-mem
  • ciflow/inductor
  • ciflow/inductor-cu126
  • ciflow/inductor-micro-benchmark
  • ciflow/inductor-micro-benchmark-cpu-x86
  • ciflow/inductor-pallas
  • ciflow/inductor-perf-compare
  • ciflow/inductor-perf-test-nightly-rocm-mi300
  • ciflow/inductor-perf-test-nightly-rocm-mi350
  • ciflow/inductor-perf-test-nightly-x86-zen
  • ciflow/inductor-perf-test-nightly-xpu
  • ciflow/inductor-periodic
  • ciflow/inductor-rocm-mi200
  • ciflow/inductor-rocm-mi300
  • ciflow/mps
  • ciflow/nightly
  • ciflow/op-benchmark
  • ciflow/periodic
  • ciflow/periodic-rocm-mi200
  • ciflow/periodic-rocm-mi300
  • ciflow/pull
  • ciflow/riscv64
  • ciflow/rocm-mi200
  • ciflow/rocm-mi300
  • ciflow/rocm-navi31
  • ciflow/rocm-nightly
  • ciflow/rocm-preview
  • ciflow/s390
  • ciflow/slow
  • ciflow/slow-rocm-mi200
  • ciflow/torchtitan
  • ciflow/triton_binaries
  • ciflow/trunk
  • ciflow/tsan
  • ciflow/unstable
  • ciflow/win-arm64
  • ciflow/xpu

Please add the new label to .github/pytorch-probot.yml

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@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

leewayx added a commit to leewayx/pytorch that referenced this pull request Aug 19, 2026
…atter_realizes_expensive_src

### Summary

Resolve conflict with pytorch main by merging the upstream addition of
test_scatter_realizes_expensive_src into the refactored TestSchedulerCuda class.

### Changes

- Add DeterministicGuard to common_utils imports (required by the new test method)
- Add test_scatter_realizes_expensive_src to TestSchedulerCuda, adapted to the
  refactored class structure: remove @onlyCUDA (class is already only_for="cuda"),
  change device="cuda" to device parameter, add device to method signature

### Motivation

Upstream commit cec50d8 (pytorch#182948) added test_scatter_realizes_expensive_src to
the original TestScheduler class in test_inductor_scheduler.py. Our refactoring PR
split TestScheduler into Generic/Accelerator/Cuda classes, causing a merge conflict.
This commit resolves the conflict by placing the new method in TestSchedulerCuda
(the CUDA-specific class) and adapting it to use the device parameter pattern
consistent with the other CUDA methods in the refactored file.

### Test Plan

python test/inductor/test_inductor_scheduler.py

Authored with AI assistant.
jithunnair-amd pushed a commit to ROCm/pytorch that referenced this pull request Aug 25, 2026
This fixes deadlock with torch.compile while running bigger models in
MAD engine.

This is a cherry-pick of upstream PR:
pytorch#182948

Made with [Cursor](https://cursor.com)

(cherry picked from commit 24cf333)
jithunnair-amd pushed a commit to ROCm/pytorch that referenced this pull request Aug 27, 2026
This fixes deadlock with torch.compile while running bigger models in
MAD engine.

This is a cherry-pick of upstream PR:
pytorch#182948

Made with [Cursor](https://cursor.com)

(cherry picked from commit 24cf333)
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
Fixes a deadlock where a callback passed to `torch.cuda._lazy_call` re-enters `_lazy_call`, e.g. via `torch.cuda.set_rng_state` or `torch.cuda.manual_seed`. `_initialization_lock` is a non-reentrant `threading.Lock`, so the nested acquisition blocks forever. Originally encountered on ROCm while running larger models under `torch.compile`.

There are two reentrancy paths, both fixed here:

1. **Already initialized**: callbacks used to run while holding `_initialization_lock`, so a nested `_lazy_call` deadlocked. Callbacks now run outside the lock: a fast path runs them immediately when CUDA is initialized, and otherwise the lock is held only for the queue-or-run decision, with the callback invoked after release if initialization won the race.
2. **Queued callback during initialization**: `_lazy_init` drains `_queued_calls` while holding the lock and with `_initialized` still `False`, so a queued callback that re-enters `_lazy_call` deadlocked on its own thread's lock. `_lazy_call` now mirrors `_lazy_init`'s reentrancy guard and runs the callback immediately when `_tls.is_initializing` is set; `torch._C._cuda_init()` has already completed at that point, so this is safe.

Regression tests `test_lazy_call_reentrant_set_rng_state_does_not_deadlock` and `test_lazy_call_reentrant_queued_does_not_deadlock` run each scenario in a subprocess with a generous timeout. Both fail with a deadlock timeout before the fix and pass after (verified on a ROCm gfx90a host).

`torch/mtia/__init__.py` and `torch/xpu/__init__.py` have the same callback-under-lock pattern and would need the same treatment in a follow-up.

*Parts of this PR (the queued-path fix, second regression test, and this description) were drafted with the assistance of Claude Code and reviewed by a human.*

Pull Request resolved: pytorch#182948
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/inductor-rocm Trigger "inductor" config CI on ROCm ciflow/inductor-rocm-mi200 Trigger "inductor" config CI on ROCm MI200 ciflow/inductor-rocm-mi300 Trigger "inductor" config CI on ROCm MI300/MI325 ciflow/inductor-rocm-mi350 Trigger "inductor" config CI on ROCm MI350 ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/rocm-navi31 Trigger "default" config CI on ROCm Navi31 ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end Merged open source release notes: cuda release notes category release notes: rocm mandatorylabel 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.

6 participants