Skip to content

[CachingHostAllocator] Call free_block outside allocator locks - #200733

Closed
sujuyu wants to merge 5 commits into
pytorch:mainfrom
sujuyu:host-alloc/empty-cache-unlocked-free
Closed

sujuyu wants to merge 5 commits into
pytorch:mainfrom
sujuyu:host-alloc/empty-cache-unlocked-free

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
Supported by @ngimel, who asked for this split in #200762 (comment)

BC-breaking?

No. In CachingHostAllocatorImpl, the private virtual methods process_events() and process_events_for_specific_size() gain a PendingHostFrees& parameter, so an out-of-tree override must add it, and the public helper free_from_pool(), used only by empty_cache(), is removed. No in-tree code overrides or calls them.

Summary (human written only)

We run six GPUs in one process. While working on the host mempool from #197868, I found that the host allocator's empty_cache() calls cudaFreeHost while holding allocator locks, and cudaFreeHost waits for all work queued on the current GPU to finish. During that time, any pinned-memory operation in the same process on another GPU (a non_blocking copy, a pinned allocation or free) that needs those locks has to wait too, for as long as that GPU's queue takes. In our repro, with a 2.1 s kernel queued on one GPU, calling empty_cache() stalled a non_blocking copy on another GPU for 2.1 s. This PR only takes blocks out under the lock and frees them after unlocking. Which blocks can be freed is decided the same way as before; the locks only protect the allocator's internal tables, and once a block is taken out no other thread can find it, so freeing it does not need the lock. The problem already exists on main and can be reviewed on its own; the upcoming host mempool PR also relies on it when a pool is destroyed.

Agent details (if applicable)

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

Root cause, fix, alternatives, and test plan

cudaFreeHost waits for the work already queued on the current GPU. On an
A100 (driver 575), behind a 2.1 s kernel it took 2140 ms. empty_cache()
called free_block() while holding allocator locks. For the default pool
these were its blocks_mutex_ and a free-list mutex, which record_event() and
allocate() also take; for released private pools they included
instance_mutex_ held exclusively, which record_event() takes shared. Every
non_blocking pinned copy calls record_event(), so a copy on another GPU
stalled for the whole 2140 ms. Copies on the same GPU wait for cudaFreeHost
either way; that comes from the driver and this change does not affect it.

The fix splits destroy_block(). detach_block() takes a block out of its pool
and updates the stats under the same locks as before, after which no other
thread can reach it. Each reclamation operation returns the blocks it
detached in a PendingHostFrees, a move-only batch that owns them, and the
caller frees them with its free() once no allocator lock is held:
reclaim_completed_blocks() in allocate() and the background thread,
cache_or_reclaim_block() in free(), and reclaim_default_pool_cache() and
reclaim_released_pools() in empty_cache(). All free_block() calls go through
PendingHostFrees, including blocks above pinned_max_cached_size_mb, which
maybe_cache_block() frees instead of caching. empty_cache() reaches that
path through process_events() under the exclusive instance_mutex_, so
process_events() and process_events_for_specific_size() take the batch as a
new parameter. A released pool is still erased only once it has no blocks,
and freeing a detached block does not touch its pool.

free() attempts every block, then rethrows the first error; record_trace()
and free_block() have separate tries, so a failed trace does not skip the
free. An operation constructs its batch before taking any lock, so if it
throws, its locks are released before the batch's destructor frees the
blocks it holds; the destructor ignores free errors, so the operation's own
error propagates.

Since an address can now be handed out again before free_block() returns,
SEGMENT_FREE is recorded before free_block(), and the CUDA backend erases
the use_host_register entry before freeing instead of after, which could
drop the entry of a new allocation at the same address.

Other threads no longer wait for these frees. An allocation that missed the
cache used to wait for a free on another thread whenever it ran into the
locks that free held (the same size bucket, its own reclaim, or
instance_mutex_ while a capture is registered), so under tight CPU memory it
can now fail where it used to succeed. When allocate_host_memory() throws
and frees were in flight around the attempt, allocate() now waits until as
many frees have finished as had started, then retries once. Frees can finish
out of order, so this is best effort: a retry that comes too early fails,
and the error propagates as before. Likewise, empty_cache() can return
before blocks that other threads detached are freed.

A capture that another thread begins is no longer waited for either:
released graph pools used to be freed under the exclusive instance_mutex_,
which capture_begin() takes, and default-pool frees already had this gap.
Global capture mode, the torch.cuda.graph default, forbids cudaFreeHost on
every thread, so free_block() now runs cudaFreeHost and cudaHostUnregister
in relaxed capture mode, with the line from @kapilsh's e9c03c4 in
#200762. Such a free then neither fails nor invalidates the capture. The
guard switches only the freeing thread, which is not the one capturing, so
a guard conditioned on the current stream capturing would not help. Event
queries in empty_cache() still run in the thread's own mode, as on main.

Freeing in maybe_cache_block() after it drops its own locks is not enough,
since empty_cache() calls it under the exclusive instance_mutex_; and
processing released pools without that lock would need another mutex or
reference-counted pools, to keep a concurrent empty_cache() from erasing
them.

Test Plan:

The new gtests use a mock backend and need no GPU. In four of them,
free_block() blocks until the test releases it, and record_event(),
allocate() and free() on another thread must still finish within 10 s. Two
inject errors: when several frees fail, every block is still freed and the
first error is rethrown; when an event query fails after a block was
detached, that block is still freed and the query error wins over its
failing free. In a mock harness these six fail without this change and pass
with it, also under ASAN+UBSan and TSAN. The only sanitizer reports are
LSan's, for the two blocks the allocator never frees after an injected
event failure. The last two cover the retry: an allocation that fails while
another thread's free is blocked waits for that free and then succeeds, and
with no free in flight the error is rethrown without a retry. CI does not
run this binary (aten/tools/run_tests.sh does not list it).

test_free_during_global_capture_on_other_thread frees a block from another
thread while the main thread captures in global mode, in both
pinned_use_cuda_host_register modes. Both cases fail without the relaxed
guard (cudaErrorStreamCaptureUnsupported, then
cudaErrorStreamCaptureInvalidated) and pass with it.

On an A100, with this change on 0e5f6cd, the binary passes all 18 tests,
also with pinned_use_cuda_host_register, and the test_cuda.py selections
below pass (45 passed; 144 passed and 3 xfailed).

build/bin/cuda_caching_host_allocator_test
PYTORCH_ALLOC_CONF=pinned_use_cuda_host_register:True,pinned_num_register_threads:8 build/bin/cuda_caching_host_allocator_test
python -m pytest test/test_cuda.py -q -rfE -p no:cacheprovider -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
python -m pytest test/test_cuda.py -q -rfE -p no:cacheprovider -k "graph or Graph"

The comparisons with and without the change come from the previous revision
of this PR, on main a04f365, where the selections gave the same per-test
results with and without it. Two scripts (not in this PR) loop non_blocking
copies to cuda:1 on one thread while empty_cache() frees a cached 64 MiB
block, from the default pool or from a released CUDA graph pool, behind a
2.1 s kernel on cuda:0. On that revision, the longest copy enqueue took
2140 ms without the change in every run, and about 1 ms or less with it;
empty_cache() itself still takes about 2140 ms.

🤖 Generated with Claude Code

@pytorch-bot

pytorch-bot Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR changes the host caching allocator so that free_block() (cudaFreeHost)
runs after the allocator locks are released, by detaching blocks into a
P​endingHostFrees batch under the locks and freeing them afterwards.
Recommendation: Needs Discussion. The open question is whether CUDA graph
maintainers accept that frees from released graph pools no longer exclude a
concurrent capture_begin. Every other point is non-blocking.

Findings (8):

[minor] aten/src/ATen/core/CachingHostAllocator.h:649
Design decision needed: a concurrent capture_begin no longer waits for frees
from released graph pools. Before, empty_cache() freed released-pool blocks
while holding instance_mutex_ exclusively, and CUDAGraph::capture_begin takes
that lock via begin_allocate_to_pool (CUDAGraph.cpp:244) before
cudaStreamBeginCapture. Now reclaim_released_pools() drops the lock before
.free() runs. Thread B can begin a global-mode capture while thread A is still
running cudaFreeHost calls. A free issued during the capture is prohibited:
AT_CUDA_CHECK throws on A, the remaining blocks' pinned memory leaks, and B's
capture can be invalidated. Default-pool frees already had this gap; the PR
extends it to released-pool blocks (the torch.cuda.graph _host_emptyCache()
path). A shared lock won't work (no atomic downgrade). Fix option: a small
dedicated mutex that empty_cache() holds while freeing released-pool blocks and
that begin_allocate_to_pool takes first. CUDA graph maintainers should decide.
If the gap is accepted, document it in code (e.g. the Note at :176-187), not
only in the PR body.

[minor] aten/src/ATen/core/CachingHostAllocator.h:856
Non-blocking BC: "BC-breaking? No" leaves two things out. (1) process_events and
process_events_for_specific_size are virtual extension points that out-of-tree
backends subclass, and they now take an extra P​endingHostFrees& parameter. An
override written without `override` still compiles but becomes a separate
overload that is never called, so its behavior silently stops running. (2) The
public method free_from_pool(BlockPool&) was removed (a caller is unlikely,
since the pools are private). Mention both in the BC section and the release
note. No in-tree backend is affected.

[minor] aten/src/ATen/core/CachingHostAllocator.h:860
Non-blocking: doc comments don't describe the contracts that changed. free_block
(:1208-1211) should say it can now run with no allocator lock, concurrently with
other free_block calls on the same pool (before, these were serialized under
blocks_mutex_), so a backend's per-pointer state needs its own lock, as the CUDA
use_host_register change shows. The process_events* comment says nothing about
the new `frees` parameter.

[minor] aten/src/ATen/core/CachingHostAllocator.h:1482
Non-blocking: the new HostAllocator::empty_cache() comment says it may return
early only when another empty_cache() runs concurrently. It can also return
before blocks are freed that a concurrent free() of a large block, an
allocate(), or the background thread has already detached.

[minor] aten/src/ATen/core/CachingHostAllocator.h:359
Non-blocking: error handling in P​endingHostFrees::free_blocks(). On the
exception path, the destructor drops free errors without logging, so leaked
pinned memory leaves no trace (drain_deferred_custom_frees_noexcept in
c10/cuda/CUDACachingAllocator.cpp uses LOG(ERROR)). Also, record_trace() is in
the same try as free_block(). If it throws (the ring-buffer insert allocates
when history recording is on), free_block() is skipped but `delete block` still
runs, which leaks pinned memory and breaks the "attempt every block" guarantee.
Give record_trace its own try.

(3 more not shown, see the review run)

Reviewed commit: 0fb6f3b (NOT the current head 3c07b28)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit 3c07b28 with merge base 9a9f91b (image):

NEW FAILURE - The following job has failed:

  • trunk / macos-py3-arm64 / test (openreg, 1, 1, macos-m1-stable) (gh)
    'Test'

    AI verdict: AI verdict: probably not related

    The openreg job on the suspect timed out after 240 minutes. It hung in the torch_openreg Python tests right after its C++ gtests passed, without printing any error. The PR only changes CachingHostAllocatorImpl, which only the CUDA and XPU host allocators (plus a CUDA-only gtest) instantiate. OpenReg's host allocator does not use it, and none of that code runs on a macOS openreg job, so there is no causal path. The same job passes in about 5 minutes on the merge base and on nearby trunk commits, so this looks like a one-off hang.

    Full reasoning on HUD →

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"

cudaFreeHost waits for the work already queued on the current GPU. On an
A100 (driver 575), behind a 2.1 s kernel it took 2140 ms. empty_cache()
called free_block() while holding allocator locks. For the default pool
these were its blocks_mutex_ and a free-list mutex, which record_event() and
allocate() also take; for released private pools they included
instance_mutex_ held exclusively, which record_event() takes shared. Every
non_blocking pinned copy calls record_event(), so a copy on another GPU
stalled for the whole 2140 ms. Copies on the same GPU wait for cudaFreeHost
either way; that comes from the driver and this change does not affect it.

The fix splits destroy_block(). detach_block() takes a block out of its pool
and updates the stats under the same locks as before, after which no other
thread can reach it. Each reclamation operation returns the blocks it
detached in a PendingHostFrees, a move-only batch that owns them, and the
caller frees them with its free() once no allocator lock is held:
reclaim_completed_blocks() in allocate() and the background thread,
cache_or_reclaim_block() in free(), and reclaim_default_pool_cache() and
reclaim_released_pools() in empty_cache(). All free_block() calls go through
PendingHostFrees, including blocks above pinned_max_cached_size_mb, which
maybe_cache_block() frees instead of caching. empty_cache() reaches that
path through process_events() under the exclusive instance_mutex_, so
process_events() and process_events_for_specific_size() take the batch as a
new parameter. A released pool is still erased only once it has no blocks,
and freeing a detached block does not touch its pool.

free() attempts every block, then rethrows the first error. An operation
constructs its batch before taking any lock, so if it throws, its locks are
released before the batch's destructor frees the blocks it holds; the
destructor ignores free errors, so the operation's own error propagates.

Since an address can now be handed out again before free_block() returns,
SEGMENT_FREE is recorded before free_block(), and the CUDA backend erases
the use_host_register entry before freeing instead of after, which could
drop the entry of a new allocation at the same address. An empty_cache()
racing with another one can now return before the blocks the other one took
are freed.

Freeing in maybe_cache_block() after it drops its own locks is not enough,
since empty_cache() calls it under the exclusive instance_mutex_; and
processing released pools without that lock would need another mutex or
reference-counted pools, to keep a concurrent empty_cache() from erasing
them.

Test Plan:

The new gtests use a mock backend and need no GPU. In four of them,
free_block() blocks until the test releases it, and record_event(),
allocate() and free() on another thread must still finish within 10 s. The
other two inject errors: when several frees fail, every block is still freed
and the first error is rethrown; when an event query fails after a block was
detached, that block is still freed and the query error wins over its
failing free. In a mock harness they fail without this change and pass with
it, also under ASAN+UBSan and TSAN. The only sanitizer reports are LSan's,
for the two blocks the allocator never frees after an injected event
failure. CI does not run this binary (aten/tools/run_tests.sh does not list
it).

On an A100, with this change on 0e5f6cd, the binary passes all 16 tests,
also with pinned_use_cuda_host_register, and the test_cuda.py selections
below pass (43 passed; 142 passed and 3 xfailed).

```bash
build/bin/cuda_caching_host_allocator_test
PYTORCH_ALLOC_CONF=pinned_use_cuda_host_register:True,pinned_num_register_threads:8 build/bin/cuda_caching_host_allocator_test
python -m pytest test/test_cuda.py -q -rfE -p no:cacheprovider -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
python -m pytest test/test_cuda.py -q -rfE -p no:cacheprovider -k "graph or Graph"
```

The comparisons with and without the change come from the previous revision
of this PR, on main a04f365, where the selections gave the same per-test
results with and without it. Two scripts (not in this PR) loop non_blocking
copies to cuda:1 on one thread while empty_cache() frees a cached 64 MiB
block, from the default pool or from a released CUDA graph pool, behind a
2.1 s kernel on cuda:0. On that revision, the longest copy enqueue took
2140 ms without the change in every run, and about 1 ms or less with it;
empty_cache() itself still takes about 2140 ms.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sujuyu
sujuyu force-pushed the host-alloc/empty-cache-unlocked-free branch from f6b362f to 0fb6f3b Compare November 17, 2026 06:12
@sujuyu
sujuyu marked this pull request as ready for review November 17, 2026 06:14
@github-actions
github-actions Bot requested a review from ngimel November 17, 2026 06:16
@github-actions github-actions Bot added bot-triaged This is a label only to be used by the auto triage bot triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels Nov 17, 2026
@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 17, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review of 0fb6f3b: nothing blocking; ready for human review.

The PR changes the host caching allocator so that free_block() (cudaFreeHost) runs after the allocator locks are released, by detaching blocks into a PendingHostFrees batch under the locks and freeing them afterwards. Recommendation: Needs Discussion. The open question is whether CUDA graph maintainers accept that frees from released graph pools no longer exclude a concurrent capture_begin. Every other point is non-blocking.

⚪ 8 non-blocking findings

PendingHostFrees reclaim_released_pools() {

Design decision needed: a concurrent capture_begin no longer waits for frees from released graph pools. Before, empty_cache() freed released-pool blocks while holding instance_mutex_ exclusively, and CUDAGraph::capture_begin takes that lock via begin_allocate_to_pool (CUDAGraph.cpp:244) before cudaStreamBeginCapture. Now reclaim_released_pools() drops the lock before .free() runs. Thread B can begin a global-mode capture while thread A is still running cudaFreeHost calls. A free issued during the capture is prohibited: AT_CUDA_CHECK throws on A, the remaining blocks' pinned memory leaks, and B's capture can be invalidated. Default-pool frees already had this gap; the PR extends it to released-pool blocks (the torch.cuda.graph _host_emptyCache() path). A shared lock won't work (no atomic downgrade). Fix option: a small dedicated mutex that empty_cache() holds while freeing released-pool blocks and that begin_allocate_to_pool takes first. CUDA graph maintainers should decide. If the gap is accepted, document it in code (e.g. the Note at :176-187), not only in the PR body.


PendingHostFrees& frees) {

Non-blocking BC: "BC-breaking? No" leaves two things out. (1) process_events and process_events_for_specific_size are virtual extension points that out-of-tree backends subclass, and they now take an extra PendingHostFrees& parameter. An override written without override still compiles but becomes a separate overload that is never called, so its behavior silently stops running. (2) The public method free_from_pool(BlockPool&) was removed (a caller is unlikely, since the pools are private). Mention both in the BC section and the release note. No in-tree backend is affected.


// If size is -1, process all events from backwards until the last unready

Non-blocking: doc comments don't describe the contracts that changed. free_block (:1208-1211) should say it can now run with no allocator lock, concurrently with other free_block calls on the same pool (before, these were serialized under blocks_mutex_), so a backend's per-pointer state needs its own lock, as the CUDA use_host_register change shows. The process_events* comment says nothing about the new frees parameter.


// allocator's internal cache. If another call runs concurrently, this one can

Non-blocking: the new HostAllocator::empty_cache() comment says it may return early only when another empty_cache() runs concurrently. It can also return before blocks are freed that a concurrent free() of a large block, an allocate(), or the background thread has already detached.


for (auto* block : std::exchange(blocks_, {})) {

Non-blocking: error handling in PendingHostFrees::free_blocks(). On the exception path, the destructor drops free errors without logging, so leaked pinned memory leaves no trace (drain_deferred_custom_frees_noexcept in c10/cuda/CUDACachingAllocator.cpp uses LOG(ERROR)). Also, record_trace() is in the same try as free_block(). If it throws (the ring-buffer insert allocates when history recording is on), free_block() is skipped but delete block still runs, which leaks pinned memory and breaks the "attempt every block" guarantee. Give record_trace its own try.


Non-blocking: the new private:/public: pair (:620, :688) splits the public section, though the file already has a private helper section at :779 holding maybe_cache_block and detach_block. cache_or_reclaim_block and reclaim_default_pool_cache are each used once and could be inlined. std::exchange (:335, :359) needs <utility>, which is only included transitively.


Non-blocking: none of the six new tests run in CI. cuda_caching_host_allocator_test is built only from ATen_CUDA_TEST_SRCS and isn't listed in aten/tools/run_tests.sh, so the lock-freedom and error-propagation guarantees have no regression coverage. Add run_if_exists cuda_caching_host_allocator_test. Better, since the mock tests need no GPU, move them into a CPU test binary that the ASAN/TSAN jobs build. Fix this first: empty_cache_frees_detached_blocks_on_query_error deliberately leaves a block allocated (EXPECT_EQ(allocator.live, 1)), and since the allocator destructor frees nothing, LSan would fail the binary under ASAN. It needs a suppression or a mock that cleans up its own allocations.


struct MockAllocator : at::CachingHostAllocatorImpl<TestStream, TestEvent> {

Non-blocking: MockAllocator repeats the malloc/free overrides of the existing ThrowingRecordAllocator. ThrowingRecordAllocator could derive from it.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

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

ngimel commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Looks good, small comment
Tracing must not prevent physical freeing. In PendingHostFrees::free_blocks(), record_trace() and free_block() share a try. Trace insertion can allocate and throw; that skips the backend free, but delete block still runs, losing the pinned allocation's tracking. Separate the error handling so the backend free is always attempted.

@galv

galv commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

This is true:

Non-blocking BC: "BC-breaking? No" leaves two things out. (1) process_events and process_events_for_specific_size are virtual extension points that out-of-tree backends subclass, and they now take an extra PendingHostFrees& parameter. An override written without override still compiles but becomes a separate overload that is never called, so its behavior silently stops running. (2) The public method free_from_pool(BlockPool&) was removed (a caller is unlikely, since the pools are private). Mention both in the BC section and the release note. No in-tree backend is affected.

However, I don't think it's a good policy to maintain developer-internal interfaces forever on the basis that it will break out-of-tree backends. I encountered that problem before, and there are situations like this one where such a restriction is not tenable. So there is no need for any changes here.

A place where backwards compatibility could break: It's now possible for a cudaHostAlloc() call in thread A that could free will now fail because pending cudaFreeHost() calls in thread B are no longer waited on by thread A. This is really because of your PR, which is what makes this a bit difficult to deal with. You could consider having allocation include a retry path where it sleeps on a std::condition_variable until all outstanding frees are done in case it does encounter an OOM. I'm not sure how intrusive this is. I'm also not sure how much of a problem this is in practice. As you are well aware, most users in pytorch these days assign a single GPU to each process. So it's not something I feel super strongly about. I suppose we can have multiple data loader threads that allocate pinned host memory. If someone uses this feature, then they won't be caching pinned host memory blocks. This means data loader threads will be constantly calling cudaHostAlloc() and cudaFreeHost(), and thus they are vulnerable to failing if your PR merged in its current state in a regime where CPU memory is tight. However, I doubt that that feature is commonly used anyway. Regardless, I would err on the side of making my suggested change if it is a small change.

Regarding the cuda graph capture issue, I believe it is a non-issue. The cudaFreeHost() call is wrapped properly in your next PR: https://github.com/pytorch/pytorch/pull/200762/changes#diff-5d3beb56bf9b6f380f91d5f6f063480ce2e14ca15c415d59d153436018089223R139

Nonetheless, for the sake of an atomically complete PR, I recommend moving that line of code here. I haven't read your second PR at the time of writing, so let me know if I am missing something.

sujuyu and others added 3 commits November 18, 2026 11:10
…ace fails

PendingHostFrees::free_blocks() called record_trace() and free_block() in
one try. With memory history recording on, record_trace() inserts into a
ring buffer, which can allocate and throw. free_block() was then skipped
while `delete block` still ran, so the pinned allocation was lost. Main
recorded SEGMENT_FREE after the free, so a failed trace could not skip it;
this PR records it before the free, because the address can be handed out
again as soon as free_block() returns.

Each call now has its own try. Every block is still attempted, and the first
error is still rethrown.

Test Plan:

No new test: record_trace() fails only when the ring buffer cannot
allocate, and it is not virtual, so a test cannot inject that failure
without a new hook. The existing gtests, which cover failing frees, pass
(results with the next two commits on top, on an A100):

```bash
build/bin/cuda_caching_host_allocator_test
PYTORCH_ALLOC_CONF=pinned_use_cuda_host_register:True,pinned_num_register_threads:8 build/bin/cuda_caching_host_allocator_test
```

Authored with assistance from Claude Code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This PR frees detached blocks after the allocator locks are released, so a
capture that another thread begins no longer waits for the frees of
released graph pools, which used to run under the exclusive instance_mutex_
that capture_begin() takes. Default-pool frees already had this gap. Global
capture mode, the torch.cuda.graph default, forbids cudaFreeHost and
cudaHostUnregister on every thread, so such a free failed with
cudaErrorStreamCaptureUnsupported and invalidated the capture.

free_block() now runs them in relaxed capture mode. The line is copied
verbatim from Kapil Sharma's e9c03c4 in pytorch#200762, so that pytorch#200762
restacks cleanly. The guard switches only the freeing thread. A guard
conditioned on the current stream capturing, like the one around
cudaHostAlloc, would not help, since the freeing thread is not the one
capturing. Event queries in empty_cache() still run in the thread's own
mode, as on main.

Test Plan:

test_free_during_global_capture_on_other_thread frees a cached block from
another thread while the main thread captures in global mode, in both
pinned_use_cuda_host_register modes. On an A100, both cases fail without the
new line (cudaErrorStreamCaptureUnsupported in the worker, then
cudaErrorStreamCaptureInvalidated at the end of the capture) and pass with
it.

```bash
python test/test_cuda.py TestCachingHostAllocatorCudaGraph.test_free_during_global_capture_on_other_thread_use_cuda_host_register_False TestCachingHostAllocatorCudaGraph.test_free_during_global_capture_on_other_thread_use_cuda_host_register_True
```

Authored with assistance from Claude Code.

Co-authored-by: Kapil Sharma <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Before this PR, free_block() ran under the pool locks. An allocation on
another thread that needed those locks (the same size bucket, its own
reclaim, or instance_mutex_ while a capture is registered) waited for the
free to finish before it called cudaHostAlloc. Now it does not, so when CPU
memory is tight it can fail where it used to succeed, for example with
pinned_max_cached_size_mb set and several threads allocating and freeing
large blocks. The old wait came from lock collisions and depended on
timing. This restores it only where it matters, when the allocation fails.

frees_started_ counts the blocks added to a PendingHostFrees, and
frees_finished_ the blocks whose free was attempted, failed or not. When
allocate_host_memory() throws, allocate() rethrows if no free was in flight
around the attempt (frees_started_ read after the failure equals
frees_finished_ read before it). Otherwise it waits until frees_finished_
reaches that frees_started_, then retries once.

Frees can finish out of order, so the retry can come before the free it
needed, and the error then propagates as before. Waiting until nothing is in
flight would be exact, but it could wait indefinitely while other threads
keep freeing. Tracking each batch would be exact without that problem, but
it needs more code than a best-effort retry deserves.

The wait holds no allocator lock. A thread's own reclaimed blocks are freed
before it allocates, and frees need no allocator lock or GIL. frees_mutex_
is never held together with another lock. Empty batches return before
taking it, so allocate() and free() pay nothing extra unless they free
blocks. Generic code cannot tell an out-of-memory error from other errors,
so any c10::Error is retried once if frees were in flight.

With pinned_use_cuda_host_register, a failed cudaHostRegister already leaks
its malloc'd buffer on main; the retry can make that happen twice. That is
left for a separate change.

Test Plan:

Two new mock gtests, which need no GPU:

- An allocation fails while another thread's free_block() is blocked. It
  waits for that free and then succeeds, and the mock checks that the retry
  came after the free.
- With no free in flight, the error is rethrown without a retry.

On an A100, the binary passes all 18 tests, also with
pinned_use_cuda_host_register, and the two new ones pass five times in a
row.

```bash
build/bin/cuda_caching_host_allocator_test
PYTORCH_ALLOC_CONF=pinned_use_cuda_host_register:True,pinned_num_register_threads:8 build/bin/cuda_caching_host_allocator_test
build/bin/cuda_caching_host_allocator_test --gtest_filter='*frees_in_flight*'
```

CI does not run this binary (aten/tools/run_tests.sh does not list it).

Authored with assistance from Claude Code.

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

sujuyu commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel Fixed in d04cd3d. Split the try blocks — trace failure no longer skips the free. Still rethrows the first error after all blocks are tried.

@sujuyu

sujuyu commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@galv Thanks.

Relaxed free: moved the guard here in 174a420 (originally @kapilsh's from #200762). It's unconditional since the freeing thread isn't capturing. Added a test for this.

OOM: retry added in 7f7c97f. Previously it only waited on lock contention, which was timing-dependent. Now, if allocate_host_memory() throws with frees in flight, allocate() waits for that many frees to finish, then retries once. Re-throws immediately if none are in flight. Best-effort since frees can finish out of order. Two mock gtests cover it.

BC: agreed, no change.

@eqy
eqy requested a review from galv November 18, 2026 20:51
@sujuyu

sujuyu commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel Merged main for CI. Please re-approve the workflows.

@sujuyu

sujuyu commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 19, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (openreg, 1, 1, macos-m1-stable). Blocking jobs that the merge waited on for a Dr.CI or AI CI Advisor classification: 1.

Details for Dev Infra team

Raised by workflow job

@ngimel

ngimel commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

@claude is test failure related?

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

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


No, the failure isn't related to this PR. It's an infra/flaky timeout, so re-running the job or merging with -i should be fine.

Details

What failed: trunk / macos-py3-arm64 / test (openreg, 1, 1, macos-m1-stable) did not report any failing test. The step hit the 240-minute limit (##[error]The action 'Test' has timed out after 240 minutes).

  • Running test_openreg 1/1 started at 12:19:59.
  • The OpenReg C++ gtests finished at 12:20:16 with [ PASSED ] 47 tests.
  • The last line printed is a skipIfMPS UserWarning from torch_openreg/tests/test_autograd.py (12:20:19). After that there is no output until the timeout at 16:19:49. No traceback, crash or error message was printed.

Why the PR can't have caused it:

  • OpenReg's host allocator (test/cpp_extensions/open_registration_extension/torch_openreg/csrc/runtime/OpenRegHostAllocator.h:11) is struct OpenRegHostAllocator final : at::HostAllocator. It inherits from the abstract at::HostAllocator interface and does not use CachingHostAllocatorImpl.
  • Nearly all of the PR's changes are inside CachingHostAllocatorImpl (PendingHostFrees, detach/reclaim, the free counters and condition variable). The rest are in the CUDA backend and CUDA tests.
  • The PR's only edit to at::HostAllocator is the doc comment on empty_cache(). No signatures or virtual methods change.
  • So none of the changed runtime code runs on a macOS openreg job. Dr. CI also reports that the same job passes in about 5 minutes on the merge base and on nearby trunk commits.

@ngimel

ngimel commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: trunk / macos-py3-arm64 / test (openreg, 1, 1, macos-m1-stable)

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 added a commit to sujuyu/pytorch that referenced this pull request Nov 20, 2026
…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]>
sujuyu added a commit to sujuyu/pytorch that referenced this pull request Nov 20, 2026
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]>
@sujuyu
sujuyu deleted the host-alloc/empty-cache-unlocked-free branch November 20, 2026 01:26
pytorchmergebot pushed a commit to sujuyu/pytorch that referenced this pull request Nov 25, 2026
…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]>
pytorchmergebot pushed a commit to sujuyu/pytorch that referenced this pull request Nov 25, 2026
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 pushed a commit that referenced this pull request Nov 25, 2026
…00762)

- [x] Passes lint (`spin fixlint`)
- [x] Added/updated tests
- [x] Updated documentation (if applicable)
- [x] 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 (sujuyu#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 #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 (#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.

<details>
<summary>Design, alternatives, and test plan</summary>

```python
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.

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Pull Request resolved: #200762
Approved by: https://github.com/kapilsh

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Kapil Sharma <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triaged This is a label only to be used by the auto triage bot ciflow/trunk Trigger trunk jobs on your pull request Merged open source ready for review Automated review passed, ready for a final review by a maintainer. release notes: cuda release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants