Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/199144
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit ca4ec9c with merge base 2438180 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@pytorchbot label "release notes: cuda" |
|
@claude review this PR, pay attention to not adding overhead on the hot path |
|
Claude finished @ngimel's task in 2m 23s —— View job I found no new overhead on the cached allocate/free hot path; the only extra cost is one uncontended mutex on the block create/destroy slow path. PR Review: #199144SummaryThe PR moves per-bucket host stats from the global Hot-path analysis (the focus requested):
The findings below are optional or low severity. Performance
Testing
RecommendationApprove (from a hot-path/perf standpoint). The cached allocate/free fast paths are unchanged in lock count and memory traffic. The only added cost is one uncontended mutex on the block create/destroy slow path, and the per-pool |
…ools (#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. > > #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: #199145 Approved by: https://github.com/ngimel Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Since pytorch#167507 added host private pools, the default pool and a private pool update the same HostStatsStaged counters. Each pool guards them with its own mutexes, the bucket stats with free_list_[i].mutex_ and allocations and allocated_bytes with blocks_mutex_, so updates from two pools race. For example, pinned allocations into a graph's private pool during capture can race with a DataLoader pin_memory thread and lose updates. In debug builds, free() can then fail the current >= 0 assert in Stat::decrease. Move the bucket stats into HostBlockPool, next to the free-list mutexes that already guard them, and give allocations and allocated_bytes their own mutex. Those two only change when a block is created or destroyed, so the cached allocate and free paths take no new lock. getStats() and the reset functions now walk every pool. When empty_cache() erases a private pool, it adds that pool's bucket stats to default_pool_'s, so the totals don't drop. A single stats mutex would also fix the race, but it would add a global lock to every cached allocate and free. Atomic counters would keep every pool writing the same cache lines. getStats() already estimates the total peak by summing per-bucket peaks. It now also sums per-pool peaks, and an erased pool's peaks stay counted until reset_peak_host_memory_stats(). So with private pools in use, the reported active_requests and active_bytes peaks can be higher than before, and can grow with each erased pool. allocations and allocated_bytes stay exact. Test Plan: ```bash python -m pip install -e . -v --no-build-isolation build/bin/cuda_caching_host_allocator_test --gtest_filter='CachingHostAllocatorTest.*' f=0 for i in $(seq 1 20); do build/bin/cuda_caching_host_allocator_test \ --gtest_filter=CachingHostAllocatorTest.stats_concurrent_pools >/dev/null 2>&1 || f=$((f+1)) done echo "failed $f of 20" python -m pytest test/test_cuda.py \ -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache" ``` All 10 gtests pass, and stats_concurrent_pools passes 20 of 20 runs. The pytest set gives 41 passed and 3 skipped, all disabled upstream. With the header reverted to 2a20f3e, stats_concurrent_pools fails 20 of 20 runs with lost counts. It is a stress test, so a run could pass by chance. stats_include_private_pools passes there as well, since it checks the summing across pools and not the race. No test covers the allocations and allocated_bytes half, because the cached path creates at most one block per pool. 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]>
a0ffd20 to
ca4ec9c
Compare
|
Rebased onto main, which now includes #199145. The empty_cache() loop conflicted; I resolved it by moving the stats fold into the locked emptiness check, with no change in logic. As the Claude review suggested, I also added active_bytes asserts to stats_concurrent_pools. Reran on an A100 and all tests pass. |
|
@pytorchbot merge |
Merge startedYour 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 |
…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]>
…h#199144) While prototyping the generic host mempool that ngimel suggested in pytorch#197868, I found that all pools share one set of stat counters, but each pool updates them under its own locks. In our multi-GPU inference setup the pools are split by NUMA node, and several threads use different pools at the same time, so these counters can lose updates and also become a point of contention between threads. This fix can be merged independently of the interface design that is still open in pytorch#197868. I have reviewed the change, and the tests have been run on an A100. The change gives each pool its own per-bucket stats, guarded by the free-list locks it already takes. The global allocations and allocated_bytes counters get a separate lock that is only taken when a block is created or destroyed, so the allocate and free paths that hit the cache need no extra locking. getStats() adds up the stats of all pools. When private pools are in use, the active peaks, which were already an estimate, can be higher than before; allocations and allocated_bytes stay exact. 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> > Since pytorch#167507 added host private pools, the default pool and a private pool > update the same HostStatsStaged counters. Each pool guards them with its own > mutexes, the bucket stats with free_list_[i].mutex_ and allocations and > allocated_bytes with blocks_mutex_, so updates from two pools race. For > example, pinned allocations into a graph's private pool during capture can > race with a DataLoader pin_memory thread and lose updates. In debug builds, > free() can then fail the current >= 0 assert in Stat::decrease. > > Move the bucket stats into HostBlockPool, next to the free-list mutexes that > already guard them, and give allocations and allocated_bytes their own > mutex. Those two only change when a block is created or destroyed, so the > cached allocate and free paths take no new lock. getStats() and the reset > functions now walk every pool. When empty_cache() erases a private pool, it > adds that pool's bucket stats to default_pool_'s, so the totals don't drop. > > A single stats mutex would also fix the race, but it would add a global lock > to every cached allocate and free. Atomic counters would keep every pool > writing the same cache lines. > > getStats() already estimates the total peak by summing per-bucket peaks. It > now also sums per-pool peaks, and an erased pool's peaks stay counted until > reset_peak_host_memory_stats(). So with private pools in use, the reported > active_requests and active_bytes peaks can be higher than before, and can > grow with each erased pool. allocations and allocated_bytes stay exact. > > Test Plan: > > ```bash > python -m pip install -e . -v --no-build-isolation > build/bin/cuda_caching_host_allocator_test --gtest_filter='CachingHostAllocatorTest.*' > f=0 > for i in $(seq 1 20); do > build/bin/cuda_caching_host_allocator_test \ > --gtest_filter=CachingHostAllocatorTest.stats_concurrent_pools >/dev/null 2>&1 || f=$((f+1)) > done > echo "failed $f of 20" > python -m pytest test/test_cuda.py \ > -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache" > ``` > > All 10 gtests pass, and stats_concurrent_pools passes 20 of 20 runs. The > pytest set gives 41 passed and 3 skipped, all disabled upstream. With the > header reverted to 2a20f3e, stats_concurrent_pools fails 20 of 20 runs > with lost counts. It is a stress test, so a run could pass by chance. > stats_include_private_pools passes there as well, since it checks the > summing across pools and not the race. No test covers the allocations and > allocated_bytes half, because the cached path creates at most one block per > pool. 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. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: pytorch#199144 Approved by: https://github.com/ngimel Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
While prototyping the generic host mempool that ngimel suggested in #197868, I found that all pools share one set of stat counters, but each pool updates them under its own locks. In our multi-GPU inference setup the pools are split by NUMA node, and several threads use different pools at the same time, so these counters can lose updates and also become a point of contention between threads. This fix can be merged independently of the interface design that is still open in #197868. I have reviewed the change, and the tests have been run on an A100.
The change gives each pool its own per-bucket stats, guarded by the free-list locks it already takes. The global allocations and allocated_bytes counters get a separate lock that is only taken when a block is created or destroyed, so the allocate and free paths that hit the cache need no extra locking. getStats() adds up the stats of all pools. When private pools are in use, the active peaks, which were already an estimate, can be higher than before; allocations and allocated_bytes stay exact.
The technical summary below was drafted with Claude, and I checked it against the code.
Technical details and test plan (drafted with Claude)
🤖 Generated with Claude Code