Skip to content

[CachingHostAllocator] Add thread-routed pinned host memory pools - #200762

Closed
sujuyu wants to merge 8 commits into
pytorch:mainfrom
sujuyu:host-alloc/host-mempool
Closed

sujuyu wants to merge 8 commits into
pytorch:mainfrom
sujuyu:host-alloc/host-mempool

Conversation

@sujuyu

@sujuyu sujuyu commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor
  • Passes lint (spin fixlint)
  • Added/updated tests
  • Updated documentation (if applicable)
  • Included benchmark results (for PRs impacting perf)

Linked issue or supporting maintainer

Part of #160420

BC-breaking?

No breaking changes for existing callers. torch.cuda.use_mem_pool has been refactored from a generator function into a class, and also accepts a HostMemPool. See Agent details for the specifics.

Summary (human written only)

In a single-process deployment with multiple GPUs across NUMA nodes, the pinned memory cache reuses blocks by size only, so a thread on node 1 can get a buffer allocated on node 0, and both the H2H copy and the following H2D DMA then cross nodes (#160420). We drive six A100s on two nodes from one process and load models from several threads concurrently; cross-node H2H bandwidth is a third of local (36 vs 116 GiB/s), and loading on node 1 is still 30% slower than on node 0 even with the whole node to itself. Following @ngimel's suggestion in #197868, this PR adds a generic host memory pool instead of making the allocator NUMA-aware: torch.cuda.HostMemPool, entered with torch.cuda.use_mem_pool(host_pool), routes the current thread's pinned allocations to that pool, and cached blocks are reused only within that pool. Users can have the threads on each node use that node's own pool, so blocks are not reused across nodes.

@kapilsh suggested host pools should follow the same capture rules as device MemPools, and proposed merging the API into use_mem_pool. Their commit is included here (sujuyu#1), plus three follow-ups.

Three more commits: per @galv's review, two drop graph(pool=HostMemPool) and use_mem_pool(mp, pinned=True) and relax cudaHostAlloc/cudaHostRegister only during capture; the third frees a released pool's cache even while capturing. Details in Agent details.

#200733 has landed; this is rebased on main.

Agent details (if applicable)

The text below was drafted with Claude Code (an AI assistant) and checked against the code and the test logs.

Commits

#200733 has landed, and this PR is rebased on it (aba7352).

  1. f097629 adds HostMemPool and per-thread routing of pinned allocations.
  2. 7c1a1e2, by @kapilsh (PR #200762 (HostMemPool): aligning host pools with device MemPool under CUDA graphs sujuyu/pytorch#1), makes host pools follow device MemPool's rules under CUDA graph capture and folds use_host_mem_pool into use_mem_pool.
  3. a6e4bd4 follows up on it: the allocator's event queries switch to relaxed capture mode only while a capture is registered with it (switching on every query slowed pinned allocation with concurrent H2D copies by a third, see the benchmark below), CUDAGraph::reset releases the graph's own host pool before the pools it retained, as the device side does, use_mem_pool reads the current device on entry again, Dynamo traces functions decorated with use_mem_pool again, HostMemPool blocks use hipHostMallocNumaUser on ROCm 7.2 and later, a gtest that still expected the removed capture-pool check is rewritten, and comments, docs and type annotations are updated.
  4. 66063bc addresses review: use_mem_pool keeps the device of each open entry, so a context re-entered on another device ends both routes, and a capture into a HostMemPool no longer takes blocks from the pinned reserve segment, like a routed thread.
  5. 3c7d65e fixes an abort: after a graph that used a MemPool as its pool was reset, a capture that entered use_mem_pool on that MemPool took a host reference on the released pool, and resetting that graph aborted the process. retain_pool now skips released pools, as the other paths that take a reference or a route already do.
  6. ca8bb3b addresses @galv's review: it drops torch.cuda.graph(pool=HostMemPool) and use_mem_pool(mp, pinned=True), which gave a device pool and a host pool the same id, and restores the first commit's rejection of a HostMemPool as a graph pool. A graph still keeps a HostMemPool whose context is entered during its capture, and the allocator's retain_pool now takes only host mem pools. use_mem_pool.__enter__ ends the routes it began if retaining the pool fails.
  7. c010f31: cudaHostAlloc/cudaHostRegister run in relaxed capture mode only while a capture is registered with the allocator, like the event query, instead of always.
  8. 29cefaf: a released HostMemPool frees its cache at once even while a capture is underway, since frees run in relaxed capture mode since [CachingHostAllocator] Call free_block outside allocator locks #200733.

API

  • torch.cuda.HostMemPool() is a pool of pinned host memory only.
  • torch.cuda.use_mem_pool(pool, device=None) routes the current thread's allocations: device allocations for a MemPool, as before, and pinned allocations for a HostMemPool, where device=... raises ValueError.
  • A HostMemPool cannot be a graph's pool: torch.cuda.graph(pool=hp) raises TypeError, and CUDAGraph.capture_begin rejects its id. A graph that enters use_mem_pool(hp) during its capture keeps the pool instead (see below).
  • use_mem_pool is now a class (a contextlib.ContextDecorator) instead of a @contextmanager function, so use_mem_pool.__wrapped__ is gone. Its arguments are unchanged, and with device=None the device is still the one current on entry. Contexts of a HostMemPool must be exited in reverse order, on the thread that entered them; otherwise exiting raises and changes nothing.
  • Under torch.compile, only device routing with a MemPool is supported. A function decorated with @torch.cuda.use_mem_pool(pool) still compiles without a graph break: Dynamo cannot trace the class's _recreate_cm, so it rebuilds the context from the decorator's arguments, as for the with form.

CUDA graphs: the same rules as device MemPool

  • The newest scope wins. Each capture and each context that routes pinned memory takes a sequence number when it begins. A pinned allocation on a capturing stream goes to the graph's pool if the capture began inside the thread's innermost context, and to the context's pool if the context was entered during the capture. The thread's allocations on other streams go to its innermost context.
  • A graph keeps a pool until it is reset if the pool's context is entered while the current stream is capturing into the graph (CUDAGraph::retain_pool now also takes a host reference on a HostMemPool, which reset() releases). A capture begun inside a context takes no reference to that context's pool. HostMemPool.use_count() is 1 for the object, plus 1 for each open context on any thread and 1 for each graph that keeps the pool.
  • Pinned blocks allocated during a capture and then used by a stream are kept out of reuse until the last reference to the capture's pool is released, since reusing one while a graph is alive would change what the graph reads on replay. That is the reset of the last graph using the capture's pool. Before, such blocks were never reused or freed. This applies to every graph, with or without these APIs.
  • cudaHostAlloc/cudaHostRegister and the allocator's cudaEventQuery run in relaxed capture mode while a capture is registered with the allocator, and cudaFreeHost/cudaHostUnregister always do ([CachingHostAllocator] Call free_block outside allocator locks #200733). Before, only allocation and registration did, and only while the current stream was capturing. That misses a capturing thread's allocations on its other streams, which go to its HostMemPool and can query a pending event or allocate a new block. CUDAGraph registers its capture before cudaStreamBeginCapture and deregisters it after cudaStreamEndCapture, so a thread can allocate pinned memory and process events while another thread captures in global mode. Captures the allocator does not see, such as one begun outside CUDAGraph or the moment a CUDAGraph capture switches into or out of a conditional node, get unguarded event queries, as before this PR. Switching modes makes two cudaThreadExchangeStreamCaptureMode calls, which serialize threads in the driver (a pair took 275 ns on one thread and 6.6 us per thread with eight threads), which is why event queries outside a capture skip it.
  • Host empty_cache(), which torch.cuda.graph calls on entry, leaves the cache of a live pool alone.
  • A host pool frees its cached blocks at once when its last reference goes, the pool object or the last graph that keeps it, so this can happen in CUDAGraph.reset(). This also holds during a capture on any thread, since the frees run in relaxed capture mode. If the pool's last route ended because its thread exited, a later empty_cache() frees them instead. Blocks still in use, by tensors, pending copies or another graph that shares the capture's pool, wait for a later empty_cache(), as with device MemPool.

NUMA placement

On CUDA, cudaHostAlloc places and pins the pages of a new block on the calling thread's node, or on the node its memory policy names, so a pool needs no NUMA knowledge. On ROCm, hipHostMalloc takes the pages from the node nearest the current GPU unless hipHostMallocNumaUser is set, so a pool's new blocks set that flag on ROCm 7.2 and later. HIP then follows only MPOL_BIND and MPOL_PREFERRED, not CPU affinity alone. Before 7.2, HIP fails the allocation instead of falling back when get_mempolicy is blocked (as under Docker's default seccomp profile), so earlier ROCm keeps the default placement. This was checked against the HIP/CLR sources, not tested on ROCm hardware.

Design, alternatives, and test plan
hpool = torch.cuda.HostMemPool()
with torch.cuda.use_mem_pool(hpool):
    buf = torch.empty(n, pin_memory=True)  # comes from hpool

The motivating use is one pool per NUMA node, entered by the loader threads bound to that node. A pool guarantees cache isolation: a freed block returns to its pool, whichever thread frees it, and is handed out again only to threads routed to that pool. Because placement follows the thread that calls cudaHostAlloc, routing follows the current thread (thread_local), not a stream filter.

Design (aten/src/ATen/core/CachingHostAllocator.h, best reviewed first): a pool that threads can route to is a HostPrivatePool marked is_host_mem_pool. A HostMemPool takes its id from MemPool::graph_pool_handle, so it never collides with another pool by accident. begin/end_allocate_current_thread_to_pool() push and pop a route on the calling thread's route stack. Several threads may be in one pool at once, and a thread may re-enter a pool; ends are strictly LIFO per thread. Each capture and each route takes a sequence number when it begins, and get_allocation_pool_for_current_stream() picks the newest one that matches. active_routes_ counts all routes and captures, so with none anywhere an allocation pays one relaxed load and never touches TLS. Routes still open when a thread exits are ended by a thread_local destructor, which only updates counts. Each block stores a pointer to its pool, so free() does not look the pool up under instance_mutex_: with the lookup, eight threads in their own pools paid 1227 ns per allocate+free instead of 410 ns.

A pool's new blocks never come from the pinned_reserve_segment_size_mb segment, which is shared, placed by whichever thread allocated first, and never freed.

Alternatives: lazy release by the next empty_host_cache() would keep deleted pools pinned until the user calls it and differs from device ~MemPool. The first revision let a capture always win over a thread's pool and kept HostMemPools out of graphs; 7c1a1e2 replaced that with device MemPool's rules, and also let a HostMemPool be a graph's pool and a MemPool route pinned memory. ca8bb3b drops those two at @galv's suggestion, since they gave a device pool and a host pool the same id; a capture can enter use_mem_pool(host_pool) instead. For ROCm before 7.2, a retry without hipHostMallocNumaUser would also work, but the compile-time check keeps the allocation path free of a fallback. Releasing blocks of a deleted pool when the tensors that hold them are freed, instead of at a later empty_host_cache(), is left out: device MemPool does the same, and doing it well needs the pending events of a dead pool to be processed somewhere.

Test Plan:

CUDA_VISIBLE_DEVICES=1 build/bin/cuda_caching_host_allocator_test
CUDA_VISIBLE_DEVICES=2 PYTORCH_ALLOC_CONF=pinned_use_cuda_host_register:True,pinned_num_register_threads:8 build/bin/cuda_caching_host_allocator_test
CUDA_VISIBLE_DEVICES=3 python -m pytest test/test_cuda.py -k "HostMemPool or CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
CUDA_VISIBLE_DEVICES=4 python -m pytest test/test_cuda.py -k "graph or Graph"
CUDA_VISIBLE_DEVICES=5 python -m pytest test/test_cuda.py -k "MemPool or mempool or mem_pool"
CUDA_VISIBLE_DEVICES=0 python -m pytest test/dynamo/test_ctx_manager.py -k "mem_pool or MemPool"

On A100s, rebased on main aba7352: 22/22 gtests, also with pinned_use_cuda_host_register (4 HostMemPoolTest with a mock backend: a HostMemPool rejected as a capture pool, unrouted threads not querying the stream, thread-exit cleanup, a lifetime stress test; CI does not run this binary); 66 passed; 145 passed, 3 xfailed; 53 passed, 1 failed; 15 passed. The failure is test_mempool_cudamallocasync_subprocess, whose child runs python -S and so skips the .pth hook of an editable scikit-build-core install; torch fails to load there. With main's current-stream check in place of the new alloc/register guards, both cases of test_side_stream_alloc_during_global_capture fail with cudaErrorStreamCaptureUnsupported. A CUDA runtime probe shows that a relaxed cudaFreeHost or cudaHostUnregister on the capturing thread neither fails nor breaks a global- or thread_local-mode capture, which the last commit relies on. The 2-GPU tests (test_use_mem_pool_device_on_entry, test_use_mem_pool_reentered_on_other_device) and the cudaMallocAsync runs were not repeated on this revision; they passed on the previous one, and the device path of use_mem_pool is unchanged since. The ROCm path was not run.

On a two-node host, a 64 MiB block allocated in pools[k] by a thread bound to node k had all pages on node k, also with a reserve segment placed on the other node (measured on the first commit before it was rebased; the routed CUDA path is unchanged since). A mock-backend TSAN and ASAN+UBSan stress test of pools released while routed, concurrent captures, out-of-order ends and threads exiting inside routes showed no new reports on the first commit before it was rebased; it was not re-run on the later commits. Allocate+free of a small pinned tensor, median ns per op, threads pinned to one node:

                             parent     this change
                            no pool   no pool   own pool(s)
1 thread                      407.1     401.0        412.0
8 threads                    8927.4    8620.3        422.0
1 thread, H2D copy per op    8090.3    8152.8       8148.8
8 threads, H2D copy per op  20810.0   20561.2      19496.9

Without the third commit's event-query change, the copy rows were 8441.8 and 8501.6 (1 thread) and 28138.7 and 28478.2 (8 threads), measured in the same run.

🤖 Generated with Claude Code

cc @albanD @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

@pytorch-bot

pytorch-bot Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 1 Pending, 1 Unrelated Failure

As of commit b35ca6e with merge base 175df4e (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 Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: cuda"

@pytorch-bot pytorch-bot Bot added the release notes: cuda release notes category label Oct 13, 2026
@galv
galv self-requested a review October 21, 2026 17:33
@sujuyu

sujuyu commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel, following your suggestion in #197868, I've implemented explicit host memory pools here. Could you take a look at the proposed interaction with CUDA graph pools in the PR description? I'm keeping this as a draft pending feedback on those semantics. Thanks!

@kapilsh
kapilsh self-requested a review October 27, 2026 01:00
std::lock_guard<std::mutex> gf(pool.free_list_[index].mutex_);
destroy_block(block, pool, /*is_active=*/true);
// Push first, so that the block stays in the pool if that throws.
detached.push_back(block);

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.

This was flagged by an AI Review

When a program releases a HostMemPool, the allocator frees the cached blocks of the pool immediately. It does not free the blocks that tensors use. When the program frees such a tensor later, this function puts the block on the free list of the released pool. No thread can route to that pool again. Thus, the allocator cannot use the block again. The block stays pinned until the program calls torch.accelerator.empty_host_cache(). Most training programs do not call this function.

Example:

  • A loader uses one pool for each NUMA node to load a model.
  • After the load, the loader releases the pools.
  • The model keeps some pinned tensors and frees them later.
  • The memory of these tensors stays pinned until the process stops. The OS cannot use it.

The device MemPool operates in the same way. Its free_block() also puts the block back into a freeable pool. But pinned host memory is a shared resource, and the OS cannot get it back.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This aligns with device MemPool: after a pool is deleted, blocks still held by tensors return to it when freed, and the next empty_cache releases them. One difference is that the device allocator also releases freeable pools when cudaMalloc fails, whereas the host allocator has no such retry logic. Releasing these blocks immediately when the tensors are gone would require processing the pending events of a deleted pool somewhere—without blocking free() or putting cudaFreeHost on another thread's allocation path. Because of this complexity, I left it out of this PR and documented the current behavior. I'm happy to tackle it in a follow-up, for example, by releasing deleted pools and retrying when cudaHostAlloc fails.

allocate_host_memory_slowpath(size, ptr);
}

void allocate_host_memory_slowpath(size_t size, void** 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.

Flagged by AI Review

This PR expects the OS to put pinned pages on the NUMA node that the calling thread selects. This is correct for cudaHostAlloc. It is possibly not correct for ROCm.
On ROCm, hipify changes this file. allocate_host_memory_slowpath() then calls hipHostMalloc(ptr, size, hipHostMallocDefault). The HIP header has a different flag for placement by the NUMA policy of the user:

* Host memory allocation will follow numa policy set by user.
*/
#define hipHostMallocNumaUser  0x20000000

AMD TransferBench sets hipHostMallocNumaUser for pinned host memory, so that the allocation obeys the NUMA policy. Without this flag, HIP can select the node itself, for example from the current device. Also, before the call, allocate_host_memory_slowpath() sets the current device to a device that has a primary context. This device is frequently device 0.
Do the placement test from the PR description on an MI300 host. If a pool block does not obey the thread binding, do one of these steps:

  • Set hipHostMallocNumaUser for host mem pool blocks when USE_ROCM is defined.
  • Tell users in the docs that NUMA placement through HostMemPool is available only on CUDA.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I added this in the follow-up commit for blocks a context allocates into its pool on ROCm 7.2+. For earlier versions, we keep the default placement because HIP fails the allocation instead of falling back when get_mempolicy is blocked (e.g., by Docker's default seccomp profile). Also note that HIP only honors MPOL_BIND and MPOL_PREFERRED here, not CPU affinity alone—I've updated the docs to reflect this. I verified this against the HIP/CLR sources, though I don't have an MI300 to test on.

Comment thread docs/source/notes/cuda.md Outdated
Comment on lines +1018 to +1019
with torch.cuda.use_host_mem_pool(pool):
buf = torch.empty(1024, pin_memory=True) # allocated from pool

@kapilsh kapilsh Oct 27, 2026 •

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.

is it feasible to have something to the effect of use_mem_pool(pool: MemPool | HostMemPool, ...). I feel api might be more natural that way

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done, via your commit.

Comment thread docs/source/notes/cuda.md
Comment on lines +1037 to +1039
* Use contexts from synchronous code, on threads you control. A context that stays open across
an `await` or a generator's `yield` also routes whatever runs on the thread in between. The
pin-memory thread of {class}`torch.utils.data.DataLoader` is not covered yet.

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.

curious why we decided to skip DataLoader?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Routing is strictly per-thread. When using pin_memory=True with num_workers > 0, DataLoader pins batches in its own dedicated pin-memory thread. Since that thread operates outside the user's context, those batches will fall back to the default pool. To cover this case, we'd need a new DataLoader option (e.g., specifying a pool for that thread to enter), so I'd prefer to handle it in a separate PR. Note that with num_workers=0, pinning happens on the calling thread and is therefore already covered.

Comment thread docs/source/notes/cuda.md Outdated
Comment on lines +1050 to +1053
underway (where `cudaFreeHost` would invalidate the capture), are freed by a later
{func}`torch.accelerator.empty_host_cache`. As with `empty_host_cache`, a capture that another
thread begins while the pool is being freed is not waited for, so avoid deleting pools while
other threads may start a capture.

@kapilsh kapilsh Oct 27, 2026 •

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.

what happens if user forgets to call empty_host_cache - do we leak page-locked memory ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same as the first comment: the memory isn't lost. The allocator still tracks it, it shows up in host_memory_stats, and empty_host_cache releases it, but it stays pinned until then.

Comment thread docs/source/notes/cuda.md Outdated
Comment on lines +1097 to +1099
Stream-ordered host memory pools (`cudaMemPoolCreate` with `cudaMemLocationTypeHostNuma`,
CUDA 12.8+) could back a HostMemPool with explicit placement in the future, and this API may
move to {mod}`torch.accelerator`.

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.

we can probably just remove this for now

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed.

@kapilsh

kapilsh commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

I sent this sample commit that should get host mempool closer to current devide pools for graph capture -- sujuyu#1

cc: @ngimel

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Nov 2, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

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

@pytorch-bot

pytorch-bot Bot commented Nov 2, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@sujuyu

sujuyu commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @kapilsh! Your sample commit has been merged into this PR with your authorship retained, so sujuyu#1 now shows as merged. I've added a follow-up commit on top:

  • The relaxed capture-mode guard in query_event now only applies while a capture is registered with the allocator. cudaThreadExchangeStreamCaptureMode serializes threads in the driver (275 ns per set/restore pair on a single thread, 6.6 μs per thread with eight), so with the previous commit, eight threads each allocating a pinned tensor, copying it to the GPU and freeing it went from 20.7 to 28.1 μs per op, even without pools. It is now back to 20.6 μs.
  • CUDAGraph::reset() now releases the graph's own host pool before the retained ones, in the same order as the device side. Without this, a block that the capture allocated in a retained HostMemPool, and that a stream used, would remain pinned after del pool; graph.reset() until empty_host_cache is called, even though nothing uses it anymore.
  • Dynamo special-cases use_mem_pool._recreate_cm, so functions decorated with @torch.cuda.use_mem_pool(pool) still compile with fullgraph=True.
  • use_mem_pool reads the current device on entry again, matching the behavior of the old generator.
  • On ROCm 7.2+, blocks allocated by a context for its pool now use hipHostMallocNumaUser.
  • HostMemPoolTest.not_a_capture_pool in cuda_caching_host_allocator_test still expected the check your commit removed (since CI doesn't run that binary), so I rewrote it to match the new semantics.
  • Updated comments, docs, and type hints. Without adding HostMemPool to _GraphPool, pyrefly flags graph._retain_pool(self._pool).

I've updated the PR description accordingly. I'll keep this as a draft until the graph semantics are finalized.

@kapilsh

kapilsh commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

I've updated the PR description accordingly. I'll keep this as a draft until the graph semantics are finalized.

@ngimel and I chatted a bit about this - mostly feedback was to align the capture behavior to cuda alloc, hence I sent the commit to your PR.

Feel free to resolve conflicts and mark for review. I have looked at it once - i will go over it again.

@sujuyu
sujuyu force-pushed the host-alloc/host-mempool branch from 7ff1b8e to f41ff46 Compare November 5, 2026 02:15
@sujuyu
sujuyu marked this pull request as ready for review November 5, 2026 02:16

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

Thanks for picking up the commit and for the follow-up. I left a couple of small comments - also seems like some CI tests are failing - can you please look into those?

Comment thread torch/cuda/memory.py Outdated
device = self._args[1]
if device is None:
device = torch.cuda.current_device()
self._device_index = _get_device_index(device)

@kapilsh kapilsh Nov 6, 2026 •

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.

this breaks nesting of use_mem_pool though I am not if that will ever be used -- can we assign one index on each entry and pop in _end_device?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fair point. This was my follow-up's fault — moving the device lookup into __enter__ caused it. Fixed in 87ffb32 the way you suggested: each entry pushes its device and _end_device pops it. The new test_use_mem_pool_reentered_on_other_device enters the context on cuda:0, re-enters it on cuda:1, and checks that both routes end cleanly.

Comment thread docs/source/notes/cuda.md Outdated
Comment on lines +1109 to +1111
* Blocks that a context allocates for its pool never come from the
`pinned_reserve_segment_size_mb` segment, which the first allocating thread placed for the
whole process.

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.

so seems we added allocate_host_mem_pool_memory which skips the reserve segment but that skip only happens when the pool is reached through use_mem_pool route. It doesn't happen when the same pool is passed as graph(pool=hp)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right — a capture into the pool was going through the default path, so graph(pool=hp) could pull blocks from the reserve segment, which lives on the node of whichever thread allocated first. Fixed in 87ffb32: the choice now keys off the pool itself, not how it's reached, so captures into a HostMemPool also go through allocate_host_mem_pool_memory. Captures into ordinary graph pools still use the reserve segment. I folded this bullet into the next one and added the capture case to test_reserve_segment_not_used.

@sujuyu

sujuyu commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @kapilsh! Both comments are addressed in 87ffb32, and I've updated the PR description.

On the CI failures:

BC Lint flags use_mem_pool as deleted because 6fbe512 turned it from a function into a class. with use_mem_pool(pool), use_mem_pool(pool, device), and @use_mem_pool(pool) all still work, so I think this is a false positive. Could you add the suppress-bc-linter label?

Lint / pr-sanity-checks fails because the PR touches about 2,080 lines, over the 1,500 limit. Roughly 940 are tests and about 100 are docs. It also includes the 368 lines of #200733, but even without them it would be about 1,710. Could you add skip-pr-sanity-checks, or would you rather I split the PR?

The three ASAN jobs failed during setup, before any test ran (the build-artifact download was cut short on those runners, while the other shards used the same artifact and passed), so they look like infra flakes.

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

Please address the lint failures before merging

@sujuyu

sujuyu commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "suppress-bc-linter"

@pytorch-bot pytorch-bot Bot added the suppress-bc-linter Suppresses the failures of API backward-compatibility linter (Lint/bc_linter) label Nov 10, 2026
@sujuyu

sujuyu commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the approval, @kapilsh! A quick update on the remaining failures:

collect_env (older_python_version) was broken on trunk but is fixed by #203982, so it should pass on the next push.

The BC Lint error is a false positive from the function-to-class change. I've added suppress-bc-linter.

pr-sanity-checks: The PR is ~2,080 lines, which is over the 1,500 limit. Adding skip-pr-sanity-checks requires write access—could you add it? Alternatively, I can split the PR if you prefer.

Once the labels are added, I'll rebase and push to trigger the checks again.

@sujuyu

sujuyu commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@kapilsh The trunk failures are caused by redis 8.2.0 failing to import under python -bb, already fixed on main by #206270. These failures are unrelated to this PR. Could you merge with -i to avoid rebasing?

@kapilsh

kapilsh commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot rebase -b main

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

sujuyu and others added 8 commits November 25, 2026 03:51
This adds a pinned host memory pool, the host counterpart of
torch.cuda.MemPool / torch.cuda.use_mem_pool, as suggested in pytorch#197868:

```python
hpool = torch.cuda.HostMemPool()
with torch.cuda.use_host_mem_pool(hpool):
    buf = torch.empty(n, pin_memory=True)  # comes from hpool
```

It is stacked on "[CachingHostAllocator] Call free_block outside allocator
locks", whose PendingHostFrees frees blocks with no allocator lock held.

The motivating use is one pool per NUMA node, entered by the loader threads
bound to that node. cudaHostAlloc places and pins the pages of a new block on
the calling thread's node, and pinned pages never move, so the allocator needs
no NUMA knowledge. A pool guarantees cache isolation: a freed block returns to
its pool, whichever thread frees it, and is handed out again only to threads
routed to that pool. Because placement follows the thread that calls
cudaHostAlloc, routing follows the current thread (thread_local), not a stream
filter in captures_underway_.

Design (aten/src/ATen/core/CachingHostAllocator.h, best reviewed first): a host
mem pool is a HostPrivatePool marked is_host_mem_pool, with an id from
MemPool::graph_pool_handle, so it never collides with a graph pool.
begin/end_allocate_current_thread_to_pool() push and pop a route on the calling
thread's route stack. Several threads may be in one pool at once, and a thread
may re-enter a pool; ends are strictly LIFO per thread. active_routes_ counts
all routes, so with no route anywhere an allocation pays one relaxed load and
never touches TLS. Routes still open when a thread exits are ended by a
thread_local destructor, which only updates counts.

CUDA graph capture and host mem pools: capture wins over thread routes, in
either entry order, and a graph never holds a host mem pool. A host mem pool
id cannot be a graph pool: CUDAGraph::capture_begin rejects it before it
changes any state, since it routes the device allocator first. Host
empty_cache(), which torch.cuda.graph calls on entry, leaves the cache of a
live host mem pool alone.

When a HostMemPool is deleted and no thread is routed to it, its cached blocks
are freed at once through a PendingHostFrees, with the GIL released, as device
~MemPool does with emptyCache(id). If a capture is already underway, where
cudaFreeHost would invalidate it, they wait for the next empty_cache(), as do
blocks still in use. A capture that another thread begins while those blocks
are being freed is not waited for, which is also true of empty_cache() today
(found in a GPT-6 Astra review).

Host mem pool blocks never come from the pinned_reserve_segment_size_mb
segment, which is shared, placed by whichever thread allocated first, and
never freed. Each block stores a pointer to its pool, so free() does not look
the pool up under instance_mutex_: with the lookup, eight threads in their own
pools paid 1227 ns per allocate+free instead of 410 ns.

use_host_mem_pool is a small class rather than a generator, so that exiting a
context out of order or on another thread raises and changes nothing. The docs
state the limits: synchronous code on threads the caller controls, no
DataLoader pin-memory thread yet, and no fork.

Alternatives: lazy release by the next empty_host_cache() would keep deleted
pools pinned until the user calls it and differs from device ~MemPool. A
record_event() fast path for routed threads, and moving
captures_underway_empty_ off the cache line of instance_mutex_, changed no
benchmark case beyond noise, so both are left out.

Test Plan:

```
CUDA_VISIBLE_DEVICES=0 build/bin/cuda_caching_host_allocator_test
CUDA_VISIBLE_DEVICES=0 python -m pytest test/test_cuda.py -k "HostMemPool"
CUDA_VISIBLE_DEVICES=0 python -m pytest test/test_cuda.py -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
CUDA_VISIBLE_DEVICES=0 python -m pytest test/test_cuda.py -k "TestMemPool"
CUDA_VISIBLE_DEVICES=0 python -m pytest test/test_cuda.py -k "graph or Graph"
```

On an A100: 19/19 gtests (4 new HostMemPoolTest with a mock backend: the
allocator's own capture-pool check, unrouted threads not querying the stream,
thread-exit cleanup, a lifetime stress test; CI does not run this binary, so
the Python tests cover every user-visible behavior); 15 passed; 41 passed, 3
skipped (existing skips); 31 passed, 20 skipped; 118 passed, 37 skipped, 3
xfailed.

Local checks with programs not in this PR: a mock-backend stress test of pools
released while routed, concurrent captures, out-of-order ends and threads
exiting inside routes showed no new TSAN or ASAN+UBSan reports. On a two-node
host, a 64 MiB block allocated in pools[k] by a thread bound to node k had all
pages on node k, also with a reserve segment placed on the other node.
Allocate+free of a small pinned tensor, median ns per op, parent vs this
change, threads pinned to one node:

```
                             parent     this change
                            no pool   no pool   own pool(s)
1 thread                      398.8     403.1        410.4
8 threads                    8695.2    8422.3        409.5
8 threads, H2D copy per op  20857.7   20677.3      19516.9
```

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

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…MemPool

Pinned host pools now follow the same rules as device MemPool under CUDA graph
capture: allocations go to the pool they are assigned to, and graphs keep the
pools they use until reset().

1. The newest scope wins, as in the device allocator. Each capture scope and
   thread route gets a sequence number when it begins, and an allocation uses
   the newest matching scope. A pool context entered inside a capture takes
   the allocation, as use_mem_pool does; before, the capture always won. A
   HostMemPool can also be a graph's pool.

2. Graphs hold host pools and release them at reset.
   - CUDAGraph::retain_pool() also takes a host reference; reset() releases it.
   - use_mem_pool calls it when entered during a capture.
   - Each block used during a capture records the capture's pool
     (capture_owner_). When the last graph holding that pool releases it, those
     blocks become reusable. Before, they were never freed. Graphs that share
     a pool keep these blocks until the last of them is reset, because the CPU
     writes into a pinned block are not captured, and a block reused while a
     graph is alive would change what that graph reads on replay.

3. cudaHostAlloc/cudaHostRegister, cudaFreeHost/cudaHostUnregister and
   cudaEventQuery run in relaxed capture mode, so pinned allocations on side
   streams and other threads no longer invalidate a running capture.

4. One API. use_mem_pool(pool, device=None, *, pinned=None) replaces
   use_host_mem_pool. A MemPool with pinned=True routes device and pinned
   allocations to one pool id; a HostMemPool routes pinned allocations only.
   Contexts that route pinned memory must be exited in reverse order, on the
   thread that entered them. Dynamo matches the new class and rejects
   pinned=True under torch.compile.

Test plan:
python test/test_cuda.py TestHostMemPool
python -m pytest test/test_cuda.py -k "TestMemPool or graph or Graph or pinned or host_memory"
python -m pytest test/dynamo/test_ctx_manager.py -k "mem_pool or mempool"
…MemPool

The previous commit wrapped every cudaEventQuery of the host allocator in a
relaxed CUDAStreamCaptureModeGuard, so that a global-mode capture on another
thread does not reject it. Each guard makes two
cudaThreadExchangeStreamCaptureMode calls, and those serialize threads in
the driver: a pair took 275 ns on one thread and 6.6 us per thread with
eight threads (A100, CUDA 12.8). With eight threads each allocating a small
pinned tensor and copying it to the GPU, allocate+free went from 20.7 to
28.1 us in the default pool and from 19.4 to 28.5 us in per-thread pools.
query_event now switches modes only while a capture is registered with the
allocator, the case the guard is for; CUDAGraph registers its capture
before cudaStreamBeginCapture and deregisters it after cudaStreamEndCapture.
The two cases are back to 20.6 and 19.5 us. Captures the allocator does not
see, such as one begun outside CUDAGraph or the moment a capture switches
into or out of a conditional node, get unguarded queries, as before the
previous commit.

CUDAGraph::reset released the pools a graph retained before the graph's own
host pool. A block that a capture allocated in a retained HostMemPool and a
stream used is reclaimed only when the graph's own pool goes, so after
`del pool; graph.reset()` the HostMemPool had already been emptied without
it, and the block stayed pinned until a later empty_host_cache. reset now
releases the graph's own pool first, as the device side does.

Turning use_mem_pool into a class also broke functions decorated with
@torch.cuda.use_mem_pool(pool) under torch.compile: the decorator now calls
the class's _recreate_cm, which Dynamo skips (torch/cuda is not inlined), so
fullgraph=True raised Unsupported where the generator's path compiled.
UserMethodVariable now special-cases that method, as it already does
FSDPParamGroup.use_training_state, and rebuilds the context from the
instance's arguments, so the decorator form traces like the `with` form
again.

The previous commit also made use_mem_pool a class that reads the current
device in __init__. The generator it replaced read it on entry, so a context
built first and entered under another torch.cuda.device no longer routed
that device's allocations. __enter__ reads it again.
(_get_device_index(device, optional=True) would also have accepted
torch.device("cuda") without an index, which the old code rejected, so the
None case stays explicit.)

On ROCm, hipHostMalloc takes pinned pages from the CPU node nearest the
current device unless hipHostMallocNumaUser is set, so a pool did not keep
its blocks on the allocating thread's node. Blocks that a context allocates
for its pool now set that flag on ROCm 7.2 and later. Before 7.2, HIP fails
the allocation when get_mempolicy is blocked, as under Docker's default
seccomp profile, instead of falling back to the default node; a compile-time
version check keeps those versions on the old behavior without a retry path.
HIP follows only MPOL_BIND and MPOL_PREFERRED, which the notes now say. This
was checked against the HIP/CLR sources, not tested on ROCm hardware.

The previous commit also left HostMemPoolTest.not_a_capture_pool expecting
the capture-pool check it removed (CI does not run this binary). The test
now checks that a capture into a host mem pool keeps a block that a stream
used until the pool's last reference is released. Comments in
CachingHostAllocator.h, MemPool.h, the notes and the docstrings that still
described the old rules (a capture always wins, a graph never holds a host
pool, captured blocks are never reused, deleting a pool frees it at once)
now describe the current ones, and the unused HostAllocator::is_host_mem_pool
virtual is removed. _GraphPool and the _MemPool stub gain HostMemPool and
_enable_pinned; without them pyrefly reports bad-argument-type for
graph._retain_pool(self._pool). The notes drop the paragraph on possible
future backends, as asked in review, and the previous commit's lint issues
are fixed; the HostMemPool pinned=False error now reads like the device one.

Test Plan:

```
CUDA_VISIBLE_DEVICES=0 build/bin/cuda_caching_host_allocator_test
CUDA_VISIBLE_DEVICES=1 python test/test_cuda.py TestHostMemPool
CUDA_VISIBLE_DEVICES=2,3 python -m pytest test/test_cuda.py -k "TestMemPool or graph or Graph or pinned or host_memory"
CUDA_VISIBLE_DEVICES=4 python -m pytest test/test_cuda.py -k "CachingHostAllocator or host_memory or pin_memory or host_emptyCache or HostMemPool"
CUDA_VISIBLE_DEVICES=5 python -m pytest test/dynamo/test_ctx_manager.py -k "mem_pool or mempool"
CUDA_VISIBLE_DEVICES=3 PYTORCH_ALLOC_CONF=backend:cudaMallocAsync python test/test_cuda.py TestMemPool.test_mempool_cudamallocasync TestMemPool.test_mempool_cudamallocasync_custom_allocator
lintrunner --skip CLANGTIDY <changed files>
```

On A100s, rebased on viable/strict 609ff97: 19/19 gtests; 19 passed;
181 passed, 59 skipped (CPU variants of device-type tests, no cuda-python,
SM90-, ROCm- or cudaMallocAsync-only, no green contexts, or disabled
upstream), 3 xfailed, 1 failed; 53 passed, 3 skipped; 15 passed, 1 skipped;
2 passed; lint clean, including PYREFLY. The failure is
test_mempool_cudamallocasync_subprocess, whose child runs `python -S` and so
skips the .pth hook of an editable scikit-build-core install; torch fails to
load there. The two tests it runs pass when run directly (last command).
Without the memory.py change, test_use_mem_pool_device_on_entry fails, and
without the Dynamo change, test_cuda_use_mem_pool_decorator fails.

The timings come from a local C++ program, not part of this PR, that
allocates and frees a small pinned tensor through libtorch, optionally
copying it to the GPU, with threads pinned to one NUMA node; builds of the
parent, of this branch with and without the query_event change, and of the
first revision ran interleaved, 8 rounds of 3 repetitions each.

Authored with assistance from Claude Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g the reserve segment

Two fixes from review.

The previous commit made use_mem_pool read the current device on entry and
keep it in one attribute, which every __enter__ overwrote. Re-entering one
context on another device, as in

    with torch.cuda.device(0), ctx:
        with torch.cuda.device(1), ctx:
            ...

made the outer exit end the route on device 1 a second time: it raised
"endAllocatePool: not currently recording to mempool_id" and left device 0
routed to the pool. The context now keeps one device per open entry, pushed
on entry and popped on exit. Sharing one context object between threads that
use different devices is still unsupported; the generator that use_mem_pool
replaced could not be entered twice at all.

New blocks of a host mem pool skipped the pinned_reserve_segment_size_mb
segment only when a thread routed to the pool allocated them. A capture into
a HostMemPool, as in torch.cuda.graph(g, pool=hp), still carved them out of
the reserve segment, which the first allocating thread placed for the whole
process, so a pool kept per NUMA node could take blocks from another node.
get_allocation_pool_for_current_stream now reports whether the pool is a host
mem pool instead of whether a thread route matched, so both paths allocate
through allocate_host_mem_pool_memory. Captures into other graph pools still
use the reserve segment. A MemPool's host pool becomes a host mem pool at its
first use_mem_pool(pool, pinned=True), as before, so a capture into it before
that still takes blocks from the segment; the notes, which merge the two
placement bullets into one, say so.

Test Plan:

```
CUDA_VISIBLE_DEVICES=2 build/bin/cuda_caching_host_allocator_test
CUDA_VISIBLE_DEVICES=2 python test/test_cuda.py TestHostMemPool
CUDA_VISIBLE_DEVICES=3,4 python -m pytest test/test_cuda.py -k "TestMemPool or graph or Graph or pinned or host_memory"
CUDA_VISIBLE_DEVICES=5 python -m pytest test/test_cuda.py -k "CachingHostAllocator or host_memory or pin_memory or host_emptyCache or HostMemPool"
CUDA_VISIBLE_DEVICES=5 python -m pytest test/dynamo/test_ctx_manager.py -k "mem_pool or mempool"
CUDA_VISIBLE_DEVICES=3 PYTORCH_ALLOC_CONF=backend:cudaMallocAsync python test/test_cuda.py TestMemPool.test_mempool_cudamallocasync TestMemPool.test_mempool_cudamallocasync_custom_allocator
lintrunner --skip CLANGTIDY <changed files>
```

On A100s: 19/19 gtests; 19 passed; 182 passed, 59 skipped, 3 xfailed,
1 failed; 53 passed, 3 skipped; 15 passed, 1 skipped; 2 passed; lint clean.
The failure is test_mempool_cudamallocasync_subprocess, as for the previous
commit: its child runs `python -S`, which skips the .pth hook of the
editable install, and the two tests it runs pass directly (last command).

Without the memory.py change, the new
test_use_mem_pool_reentered_on_other_device fails with the endAllocatePool
error. Without the CachingHostAllocator.h change,
test_reserve_segment_not_used prints "True False True": the block captured
into the HostMemPool came from the reserve segment.

Authored with assistance from Claude Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A capture that enters use_mem_pool(pool) calls CUDAGraph::retain_pool, which
also takes a host reference on the pool's id when the host allocator has a
pool with that id. The host retain_pool only checked that the pool exists. A
released graph pool (use_count 0) stays in graph_pools_ until an
empty_cache() finds it without blocks, so retain_pool could take it back to
use_count 1 while it was still in graph_pools_freeable_. Resetting that graph
released it again, and the assert in make_freeable_under_lock that a pool
becomes freeable only once fired. reset() stopped before clearing its state,
so ~CUDAGraph released the graph's pools a second time, the use_count assert
fired in the destructor, and the process aborted:

    mp = torch.cuda.MemPool()
    g1 = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g1, pool=mp.id):
        kept = torch.empty(1000, pin_memory=True)
    g1.reset()  # releases mp's host pool; kept keeps it in graph_pools_
    g2 = torch.cuda.CUDAGraph()
    with torch.cuda.graph(g2):
        with torch.cuda.use_mem_pool(mp):
            torch.ones(1, device="cuda")
    g2.reset()  # raises, then ~CUDAGraph aborts

The device allocator does not hit this: a MemPool holds a device reference
for its whole life, but a host reference only once it routes pinned memory.

retain_pool now returns false for a released pool, as for an absent one, so
the graph does not hold it. The other paths that add a reference or a route
to an existing pool, create_or_incref_pool_under_lock and
begin_allocate_current_thread_to_pool, already require use_count > 0.
Raising, as those paths do, would break captures like g2's that use the
MemPool only for device memory. Reviving the pool, by taking it out of
graph_pools_freeable_, would make retain_pool the only path that brings a
released pool back.

retain_pool is new in this stack, so main is not affected.

Test Plan:

```
CUDA_VISIBLE_DEVICES=2 build/bin/cuda_caching_host_allocator_test
CUDA_VISIBLE_DEVICES=2 PYTORCH_ALLOC_CONF=pinned_use_cuda_host_register:True,pinned_num_register_threads:8 build/bin/cuda_caching_host_allocator_test
CUDA_VISIBLE_DEVICES=2 python test/test_cuda.py TestHostMemPool
CUDA_VISIBLE_DEVICES=3,4 python -m pytest test/test_cuda.py -k "TestMemPool or graph or Graph or pinned or host_memory"
CUDA_VISIBLE_DEVICES=5 python -m pytest test/test_cuda.py -k "CachingHostAllocator or host_memory or pin_memory or host_emptyCache or HostMemPool"
CUDA_VISIBLE_DEVICES=5 python -m pytest test/dynamo/test_ctx_manager.py -k "mem_pool or mempool"
CUDA_VISIBLE_DEVICES=3 PYTORCH_ALLOC_CONF=backend:cudaMallocAsync python test/test_cuda.py TestMemPool.test_mempool_cudamallocasync TestMemPool.test_mempool_cudamallocasync_custom_allocator TestHostMemPool.test_capture_does_not_retain_released_pool
lintrunner -a --skip CLANGTIDY aten/src/ATen/core/CachingHostAllocator.h test/test_cuda.py
```

On A100s, on viable/strict 0e5f6cd: 20/20 gtests in both
configurations; 20 passed; 188 passed, 3 xfailed, 1 failed; 56 passed;
15 passed; 3 passed; lint clean. The failure is
test_mempool_cudamallocasync_subprocess, as for the previous commits: its
child runs `python -S`, which skips the .pth hook of the editable install,
and the two tests it runs pass directly (last test command).

Without the CachingHostAllocator.h change, the new
test_capture_does_not_retain_released_pool aborts the test process (exit
134, "uc >= 0 INTERNAL ASSERT FAILED").

Authored with assistance from Claude Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… graph pools

@galv asked to remove torch.cuda.graph(pool=HostMemPool) and
use_mem_pool(mp, pinned=True): both give a device pool and a host pool the
same id, and nothing here needs them. A capture that should take pinned
memory from a HostMemPool can enter use_mem_pool(host_pool) inside the
capture instead, which wins on the capturing stream and makes the graph
keep the pool.

This restores the rejection from the first commit: graph(pool=hp) raises
TypeError, and CUDAGraph::capture_begin and begin_allocate_to_pool reject a
HostMemPool id before changing any state. MemPool::enable_pinned and
create_or_incref_host_mem_pool go away. CUDAGraph._retain_pool still takes a
HostMemPool, and the allocator's retain_pool now takes only host mem pools,
so a device MemPool entered during a capture no longer takes a reference on
a host pool that shares its id. The rest of the capture rules stay: the
newest scope wins, and a pinned block allocated on a capturing stream and
used by a stream is not reused until the graphs using that capture's pool
are reset.

use_mem_pool.__enter__ now ends the routes it began if retaining the pool
fails, as the try/finally of the generator version did.

Test Plan:

test_not_a_graph_pool and the gtest not_a_capture_pool (both from the first
commit) check the rejection; test_wrong_pool_type checks the TypeError. The
tests that used the dropped APIs are removed or rewritten.

```bash
build/bin/cuda_caching_host_allocator_test
python -m pytest test/test_cuda.py -k "HostMemPool or CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
python -m pytest test/dynamo/test_ctx_manager.py -k "mem_pool or MemPool"
```

Authored with assistance from Claude Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng captures

cudaHostAlloc and cudaHostRegister ran in relaxed capture mode
unconditionally. They now do so only while a capture is registered with the
allocator, like the event query (the captures_underway check from pytorch#174724).
That still covers what main's current-stream check does not: inside a
HostMemPool context, a capture begun on this thread takes only the capturing
stream, so an allocation on another stream goes to the pool, and allocating
a block or querying a block's event there runs on the capturing thread while
its current stream is not capturing. Frees stay relaxed unconditionally
(pytorch#200733).

Test Plan:

test_side_stream_alloc_during_global_capture allocates on a side stream from
the routed pool during a global-mode capture, querying a pending event and
allocating a new block, in both pinned_use_cuda_host_register modes. With
main's current-stream check instead, both cases fail with
cudaErrorStreamCaptureUnsupported and invalidate the capture.

```bash
python -m pytest test/test_cuda.py -k test_side_stream_alloc_during_global_capture
```

Authored with assistance from Claude Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A released HostMemPool kept its cache until a later empty_cache() while any
capture was underway, since cudaFreeHost would have invalidated the capture.
Frees now run in relaxed capture mode (pytorch#200733), and a relaxed cudaFreeHost
or cudaHostUnregister, even on the capturing thread, neither fails nor
breaks a global- or thread_local-mode capture (checked with a CUDA runtime
probe on an A100, CUDA 12.8, driver 575). So the pool frees its cache at
once in every case.

Test Plan:

test_del_during_capture_frees deletes a pool inside a global-mode capture
on the same thread, checks that its block is freed at once, and replays the
graph.

```bash
python -m pytest test/test_cuda.py -k test_del_during_capture_frees
```

Authored with assistance from Claude Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased host-alloc/host-mempool onto refs/remotes/origin/main, please pull locally before adding more changes (for example, via git checkout host-alloc/host-mempool && git pull --rebase)

@kapilsh

kapilsh commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

these failures are unrelated to this PR. Could you merge with -i to avoid rebasing?

yeah - I think might need a rebase - I just triggered it so hopefully they should go away now

@kapilsh

kapilsh commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@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

@sujuyu
sujuyu deleted the host-alloc/host-mempool branch November 25, 2026 07:06
kapilsh added a commit to kapilsh/pytorch that referenced this pull request Nov 29, 2026
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. The callbacks have the same signatures as in
MemPool.from_py_allocator. 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.

HostAllocator::create_pool gets an optional allocator argument. pytorch#200762
added this virtual function, and no release contains it.

alloc_fn runs in relaxed capture mode while a CUDA graph capture is
registered, as cudaHostAlloc does. free_fn always does, as cudaFreeHost
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.

The public API is only from_py_allocator. HostMemPool() has no
arguments. A later change can add other allocator types if necessary.

Test Plan:

```
build/bin/cuda_caching_host_allocator_test
cd test && python test_cuda.py -k TestHostMemPool -k TestCachingHostAllocator -k pinned
```

All 24 gtests pass. test_cuda.py: 66 tests, 0 failures, 3 skipped.

An AI assistant (Claude Code) helped write this change.
kapilsh added a commit to kapilsh/pytorch that referenced this pull request Nov 30, 2026
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. The callbacks have the same signatures as in
MemPool.from_py_allocator. 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.

HostAllocator::create_pool gets an optional allocator argument. pytorch#200762
added this virtual function, and no release contains it.

alloc_fn runs in relaxed capture mode while a CUDA graph capture is
registered, as cudaHostAlloc does. free_fn always does, as cudaFreeHost
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.

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. A later change can add other allocator types if necessary.

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 fix.
test_cuda.py: 66 tests, 0 failures, 3 skipped.

An AI assistant (Claude Code) helped write this change.
kapilsh added a commit to kapilsh/pytorch that referenced this pull request Nov 30, 2026
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. The callbacks have the same signatures as in
MemPool.from_py_allocator. 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.

HostAllocator::create_pool gets an optional allocator argument. pytorch#200762
added this virtual function, and no release contains it.

alloc_fn runs in relaxed capture mode while a CUDA graph capture is
registered, as cudaHostAlloc does. free_fn always does, as cudaFreeHost
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.

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. A later change can add other allocator types if necessary.

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 fix.
test_cuda.py: 66 tests, 0 failures, 3 skipped.

An AI assistant (Claude Code) helped write this change.
kapilsh added a commit to kapilsh/pytorch that referenced this pull request Nov 30, 2026
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 pushed a commit to kapilsh/pytorch that referenced this pull request Dec 1, 2026
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 pushed a commit that referenced this pull request Dec 1, 2026
)

## 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::SafePyObject`s 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.
Pull Request resolved: #206673
Approved by: https://github.com/ngimel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo open source release notes: cuda release notes category skip-pr-sanity-checks suppress-bc-linter Suppresses the failures of API backward-compatibility linter (Lint/bc_linter)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants