Skip to content

[CachingHostAllocator] Add python allocator API for HostMempool - #206673

Closed
kapilsh wants to merge 1 commit into
pytorch:mainfrom
kapilsh:kapilsh/host-caching-alloc/host-mem-pool-allocator
Closed

kapilsh wants to merge 1 commit into
pytorch:mainfrom
kapilsh:kapilsh/host-caching-alloc/host-mem-pool-allocator

Conversation

@kapilsh

@kapilsh kapilsh commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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 #200762

Agent 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 with torch.cuda.use_mem_pool(pool), as other HostMemPools.

  • alloc_fn(size) returns the address of size bytes as an integer, or None or 0 on failure. free_fn(ptr, size) frees the memory.
  • HostMemPool() does not change. It has no arguments.
  • docs/source/notes/cuda.md shows 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 with cudaMemPoolSetAccess. The example uses only cuda.bindings.

Rules for the callbacks

  • alloc_fn must return pinned host memory: from cudaHostAlloc, registered with cudaHostRegister, or from a CUDA memory pool on the host. The allocator checks this with cudaPointerGetAttributes. If the memory is not pinned, the allocator gives it back to free_fn and raises an error.
  • If alloc_fn returns None or 0, the allocation raises an error. A failed allocation through alloc_fn is not tried again.
  • free_fn gets the address and the size that alloc_fn got, possibly later and on another thread.
  • alloc_fn runs with a device that has a primary context as the current device, if one exists, as cudaHostAlloc does.
  • alloc_fn runs in relaxed capture mode while a CUDA graph capture is registered with the allocator, 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 mode, as cudaFreeHost does. Thus alloc_fn can run during a global-mode capture.
  • The blocks of the pool never come from the pinned reserve segment. pinned_use_cuda_host_register does not apply to them.
  • A block goes back to free_fn even after the pool object is deleted. A graph that enters use_mem_pool(pool) during capture keeps the pool until reset().
  • An exception in free_fn becomes 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 with allocate(size) and free(ptr, size). It has no backend types.
  • HostBlockPool::allocator_ holds the allocator, and create_pool(pool_id, allocator) sets it. Each block keeps a copy in HostBlock::allocator_, because free_block runs after the block leaves its pool, and the pool can be erased at that time.
  • CachingHostAllocatorImpl gets the private virtual allocate_host_memory_with_allocator. The CUDA backend sets the device and the capture mode, calls allocate, and checks the memory. Its free_block calls free with the block size. Other backends raise "not implemented".
  • PythonHostMemPoolAllocator (torch/csrc/cuda/MemPool.cpp) holds the callbacks in c10::SafePyObjects and calls them with the GIL, as callPythonAllocator and callPythonDeallocator in torch/csrc/cuda/Module.cpp do. The private constructor _HostMemPool(alloc_fn, free_fn) makes it.

Deadlock fixes: the GIL and the allocator locks

free_fn must 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_fn must 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). Thus PendingHostFrees::free_blocks frees 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 call alloc_fn a 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 in torch.cuda.host_memory_stats(), then deadlocks with it. Now the erase gives the allocator to PendingHostFrees, 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), cudaHostAlloc below 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_allocator could use torch._C._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.

Tests

  • gtest HostMemPoolTest.pool_allocator: the blocks of the pool come from its allocator and go back to it. Other blocks do not.
  • gtest 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 if PendingHostFrees::free_blocks does not free the counted blocks first.
  • gtest 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.
build/bin/cuda_caching_host_allocator_test
cd test && python test_cuda.py -k TestHostMemPool -k TestCachingHostAllocator -k pinned

All 25 gtests pass. test_cuda.py: 66 tests, 0 failures, 3 skipped. Host: GB200 (2 GPUs, 2 NUMA nodes), CUDA 13.

Other checks:

  • The docs example ran unchanged. Threads bound to one node allocated from the pool of the other node. At 4 KiB, 1 MiB and 4 MiB, the pages were on the node of the pool, and the H2D copies were correct. An allocation and a free through the pool during a global-mode capture did not break the capture, and the replay was correct.
  • 256 MiB non_blocking=True copies between the example's memory and each GPU, in both directions, took 0.7 to 1.2 ms and returned before the copy completed. Without cudaMemPoolSetAccess, the same copies were synchronous and took 17 to 34 ms.
  • Not tested: ROCm, XPU, the Sphinx docs build.

@pytorch-bot

pytorch-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - 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.

Findings (8):

[minor] aten/src/ATen/core/CachingHostAllocator.h:590
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.

[minor] aten/src/ATen/cuda/CachingHostAllocator.cpp:106
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).

[minor] aten/src/ATen/test/cuda_caching_host_allocator_test.cpp:957
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 `P​endingHostFrees::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.

[minor] test/test_cuda.py:11327
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`.

[minor] aten/src/ATen/test/cuda_caching_host_allocator_test.cpp:905
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.

(3 more not shown, see the review run)

Reviewed commit: 5b00759 (NOT the current head 7d3da87)

Review run

🐛 Report a bad review

🔗 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 SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

⏳ No Failures, 1 Pending

As of commit 7d3da87 with merge base 1d6250b (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • User-facing surface
    • HostAllocator::create_pool in aten/src/ATen/core/CachingHostAllocator.h is a TORCH_API virtual whose exported signature gains a HostMemPoolAllocator parameter
    • Adds public torch.cuda.HostMemPool.from_py_allocator and new at::HostMemPoolAllocator interface, plus HostMemPool(allocator) ctor in aten/src/ATen/cuda/MemPool.h
  • Triviality
    • A new feature with GIL and allocator-lock ordering changes fits no trivial change class
    • P​endingHostFrees::free_blocks now partitions frees and frees_started_ skips pool-allocator blocks, changing the retry-wait protocol
  • Callers
    • The only in-tree create_pool overrides are CachingHostAllocatorInterface and CachingHostAllocatorImpl, both updated in the diff

reason: needs_socialization
Reviewed commit: f29436d (NOT the current head 7d3da87)

Inference job

🐛 Report a wrong verdict

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

@kapilsh kapilsh added the release notes: cuda release notes category label Nov 26, 2026
@kapilsh kapilsh changed the title [CachingHostAllocator] Add HostMemPool.from_py_allocator [CachingHostAllocator] Add python allocator API for HostMempool Nov 26, 2026
@kapilsh
kapilsh force-pushed the kapilsh/host-caching-alloc/host-mem-pool-allocator branch 3 times, most recently from 4e84545 to 5b00759 Compare November 30, 2026 12:04
@kapilsh
kapilsh marked this pull request as ready for review November 30, 2026 16:18
@kapilsh
kapilsh requested a review from ngimel November 30, 2026 16:18
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 30, 2026
@ngimel

ngimel commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

@claude where is automatic github actions review of this PR?

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 29s —— View job


The automated review didn't run because this PR doesn't have the in progress label, and that label is what starts it.

Details

The automated review is the Hardened PR Review workflow (.github/workflows/hardened-pr-review.yml, which then runs hardened-pr-review-run.yml). Its capture job only runs if all of these hold:

  • the PR is not a draft
  • the PR has the in progress label: either that label is being added in this event, or it is already on the PR when a synchronize, reopened or ready_for_review event fires
  • the PR does not have ready for review or no automated review

Right now this PR has only release notes: cuda and GL/human, and it is not a draft. The job condition is false on every event, so Stage 1 skips and no review is posted.

What did run is Auto PR Triage (auto-pr-triage.yml). That is the GreenLight verdict in the Dr. CI comment ("PR requires human review", reason not_trivial), and it is why GL/human was added. Triage and review are separate workflows: triage does not review the code.

To get the automated review: a maintainer adds the in progress label. The labeled event starts Stage 1 right away, and Stage 2 posts the review. After that, each push re-runs it while the label stays on. Adding the label by hand works because Stage 2 only checks who triggered the run when the actor is a bot (only pytorch-bot[bot] and meta-codesync[bot] may start it). A human is always allowed.

@kapilsh kapilsh added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 30, 2026
@kapilsh

kapilsh commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

@claude I just added in progress label -- would it trigger automated review now?

@claude

claude Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Claude finished @kapilsh's task in 21s —— View job


Yes, it worked: adding in progress started the automated review. Stage 1 (Hardened PR Review, run 46484820194) ran at 18:29 UTC and succeeded, where the earlier runs on this PR were skipped.

Details
  • Stage 1's capture job runs when the event is labeled with label.name == 'in progress', the PR is not a draft, and the PR doesn't have no automated review (.github/workflows/hardened-pr-review.yml:147-158). This PR meets all three.
  • Stage 2 (hardened-pr-review-run.yml) starts on workflow_run: completed of "Hardened PR Review" when that run succeeded. It runs against the base repo, so it doesn't show in this PR's checks list. It should post the review on this PR when it finishes.
  • From now on, every push re-runs the review while in progress stays on. Adding ready for review stops it on pushes, and adding no automated review turns it off completely.
  • If no review shows up after a while, look at the Actions tab for a "Hardened PR Review Run" started from run 46484820194.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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.

Report this finding

" 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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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).

Report this finding

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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.

Report this finding

Comment thread test/test_cuda.py Outdated
def free(ptr, size, device, stream):
free_calls.append((ptr, size))
(err,) = runtime.cudaFreeHost(ptr)
self.assertEqual(err, runtime.cudaError_t.cudaSuccess)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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.

Report this finding

}
// Never allocated from, so releasing the pool erases it at once.
a.release_pool(P);
stats.wait();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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.

Report this finding

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; }));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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.

Report this finding

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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.

Report this finding

Comment thread torch/cuda/memory.py

See :ref:`cuda-host-mem-pool-allocators` for an example.
"""
pool = cls.__new__(cls)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ 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(...).

Report this finding

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Nov 30, 2026
@ngimel

ngimel commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

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).
No allocation_metadata_ hash map + mutex (CUDAPluggableAllocator tracks {ptr -> (size, device, stream)} under a lock just to pass them back to free_fn, even though HostBlock already has block->size_).
Clean public signature: alloc_fn(size) -> int | None and free_fn(ptr, size) -> None — no unused (device, stream) footgun and no "ignore stream" caveat in docs.
No CUDAAllocator coupling / dynamic_cast: CachingHostAllocator.h can take a tiny 2-method backend-agnostic interface (e.g. allocate(size_t) -> void* / free(void*, size_t)) instead of std::shared_ptrc10::Allocator + dynamic_cast<CUDAAllocator*> in CachingHostAllocator.cpp and CUDAAllocator in ATen/cuda/MemPool.h. That also makes XPU/other backends straightforward later.

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).
Keep the primary-context OptionalDeviceGuard, CUDAStreamCaptureModeGuard(Relaxed), and cudaPointerGetAttributes pinned check in CUDACachingHostAllocatorImpl so Python callbacks calling CUDA runtime APIs don't lazily create a context on device 0 or break capture.

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.

@kapilsh
kapilsh force-pushed the kapilsh/host-caching-alloc/host-mem-pool-allocator branch from 5b00759 to f29436d Compare November 30, 2026 21:41
@kapilsh

kapilsh commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

a small host-specific Python allocator (~30–40 LOC) is strictly cleaner than routing HostMemPool through _cuda_createPythonAllocator / CUDAPluggableAllocator.

Added host specific allocator interface

@kapilsh

kapilsh commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@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.
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased kapilsh/host-caching-alloc/host-mem-pool-allocator onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout kapilsh/host-caching-alloc/host-mem-pool-allocator && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the kapilsh/host-caching-alloc/host-mem-pool-allocator branch from f29436d to 7d3da87 Compare December 1, 2026 01:22
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Dec 1, 2026
@kapilsh

kapilsh commented Dec 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 Dec 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

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 GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: cuda release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants