Skip to content

[CachingHostAllocator] Fix empty_cache locking for released private pools - #199145

Closed
sujuyu wants to merge 1 commit into
pytorch:mainfrom
sujuyu:host-alloc/empty-cache-deadlock
Closed

sujuyu wants to merge 1 commit into
pytorch:mainfrom
sujuyu:host-alloc/empty-cache-deadlock

Conversation

@sujuyu

@sujuyu sujuyu commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

I also found this while prototyping the host mempool: when a private pool is used outside graph capture, empty_cache() takes the same lock twice on one thread and fails with "Resource deadlock avoided". The host mempool needs to use private pools outside capture, so it would run into this. The new test reproduces the failure on main and passes with the fix.

process_events() already knows which pool it is processing, so it can use that pool directly instead of looking it up by id; that lookup is what took the lock a second time. The same loop had another problem: it checked whether a pool was empty without holding blocks_mutex_. With pinned_max_cached_size_mb set, empty_cache() could delete a pool that another thread was still using, so the check now holds that lock as well. The second problem has no dedicated test, because it needs pinned_max_cached_size_mb to be set and another thread to free the pool's last block within a very narrow window, which is hard to reproduce reliably in a test.

The technical summary below was drafted with Claude, and I checked it against the code.

Technical details and test plan (drafted with Claude)

empty_cache() holds instance_mutex_ exclusively while it runs
process_events() on each released private pool. When a block's last event
has completed, process_events() finds the block's pool with
pool_from_block(), which locks instance_mutex_ shared on the same thread.
That is undefined behaviour. With libstdc++ on glibc it throws "Resource
deadlock avoided", and other implementations may hang. The block is already
off the event queue, so it leaks along with its pool. Graph capture does not
hit this, because blocks allocated during capture never queue events. It
needs a private pool used outside capture through begin_allocate_to_pool().

process_events() already has the pool, and pool.events_ only holds that
pool's blocks, since free() queues events on the block's own pool and
process_events() requeues them there. So use it and drop the lookup. Storing
a pool pointer in every block would also avoid the lock, and would take
instance_mutex_ off free() for private-pool blocks, but nothing needs that
yet.

The same loop read blocks_.empty() without blocks_mutex_. When
pinned_max_cached_size_mb is set, free() destroys a block larger than it
instead of caching it. The default is unlimited. That free() removes the
block from blocks_ and keeps using the pool until it releases blocks_mutex_,
so empty_cache() could erase the pool in between. The check now takes
blocks_mutex_. maybe_cache_block() now releases blocks_mutex_ after the
free-list mutex by construction, since std::scoped_lock does not guarantee
an unlock order.

Test Plan:

python -m pip install -e . -v --no-build-isolation
build/bin/cuda_caching_host_allocator_test --gtest_filter='CachingHostAllocatorTest.*'
python -m pytest test/test_cuda.py \
  -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"

All 8 gtests pass, and the pytest set gives 41 passed and 3 skipped, all
disabled upstream. With the header reverted to 2a20f3e, the
new empty_cache_released_pool_with_completed_event test fails:

Expected: allocator->empty_cache() doesn't throw an exception.
  Actual: it throws std::system_error with description "Resource deadlock avoided".

No test here covers the blocks_mutex_ change, because it needs a concurrent
free() in a narrow window. In a TSAN build of a mock-backend harness, which
is not part of this PR, the race showed up before the change and not after.
CI does not run cuda_caching_host_allocator_test, so the gtests were run
locally.

#199144 also changes the empty_cache() loop, so whichever of the two lands second
needs a small rebase.

This change was prepared with assistance from Claude, an AI assistant.

🤖 Generated with Claude Code

…ools

empty_cache() holds instance_mutex_ exclusively while it runs
process_events() on each released private pool. When a block's last event
has completed, process_events() finds the block's pool with
pool_from_block(), which locks instance_mutex_ shared on the same thread.
That is undefined behaviour. With libstdc++ on glibc it throws "Resource
deadlock avoided", and other implementations may hang. The block is already
off the event queue, so it leaks along with its pool. Graph capture does not
hit this, because blocks allocated during capture never queue events. It
needs a private pool used outside capture through begin_allocate_to_pool().

process_events() already has the pool, and pool.events_ only holds that
pool's blocks, since free() queues events on the block's own pool and
process_events() requeues them there. So use it and drop the lookup. Storing
a pool pointer in every block would also avoid the lock, and would take
instance_mutex_ off free() for private-pool blocks, but nothing needs that
yet.

The same loop read blocks_.empty() without blocks_mutex_. When
pinned_max_cached_size_mb is set, free() destroys a block larger than it
instead of caching it. The default is unlimited. That free() removes the
block from blocks_ and keeps using the pool until it releases blocks_mutex_,
so empty_cache() could erase the pool in between. The check now takes
blocks_mutex_. maybe_cache_block() now releases blocks_mutex_ after the
free-list mutex by construction, since std::scoped_lock does not guarantee
an unlock order.

Test Plan:

```bash
python -m pip install -e . -v --no-build-isolation
build/bin/cuda_caching_host_allocator_test --gtest_filter='CachingHostAllocatorTest.*'
python -m pytest test/test_cuda.py \
  -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
```

All 8 gtests pass, and the pytest set gives 41 passed and 3 skipped, all
disabled upstream. With the header reverted to 2a20f3e, the
new empty_cache_released_pool_with_completed_event test fails:

```
Expected: allocator->empty_cache() doesn't throw an exception.
  Actual: it throws std::system_error with description "Resource deadlock avoided".
```

No test here covers the blocks_mutex_ change, because it needs a concurrent
free() in a narrow window. In a TSAN build of a mock-backend harness, which
is not part of this PR, the race showed up before the change and not after.
CI does not run cuda_caching_host_allocator_test, so the gtests were run
locally.

This change was prepared with assistance from Claude, an AI assistant.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 83a0a03 with merge base 2a20f3e (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@sujuyu

sujuyu commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

cc @galv @joshuuuasu @ngimel

@sujuyu

sujuyu commented Sep 30, 2026

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 Sep 30, 2026
@albanD
albanD requested review from albanD and ngimel September 30, 2026 14:35
@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 30, 2026
@ngimel

ngimel commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator

@claude review this PR, pay attention to correctness under multithreading scenarios, and no additional locks on fast path

@claude

claude Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 2m 45s —— View job


The fix looks correct under concurrency and adds no locks on the allocate()/free() fast path. The only thing I'd raise is a pre-existing pool-lifetime gap that the planned host mempool could make easier to hit.

PR Review: #199145

Summary

The PR does two things. It stops process_events() from re-taking instance_mutex_ through pool_from_block(), which empty_cache() already holds exclusively on the same thread. It also makes empty_cache() check blocks_.empty() under blocks_mutex_, and has the destroy branch of maybe_cache_block() release blocks_mutex_ last.

I checked these multithreading points and found no new problems:

  • pool.events_ only holds that pool's blocks. free() queues events on pool_from_block(block) (CachingHostAllocator.h:510-514), and process_events_for_specific_size only requeues onto the same pool. So using pool directly is equivalent to the old lookup.
  • Fast path.
    • allocate() and get_free_block() are unchanged.
    • The cached branch of maybe_cache_block() (size <= pinned_max_cached_size, the default) still takes only the free-list mutex.
    • process_events() on a private pool now takes one fewer shared lock on instance_mutex_.
    • The only lock added is the blocks_mutex_ check in empty_cache(), which is the slow path.
  • Lock order.
    • gb(blocks_mutex_) then gf(free_list_[i].mutex_) matches the documented order blocks_mutex_ > free_list_[i].mutex_ (:180) and add_allocated_block() (:697-709).
    • The other sites that take both mutexes use std::scoped_lock, whose std::lock back-off algorithm can't deadlock against a fixed-order acquirer.
    • empty_cache() taking blocks_mutex_ while holding instance_mutex_ follows instance_mutex_ > blocks_mutex_, the same as get_block_from_ptr() and block_exists().
  • Pool erase vs. a concurrent free().
    • In the cached branch and the event branch of free(), the block stays in blocks_, so empty_cache() can't erase the pool.
    • Only the destroy branch removes the block from blocks_. It now releases blocks_mutex_ after the free-list mutex, so an empty blocks_ observed under blocks_mutex_ means that thread no longer touches the pool.
    • If a free() lands between free_from_pool() and the empty check, the pool is kept until a later empty_cache(). That's benign.
  • Destroying the last block inside empty_cache()'s own process_events(). The next loop iteration re-locks pool.events_mutex_, which is safe because the pool can't be erased before the loop body finishes, under the exclusive instance_mutex_.

Thread Safety

  • Pre-existing, not introduced here, and relevant to the host mempool follow-up (lower confidence).
    • Where: allocate() gets BlockPool& from get_allocation_pool_for_current_stream() (:966-989), which releases instance_mutex_ before returning. allocate() then uses the pool without that lock through process_events(), get_free_block() and add_allocated_block().
    • How it breaks: If a pool is released (use_count == 0, so it is in graph_pools_freeable_) while it is still listed in captures_underway_, a concurrent empty_cache() can erase it between those steps. The same applies inside allocate()'s own process_events(): once the destroy branch removes the pool's last block, empty_cache() can erase the pool while the loop goes on to lock pool.events_mutex_.
    • Why it matters now: The comment at :559-563 ("seeing blocks_ empty means it is done with the pool") is only true for free(). CUDA graphs always call end_allocate_to_pool before release_pool, so today's graph callers don't hit this.
    • Suggestion: The host mempool is meant to use private pools outside capture, so that design should either enforce end_allocate_to_pool before release_pool (e.g. TORCH_CHECK in release_pool that pool_id isn't in captures_underway_) or say in the comment that the invariant relies on it. Fix this →

Testing

  • empty_cache_released_pool_with_completed_event never calls end_allocate_to_pool if at::empty throws between begin_allocate_to_pool and end_allocate_to_pool. The pool then stays in captures_underway_ with an always-true filter on the process-wide allocator, which would send every later pinned allocation in this binary into that pool. An RAII guard or c10::scope_exit-style cleanup would keep one failure from spreading to later tests.

Recommendation

Approve

The deadlock fix and the blocks_mutex_ fix are both correct and add no fast-path locking. The allocate-side lifetime note is pre-existing and can be handled when the host mempool lands.

@sujuyu

sujuyu commented Oct 1, 2026

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

@sujuyu
sujuyu deleted the host-alloc/empty-cache-deadlock branch October 2, 2026 14:25
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…ools (pytorch#199145)

I also found this while prototyping the host mempool: when a private pool is used outside graph capture, empty_cache() takes the same lock twice on one thread and fails with "Resource deadlock avoided". The host mempool needs to use private pools outside capture, so it would run into this. The new test reproduces the failure on main and passes with the fix.

process_events() already knows which pool it is processing, so it can use that pool directly instead of looking it up by id; that lookup is what took the lock a second time. The same loop had another problem: it checked whether a pool was empty without holding blocks_mutex_. With pinned_max_cached_size_mb set, empty_cache() could delete a pool that another thread was still using, so the check now holds that lock as well. The second problem has no dedicated test, because it needs pinned_max_cached_size_mb to be set and another thread to free the pool's last block within a very narrow window, which is hard to reproduce reliably in a test.

The technical summary below was drafted with Claude, and I checked it against the code.

<details>
<summary>Technical details and test plan (drafted with Claude)</summary>

> empty_cache() holds instance_mutex_ exclusively while it runs
> process_events() on each released private pool. When a block's last event
> has completed, process_events() finds the block's pool with
> pool_from_block(), which locks instance_mutex_ shared on the same thread.
> That is undefined behaviour. With libstdc++ on glibc it throws "Resource
> deadlock avoided", and other implementations may hang. The block is already
> off the event queue, so it leaks along with its pool. Graph capture does not
> hit this, because blocks allocated during capture never queue events. It
> needs a private pool used outside capture through begin_allocate_to_pool().
>
> process_events() already has the pool, and pool.events_ only holds that
> pool's blocks, since free() queues events on the block's own pool and
> process_events() requeues them there. So use it and drop the lookup. Storing
> a pool pointer in every block would also avoid the lock, and would take
> instance_mutex_ off free() for private-pool blocks, but nothing needs that
> yet.
>
> The same loop read blocks_.empty() without blocks_mutex_. When
> pinned_max_cached_size_mb is set, free() destroys a block larger than it
> instead of caching it. The default is unlimited. That free() removes the
> block from blocks_ and keeps using the pool until it releases blocks_mutex_,
> so empty_cache() could erase the pool in between. The check now takes
> blocks_mutex_. maybe_cache_block() now releases blocks_mutex_ after the
> free-list mutex by construction, since std::scoped_lock does not guarantee
> an unlock order.
>
> Test Plan:
>
> ```bash
> python -m pip install -e . -v --no-build-isolation
> build/bin/cuda_caching_host_allocator_test --gtest_filter='CachingHostAllocatorTest.*'
> python -m pytest test/test_cuda.py \
>   -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
> ```
>
> All 8 gtests pass, and the pytest set gives 41 passed and 3 skipped, all
> disabled upstream. With the header reverted to 2a20f3e, the
> new empty_cache_released_pool_with_completed_event test fails:
>
> ```
> Expected: allocator->empty_cache() doesn't throw an exception.
>   Actual: it throws std::system_error with description "Resource deadlock avoided".
> ```
>
> No test here covers the blocks_mutex_ change, because it needs a concurrent
> free() in a narrow window. In a TSAN build of a mock-backend harness, which
> is not part of this PR, the race showed up before the change and not after.
> CI does not run cuda_caching_host_allocator_test, so the gtests were run
> locally.
>
> pytorch#199144 also changes the empty_cache() loop, so whichever of the two lands second
> needs a small rebase.
>
> This change was prepared with assistance from Claude, an AI assistant.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: pytorch#199145
Approved by: https://github.com/ngimel

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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 topic: not user facing topic 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.

5 participants