Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (8): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/206673
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ⏳ No Failures, 1 PendingAs of commit 7d3da87 with merge base 1d6250b ( 🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
4e84545 to
5b00759
Compare
|
@claude where is automatic github actions review of this PR? |
|
Claude finished @ngimel's task in 29s —— View job The automated review didn't run because this PR doesn't have the DetailsThe automated review is the Hardened PR Review workflow (
Right now this PR has only What did run is Auto PR Triage ( To get the automated review: a maintainer adds the |
|
@claude I just added in progress label -- would it trigger automated review now? |
|
Claude finished @kapilsh's task in 21s —— View job Yes, it worked: adding Details
|
There was a problem hiding this comment.
Automated review of 5b00759: nothing blocking; ready for human review.
The PR adds torch.cuda.HostMemPool.from_py_allocator(alloc_fn, free_fn) so a pinned host memory pool can get blocks from Python callbacks, moving pool-allocator frees out of the retry wait and releasing an erased pool's allocator after the allocator locks are dropped. Recommendation: Approve; every point raised is non-blocking.
⚪ 8 non-blocking findings are attached to the code below, collapsed.
This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review
| void* ptr = nullptr; | ||
| auto allocate_memory = [&] { | ||
| if (host_mem_pool) { | ||
| if (pool.allocator_) { |
There was a problem hiding this comment.
⚪ Non-blocking: the retry (lines 598-615) also runs for pools that have their own allocator, so alloc_fn can be called twice.
It catches every c10::Error from allocate_memory(), including the pool.allocator_ path: alloc_fn returning None/0 (CachingHostAllocator.cpp:99-103) and the "not pinned" rejection (:106-117). If any default-pool frees are in flight, the allocating thread (usually holding the GIL) waits for those unrelated cudaFreeHost calls, then calls the Python alloc_fn again, and on the rejection path free_fn again too. For the not-pinned case the retry can never help and only doubles the callback work. Fix: skip the retry when pool.allocator_ is set, or at least on the not-pinned error. Otherwise, document that the callback may run twice for one failed allocation.
| " bytes"); | ||
| // A device allocator, or one that does not pin, would hand out memory | ||
| // that pinned tensors cannot use. | ||
| if (!at::detail::getCUDAHooks().isPinnedPtr(*ptr)) { |
There was a problem hiding this comment.
⚪ Non-blocking: the callback's memory leaks if isPinnedPtr throws. CUDAHooks::isPinnedPtr runs AT_CUDA_CHECK on every error except…
Non-blocking: the callback's memory leaks if isPinnedPtr throws. CUDAHooks::isPinnedPtr runs AT_CUDA_CHECK on every error except cudaErrorInvalidValue. If it throws, the pointer raw_alloc just returned never reaches raw_delete, so both the user's memory and the CUDAPluggableAllocator allocation_metadata_ entry leak, and the retry can then allocate a second buffer. Fix: guard p so any exception after raw_alloc frees it, or call cudaPointerGetAttributes directly and treat any error as "not pinned" (which also avoids repeating the device guard the caller already set).
| std::unique_lock<std::mutex> g(a.m); | ||
| ASSERT_TRUE(a.cv.wait_for(g, kTimeout, [&] { return a.freeing; })); | ||
| } | ||
| EXPECT_EQ(a.host_frees, 1); |
There was a problem hiding this comment.
⚪ Non-blocking: failed_allocation_does_not_wait_for_pool_allocator_frees does not check the free ordering it claims to check.…
Non-blocking: failed_allocation_does_not_wait_for_pool_allocator_frees does not check the free ordering it claims to check. EXPECT_EQ(a.host_frees, 1) is meant to check the std::partition in PendingHostFrees::free_blocks ("other frees of the same batch run before it"). But reclaim_released_pools builds the batch in the iteration order of graph_pools_freeable_, a ska::flat_hash_map with MempoolIdHash (Fibonacci hash policy), which already places Q{0,2} before P{0,1}. So the test passes with the partition removed. Fix: give the allocator-backed pool the id that iterates first (swap the ids), or build the batch so its order is known.
| def free(ptr, size, device, stream): | ||
| free_calls.append((ptr, size)) | ||
| (err,) = runtime.cudaFreeHost(ptr) | ||
| self.assertEqual(err, runtime.cudaError_t.cudaSuccess) |
There was a problem hiding this comment.
⚪ Non-blocking: the self.assertEqual(err, runtime.cudaError_t.cudaSuccess) inside free cannot fail the test. callPythonDeallocator…
Non-blocking: the self.assertEqual(err, runtime.cudaError_t.cudaSuccess) inside free cannot fail the test. callPythonDeallocator (torch/csrc/cuda/Module.cpp) is noexcept: it catches the exception and only issues TORCH_WARN, so a failed cudaFreeHost goes unnoticed in test_allocator and test_allocator_during_capture. Fix: collect errors in a list and assert it is empty after the free, as the existing MemPool.from_py_allocator tests do with callback_errors.
| } | ||
| // Never allocated from, so releasing the pool erases it at once. | ||
| a.release_pool(P); | ||
| stats.wait(); |
There was a problem hiding this comment.
⚪ Non-blocking: failure paths in the new gtests are fragile.
In pool_allocator_released_without_allocator_lock, if a regression keeps the allocator alive past release_pool, stats is still a default-constructed future, so stats.wait() is undefined (libstdc++ throws future_error). on_destroy later runs from ~PoolMockAllocator against stats/stats_returned, which were already destroyed because they are declared after a. Fix: add ASSERT_TRUE(stats.valid()) before the wait.
| auto emptying = std::async(std::launch::async, [&] { a.empty_cache(); }); | ||
| { | ||
| std::unique_lock<std::mutex> g(a.m); | ||
| ASSERT_TRUE(a.cv.wait_for(g, kTimeout, [&] { return a.freeing; })); |
There was a problem hiding this comment.
⚪ Non-blocking: in failed_allocation_does_not_wait_for_pool_allocator_frees, the ASSERT_TRUE here returns early without setting unblocked.
If the pool-allocator free starts after that 10 s timeout, the destructor of emptying's std::async blocks forever. Fix: set unblocked from a scope guard.
| cuda_allocator != nullptr, | ||
| "The allocator of a CUDA host mem pool must be a CUDAAllocator"); | ||
| // See allocate_host_memory_slowpath. The allocator receives this device. | ||
| at::OptionalDeviceGuard device_guard; |
There was a problem hiding this comment.
⚪ Nit, non-blocking: copied code.
The primary-context OptionalDeviceGuard block (lines 81-87) and the steady_clock + timing_mutex_ stats updates (:89,119-125 and :198,203-209) repeat code from allocate_host_memory_slowpath, free_block_slowpath and get_current_stream. A small helper would keep the paths from drifting apart.
|
|
||
| See :ref:`cuda-host-mem-pool-allocators` for an example. | ||
| """ | ||
| pool = cls.__new__(cls) |
There was a problem hiding this comment.
⚪ Non-blocking: from_py_allocator skips a subclass's __init__.
It builds the object with cls.__new__(cls) and then calls _HostMemPool.__init__(pool, allocator), while MemPool.from_py_allocator returns cls(allocator, ...). Keeping allocator out of the public __init__ is a stated design choice, so this is only about consistency. Consider a private keyword-only argument on __init__ so from_py_allocator can return cls(...).
|
From codex: a small host-specific Python allocator (~30–40 LOC) is strictly cleaner than routing HostMemPool through _cuda_createPythonAllocator / CUDAPluggableAllocator. What dropping CUDAPluggableAllocator eliminates: No GetDevice + getCurrentCUDAStream on every miss (currently forced by CUDAPluggableAllocator::raw_alloc). What to keep: Reuse the same SafePyObject + Py_IsInitialized/Py_IsFinalizing + gil_scoped_acquire + noexcept/TORCH_WARN pattern from callPythonAllocator/callPythonDeallocator in torch/csrc/cuda/Module.cpp (a small shared helper or sibling _host_createPythonAllocator / direct pybind constructor on _HostMemPool). The only trade-off is that HostMemPool.from_py_allocator wouldn't have identical callback arity to MemPool.from_py_allocator (and wouldn't accept a GPU CUDAPluggableAllocator, which wouldn't return pinned host memory anyway and isn't exposed in #206673). For host memory, (size) / (ptr, size) is the more natural API. |
5b00759 to
f29436d
Compare
Added host specific allocator interface |
|
@pytorchbot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
HostMemPool.from_py_allocator(alloc_fn, free_fn) makes a host mem pool that uses Python callbacks to allocate and free the memory of its blocks. alloc_fn(size) returns the address of size bytes, or None on failure. free_fn(ptr, size) frees it. The memory must be pinned host memory. If it is not pinned, the allocator gives it back to free_fn and raises an error. The CUDA notes show one pool for each NUMA node. Each pool gets its memory from a CUDA memory pool of pinned memory on that node, and the example gives every GPU access to that memory. Without access, copies between that memory and a GPU are synchronous. The core host allocator gets at::HostMemPoolAllocator, an interface with allocate(size) and free(ptr, size). HostAllocator::create_pool gets an optional argument of this type. pytorch#200762 added this virtual function, and no release contains it. The other path was to reuse _cuda_createPythonAllocator (CUDAPluggableAllocator), as MemPool.from_py_allocator does. Its callbacks also get a device and a stream, which pinned memory does not have, and it keeps a map from pointer to size, device and stream, which the host block already has. alloc_fn runs in relaxed capture mode while a CUDA graph capture is registered, as cudaHostAlloc does. So does the free_fn call that gives back memory that is not pinned. When free_fn frees a block, it always runs in relaxed capture mode, as cudaFreeHost does. alloc_fn runs with a device that has a primary context as the current device, if one exists, as cudaHostAlloc does. A failed pinned allocation waits for the frees in progress, then tries again. free_fn must get the GIL. If the waiting thread holds the GIL, the two threads wait for each other. Thus the wait does not count frees through a pool allocator. In each batch of frees, the allocator frees the counted blocks first, tells the waiting threads, and then frees the other blocks. An allocation from a pool with its own allocator does not try again: a retry would call alloc_fn a second time, after a wait in which the thread can hold the GIL. A pool holds the only reference to its allocator. When a pool with no blocks is erased, the allocator is destroyed, and releasing the Python callbacks takes the GIL. The erase occurs under the exclusive allocator lock. A thread that holds the GIL and waits for that lock, for example in host_memory_stats(), then causes a deadlock. To prevent this, the erase gives the allocator to PendingHostFrees, which releases it after the locks. The public API is only from_py_allocator. HostMemPool() has no arguments. Test Plan: ``` build/bin/cuda_caching_host_allocator_test cd test && python test_cuda.py -k TestHostMemPool -k TestCachingHostAllocator -k pinned ``` All 25 gtests pass. The new gtest pool_allocator_released_without_allocator_lock fails without the deadlock fix. failed_allocation_does_not_wait_for_pool_allocator_frees fails if PendingHostFrees::free_blocks does not free the counted blocks first. test_cuda.py: 66 tests, 0 failures, 3 skipped. An AI assistant (Claude Code) helped write this change.
|
Successfully rebased |
f29436d to
7d3da87
Compare
|
@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 |
BC-breaking?
No.
Summary (human written only)
Adds
HostMemPool.from_py_allocator(alloc_fn, free_fn), so a pinned host memory pool can get its memory from Python callbacks, for example one pool per NUMA node backed by a CUDA host memory pool. Follow-up to #200762Agent details (if applicable)
Claude Code (an AI assistant) wrote the text below from the code and the test logs.
API
torch.cuda.HostMemPool.from_py_allocator(alloc_fn, free_fn)makes a HostMemPool that uses Python callbacks to allocate and free the memory of its blocks. Enter it withtorch.cuda.use_mem_pool(pool), as other HostMemPools.alloc_fn(size)returns the address ofsizebytes as an integer, orNoneor 0 on failure.free_fn(ptr, size)frees the memory.HostMemPool()does not change. It has no arguments.docs/source/notes/cuda.mdshows one pool for each NUMA node. Each pool gets its memory from a CUDA memory pool of pinned memory on that node (cudaMemLocationTypeHostNuma), and gives every GPU access to that memory withcudaMemPoolSetAccess. The example uses onlycuda.bindings.Rules for the callbacks
alloc_fnmust return pinned host memory: fromcudaHostAlloc, registered withcudaHostRegister, or from a CUDA memory pool on the host. The allocator checks this withcudaPointerGetAttributes. If the memory is not pinned, the allocator gives it back tofree_fnand raises an error.alloc_fnreturnsNoneor 0, the allocation raises an error. A failed allocation throughalloc_fnis not tried again.free_fngets the address and the size thatalloc_fngot, possibly later and on another thread.alloc_fnruns with a device that has a primary context as the current device, if one exists, ascudaHostAllocdoes.alloc_fnruns in relaxed capture mode while a CUDA graph capture is registered with the allocator, ascudaHostAllocdoes. So does thefree_fncall that gives back memory that is not pinned. Whenfree_fnfrees a block, it always runs in relaxed mode, ascudaFreeHostdoes. Thusalloc_fncan run during a global-mode capture.pinned_use_cuda_host_registerdoes not apply to them.free_fneven after the pool object is deleted. A graph that entersuse_mem_pool(pool)during capture keeps the pool untilreset().free_fnbecomes a warning. Once interpreter finalization starts, the callbacks are not called, and memory still in the pool is not freed.Implementation
at::HostMemPoolAllocator(aten/src/ATen/core/CachingHostAllocator.h) is an interface withallocate(size)andfree(ptr, size). It has no backend types.HostBlockPool::allocator_holds the allocator, andcreate_pool(pool_id, allocator)sets it. Each block keeps a copy inHostBlock::allocator_, becausefree_blockruns after the block leaves its pool, and the pool can be erased at that time.CachingHostAllocatorImplgets the private virtualallocate_host_memory_with_allocator. The CUDA backend sets the device and the capture mode, callsallocate, and checks the memory. Itsfree_blockcallsfreewith the block size. Other backends raise "not implemented".PythonHostMemPoolAllocator(torch/csrc/cuda/MemPool.cpp) holds the callbacks inc10::SafePyObjects and calls them with the GIL, ascallPythonAllocatorandcallPythonDeallocatorintorch/csrc/cuda/Module.cppdo. The private constructor_HostMemPool(alloc_fn, free_fn)makes it.Deadlock fixes: the GIL and the allocator locks
free_fnmust get the GIL, and releasing the callbacks also gets the GIL. Two places must not do this while a thread that holds the GIL waits for them.The retry wait. In #200762, a failed pinned allocation waits for the frees in progress, then tries again.
free_fnmust get the GIL. If the waiting thread holds the GIL, the two threads wait for each other.Now the wait does not count frees through a pool allocator. One batch of frees can contain blocks of more than one pool (
reclaim_released_pools). ThusPendingHostFrees::free_blocksfrees the counted blocks first, tells the waiting threads, and then frees the blocks of pool allocators. An allocation from a pool with its own allocator does not try again: a retry would callalloc_fna second time, after a wait in which the thread can hold the GIL.The release of the allocator. A pool holds the only reference to its allocator. When a pool with no blocks is erased (for example, a pool that never allocated), the allocator is destroyed under the exclusive
instance_mutex_. A thread that holds the GIL and waits for that mutex, for example intorch.cuda.host_memory_stats(), then deadlocks with it. Now the erase gives the allocator toPendingHostFrees, which releases it after the locks. A stress test creates and deletes unused pools while another thread reads the stats. Without this fix, it deadlocked during a 60 s run. With the fix, it ran for 60 s and did not stop.Why a pool allocator
On a GB200 host (driver 580.126.20),
cudaHostAllocbelow 2 MiB takes pages from pinned chunks that the driver already has. The thread that made a chunk sets its NUMA node. Thus "bind the thread, then enter the pool" from #200762 does not set the node of small buffers. A pool allocator that gets its memory from a CUDA memory pool on the node sets the node of all sizes.Alternatives
from_py_allocatorcould usetorch._C._cuda_createPythonAllocator(CUDAPluggableAllocator), asMemPool.from_py_allocatordoes. Its callbacks also get a device and a stream, which pinned memory does not have, and it keeps a map from pointer to size, device and stream, which the host block already has.Tests
HostMemPoolTest.pool_allocator: the blocks of the pool come from its allocator and go back to it. Other blocks do not.HostMemPoolTest.failed_allocation_does_not_wait_for_pool_allocator_frees: a free through a pool allocator stops. A failed allocation on another thread must not wait for it, and the other frees of the same batch must occur first. The test fails ifPendingHostFrees::free_blocksdoes not free the counted blocks first.HostMemPoolTest.pool_allocator_released_without_allocator_lock: the destructor of the allocator of an erased pool reads the stats on another thread. This must not wait for an allocator lock. The test fails without the fix.TestHostMemPool:test_allocator,test_allocator_during_capture,test_allocator_must_return_pinned_memory(cpu and cuda memory),test_allocator_failure.All 25 gtests pass. test_cuda.py: 66 tests, 0 failures, 3 skipped. Host: GB200 (2 GPUs, 2 NUMA nodes), CUDA 13.
Other checks:
non_blocking=Truecopies between the example's memory and each GPU, in both directions, took 0.7 to 1.2 ms and returned before the copy completed. WithoutcudaMemPoolSetAccess, the same copies were synchronous and took 17 to 34 ms.