Repository navigation
Conversation
🔗 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 FailureAs of commit b35ca6e with merge base 175df4e ( 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. |
|
@pytorchbot label "release notes: cuda" |
| 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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 0x20000000AMD 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.
There was a problem hiding this comment.
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.
| with torch.cuda.use_host_mem_pool(pool): | ||
| buf = torch.empty(1024, pin_memory=True) # allocated from pool |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Done, via your commit.
| * 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. |
There was a problem hiding this comment.
curious why we decided to skip DataLoader?
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
what happens if user forgets to call empty_host_cache - do we leak page-locked memory ?
There was a problem hiding this comment.
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.
| 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`. |
There was a problem hiding this comment.
we can probably just remove this for now
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
|
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:
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. |
7ff1b8e to
f41ff46
Compare
kapilsh
left a comment
There was a problem hiding this comment.
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?
| device = self._args[1] | ||
| if device is None: | ||
| device = torch.cuda.current_device() | ||
| self._device_index = _get_device_index(device) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| * 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. |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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.
|
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 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 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
left a comment
There was a problem hiding this comment.
Please address the lint failures before merging
|
@pytorchbot label "suppress-bc-linter" |
|
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 pr-sanity-checks: The PR is ~2,080 lines, which is over the 1,500 limit. Adding Once the labels are added, I'll rebase and push to trigger the checks again. |
|
@pytorchbot rebase -b main |
|
@pytorchbot started a rebase job onto refs/remotes/origin/main. Check the current status here |
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]>
|
Successfully rebased |
yeah - I think might need a rebase - I just triggered it so hopefully they should go away now |
29cefaf to
b35ca6e
Compare
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
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.
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.
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.
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.
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.
) ## 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
spin fixlint)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 withtorch.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)anduse_mem_pool(mp, pinned=True)and relaxcudaHostAlloc/cudaHostRegisteronly 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).
use_host_mem_poolintouse_mem_pool.CUDAGraph::resetreleases the graph's own host pool before the pools it retained, as the device side does,use_mem_poolreads the current device on entry again, Dynamo traces functions decorated withuse_mem_poolagain, HostMemPool blocks usehipHostMallocNumaUseron 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.use_mem_poolkeeps 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.poolwas reset, a capture that entereduse_mem_poolon that MemPool took a host reference on the released pool, and resetting that graph aborted the process.retain_poolnow skips released pools, as the other paths that take a reference or a route already do.torch.cuda.graph(pool=HostMemPool)anduse_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'sretain_poolnow takes only host mem pools.use_mem_pool.__enter__ends the routes it began if retaining the pool fails.cudaHostAlloc/cudaHostRegisterrun in relaxed capture mode only while a capture is registered with the allocator, like the event query, instead of always.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, wheredevice=...raises ValueError.pool:torch.cuda.graph(pool=hp)raises TypeError, andCUDAGraph.capture_beginrejects its id. A graph that entersuse_mem_pool(hp)during its capture keeps the pool instead (see below).use_mem_poolis now a class (acontextlib.ContextDecorator) instead of a@contextmanagerfunction, souse_mem_pool.__wrapped__is gone. Its arguments are unchanged, and withdevice=Nonethe 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.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 thewithform.CUDA graphs: the same rules as device MemPool
CUDAGraph::retain_poolnow also takes a host reference on a HostMemPool, whichreset()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.cudaHostAlloc/cudaHostRegisterand the allocator'scudaEventQueryrun in relaxed capture mode while a capture is registered with the allocator, andcudaFreeHost/cudaHostUnregisteralways 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 beforecudaStreamBeginCaptureand deregisters it aftercudaStreamEndCapture, 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 twocudaThreadExchangeStreamCaptureModecalls, 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.empty_cache(), whichtorch.cuda.graphcalls on entry, leaves the cache of a live pool alone.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 laterempty_cache()frees them instead. Blocks still in use, by tensors, pending copies or another graph that shares the capture's pool, wait for a laterempty_cache(), as with device MemPool.NUMA placement
On CUDA,
cudaHostAllocplaces 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,hipHostMalloctakes the pages from the node nearest the current GPU unlesshipHostMallocNumaUseris set, so a pool's new blocks set that flag on ROCm 7.2 and later. HIP then follows onlyMPOL_BINDandMPOL_PREFERRED, not CPU affinity alone. Before 7.2, HIP fails the allocation instead of falling back whenget_mempolicyis 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
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:
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 -Sand 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:
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