Skip to content

Partition the pinned host allocator's free lists by NUMA node behind an opt-in flag - #197868

Closed
sujuyu wants to merge 3 commits into
pytorch:mainfrom
sujuyu:split/numa-pools
Closed

sujuyu wants to merge 3 commits into
pytorch:mainfrom
sujuyu:split/numa-pools

Conversation

@sujuyu

@sujuyu sujuyu commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Related to #160420.

In that issue @galv asked for a use case where NUMA affinity in the pinned
allocator actually matters. Here is one, with measurements.

This addresses the reuse problem in that issue's title rather than the
cuMemCreate / CU_MEM_LOCATION_TYPE_HOST_NUMA mechanism proposed in its body,
so I have not marked the issue as fixed — that call is @galv's to make.

The setup

One inference process drives 6 A100s on a dual-socket AMD EPYC 7H12: GPUs 0-3
hang off NUMA node 0, GPUs 4-5 off node 1. Each GPU loads several hundred MB to
a few GB of constants through pinned staging buffers. The loader threads are
bound to the node of the GPU they serve.

The node-1 loaders are consistently ~30% slower than the node-0 loaders, and
they have the least contention
— one loader on node 1 versus two on node 0,
doing identical work:

concurrent loaders median prepare max
node 0 (cuda:0-3) 2 1065 ms 1388 ms
node 1 (cuda:4/5) 1 1389 ms 2067 ms

Why binding does not fix it

The binding is correct. The cache defeats it.

I pre-warm the pinned cache from a thread bound to each node, then read the
actual page placement from /proc/self/numa_maps:

node0 prewarm, 12 x 64MiB:  494.80 ms   pages all on N0 (196608 pages = 768 MiB)
node1 prewarm, 12 x 64MiB:    0.15 ms   pages still all on N0   <- nothing allocated

Node 1 allocates nothing: node 0's freed blocks are an exact size-bucket match,
so the slow path is never reached and cudaHostAlloc -- which would have placed
the pages on the calling thread's node -- is never called.

This is the part I would emphasise: node 1 does not sometimes get remote
memory, it gets remote memory every time. No amount of CPU or memory binding
changes that, because no allocation ever happens on node 1 to bind. On this host
a cross-node host-to-host copy runs at 36.8 GiB/s against 116.8 GiB/s local, so
every staged copy through such a block pays 3.2x, plus a second penalty on the
H2D DMA that I have not isolated.

Scope, to be precise: the general statement is about the allocator -- a
node-blind cache in front of it means correct binding does not imply local
memory. Under one process per GPU that never manifests, exactly as the comment
in CachingHostAllocator.cpp says, and I am not claiming otherwise. What my
deployment supplies is a case where it does: one process whose threads span two
nodes and share one cache. torch/numa/binding.py cannot help there -- it emits
numactl --physcpubind with no --membind and is organised local-rank ->
device-index, i.e. built around one process per GPU.

I am aware of #185417 and that it was closed. That patch proposed placement
policy
via set_mempolicy, which does overlap what torchrun already does.
This change does not do placement policy -- it partitions the reuse structure,
which no launcher-level binding can reach.

The change

Keep one free list per NUMA node in CachingHostAllocator, behind an opt-in
pinned_numa_aware allocator setting. Off by default.

  • An allocation is served from the pool of the node the calling thread runs
    on. No change to Allocator::allocate() — the interface stays device-agnostic
    and callers need no modification.
  • A free returns the block to the pool it came from, recorded on the block at
    allocation time, not to the pool of the freeing thread's node. Otherwise
    blocks drift to whichever node frees most often and the partition decays.
    Note this is the allocating pool's node: with default first-touch it is also
    where the pages are, but an explicit mempolicy or the host_register path can
    break that, which is why those combinations are rejected.
  • Partitioning, not filtering: default_pools_[node] is a direct index, so the
    size-bucket lookup after it is byte-for-byte what it is today. The added work on
    the allocation path is one GetCurrentNUMANode(), measured here at 563 ns --
    sched_getcpu() is 8 ns through the vDSO, but numa_node_of_cpu() walks the
    per-node cpumasks and costs the rest. That is 46x the uncontended mutex
    acquisition already on this path, so it is not free, though it is invisible next
    to the work it guards: a 64 MiB staging copy is milliseconds. A workload doing
    many small pinned allocations would notice. A thread_local cache brings it to
    2.4 ns and is safe -- a bound loader thread does not migrate, and a thread that
    did would only lose locality for itself, since a block's pool is recorded at
    creation and free routing does not consult the calling thread. I have not done
    it here: it is a separate concern from the partitioning and I would rather land
    the structure first. Say the word and I will add it.
    The free path adds a field read.
  • No cross-node fallback when the local pool is empty. Falling back would
    preserve exactly the "sometimes fast, sometimes slow, no visible reason"
    behaviour that took me a full day to track down. A fresh 64 MiB pinned
    allocation is ~40 ms, paid once per node per size bucket.
  • Pool count is numa_max_node() + 1, not the number of nodes, because node ids
    can be sparse.

This builds directly on #167507, which already introduced MempoolId_t-keyed
private host pools — the partitioning machinery exists, this adds one dimension
to it.

Opt-in because of memory, not speed. Each node keeps its own free list, so
the same sizes may be held more than once; how much is duplicated depends on how
many nodes actually allocate and on how the work is spread. Here it is one extra
copy, 768 MiB cached instead of 384 MiB. pinned_max_cached_size_mb limits the
effect for large allocations — a block above that size is freed rather than
cached — but it is a per-block threshold, not a cap on the total.

Behaviour when the flag is unset

The allocator keeps a single pool and the allocate/free fast paths are
unchanged.

Two qualifications, because I would rather state them than have them found.

Allocate and free now also run an initialization check, which is one acquire load
once the pools are built. And the second commit changes the c10 NUMA topology
queries for every caller, not only for this flag: GetNumNUMANodes(),
GetNUMANode() and GetCurrentNUMANode() used to be gated on
FLAGS_caffe2_cpu_numa_enabled and are now gated on NUMA being available. That is
a deliberate widening -- the previous gate conflated "may we move pages" with "may
we ask what the topology is" -- but it is a behaviour change outside this feature.

The one intentional behaviour change in the allocator is independent of the flag:
the first commit fixes per-bucket allocator statistics being shared across pools.
HostStatsStaged held the per-bucket vectors in a single instance while the
comment stated they were protected by pool.free_list_[index].mutex_ — different
pools, different mutexes, same counters. #167507's private pools can already
trigger this today; N concurrent per-node pools would make it routine.

Known limitations

Per-bucket peak is now summed across pools, so it over-reports. Before the
first commit the bucket counters lived in one shared vector and peak was exact.
They now live per pool and getStats sums them, so two pools that never peak at
the same moment still add up. The existing code already sums peaks across buckets
and documents that as an approximation; this adds a second dimension to the same
approximation. Blocks retired from a destroyed pool take the max rather than the
sum, so it cannot grow without bound, but it is not exact.

The clean fix is the other shape: leave the counters shared and give them their
own per-bucket locks, rather than moving them into the pools. That is a smaller
change than what is here and it keeps peak exact. I did not do it because it
decides how these counters should be structured as more pool kinds are added, and
that call belongs to whoever maintains this file. Say the word and I will redo the
first commit that way.

Enabling the flag makes 11 existing tests in TestCachingHostAllocatorCudaGraph
fail.
They go through a helper that sets
pinned_use_cuda_host_register:True,pinned_num_register_threads:8, which is
exactly the combination the compatibility check rejects. Default-off means CI is
unaffected, but anyone who turns the flag on process-wide and runs test_cuda.py
will see them. Rejecting loudly rather than silently degrading to a single pool
was a deliberate choice -- degrading silently reproduces the "sometimes fast, no
visible reason" behaviour this exists to remove -- but the friction is real and I
am happy to be told the other way is preferred.

Commits

  1. Fix per-bucket host allocator stats being shared across pools
  2. Gate the c10 NUMA topology queries on availability, not on the placement flag
  3. Keep one pinned host free list per NUMA node behind an opt-in flag

(1) and (2) stand on their own; happy to split them into separate PRs if that is
easier to land.

Validation

Built and tested on the host above. With the flag off, a node-1 allocation takes
0.19 ms, triggers 0 fresh cudaHostAlloc calls, and lands 0/65536 pages on the
local node. With it on: 116.50 ms, 4 fresh allocations, 65536/65536 pages local.

New tests in test/test_cuda.py, all subprocess-isolated because the setting
latches at the first pinned request. Being straight about what they cover: I
checked them by emulating the feature away -- forcing numa_max_node() to 0 so
the allocator keeps one pool while parsing, validation and latching still run --
and only test_free_routes_by_block_node_not_by_freeing_thread fails under that.
The other seven constrain the preconditions and the two repaired failure modes,
not the partitioning. Not covered: genuine single-node pool construction, sparse
node ids, the out-of-range fallback, and the rollback path when pool setup throws.


Disclosure per AI_POLICY.md: the measurements above are mine. I used AI
assistance to organise them into this description and to review the
implementation, and I have read and verified the code and the numbers myself.

sujuyu and others added 3 commits September 21, 2026 16:24
HostStatsStaged holds four per-bucket Stat vectors documented as protected by
pool.free_list_[i].mutex_. That mutex is per pool, so two pools at the same
bucket index take different locks while mutating the same counters: a graph
private pool and the default pool race on every shared index, which is a lost
update and undefined behaviour rather than merely an inaccurate number.

The same applies to the two process-wide counters, allocations and
allocated_bytes: they are written under whichever pool's blocks_mutex_ owns the
allocation and read under the default pool's, so they race for the same reason.

Move the per-bucket vectors into HostBlockPool, next to the free list whose
mutex already guards them, and give the two process-wide counters their own
mutex. Correctness then no longer rests on there being exactly one pool, and
the locking discipline is visible at the point of use rather than in a comment.

getStats, resetAccumulatedStats and resetPeakStats now walk the private pools
as well as the default one, so graph-pool activity keeps contributing to the
reported totals as it did while the counters were shared.

Hard to hit today, since private pools only exist during graph capture. Worth
fixing on its own terms, and a prerequisite for anything that adds a second
long-lived pool.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ent flag

GetNUMANode, GetNumNUMANodes and GetCurrentNUMANode all return -1 unless
FLAGS_caffe2_cpu_numa_enabled is set. That flag is an opt-in to NUMA
*placement*; asking which node a thread is running on, or how many nodes exist,
is a question about the machine and should not require opting into anything.
Gate the queries on whether the platform has a usable NUMA API instead, and
leave the flag on the functions that act: NUMABind and NUMAMove.

Add IsNUMAAvailable() for that, and GetNUMANodeIdUpperBound(), which is
numa_max_node() + 1. Callers sizing an array indexed by node id need the id
space, not the node count: ids can be sparse, and a machine with nodes 0 and 2
and nothing at 1 reports two configured nodes while handing out id 2.

The one existing caller keeps its old behaviour. alloc_cpu passes the node as
an argument to NUMAMove, so it is evaluated before NUMAMove can return early;
relaxing the query would have added numa_available(), sched_getcpu() and
numa_node_of_cpu() to every pageable CPU allocation for nothing. It now calls
GetCurrentNUMANodeIfEnabled(), which short-circuits on the flag exactly as
before.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
CachingHostAllocator keys its free list by size only, so a block freed by a
thread on one NUMA node is handed straight to a thread on another. Pinned pages
are mlock'd and cannot migrate, so every copy through that block then crosses
the interconnect, in both directions: the host-to-host copy filling the buffer
and the H2D DMA draining it to a GPU whose root complex sits on the other node.

The comment in cuda/CachingHostAllocator.cpp notes this and dismisses it because
"we use one process per GPU". That does not hold for a process driving several
GPUs across nodes. On a 6x A100 host with GPUs 0-3 on node 0 and 4-5 on node 1,
node-1 loaders ran 30% slower than node-0 loaders while having the least
concurrency, and a same-node host-to-host copy measured 116 GiB/s against
36 GiB/s cross-node. Pre-warming each node separately does not help: the second
node's request is served from the first node's freed blocks and never reaches
the slow path. Measured with pinned_numa_aware off, a node-1 thread got 0 of
65536 pages local and its "allocation" took 0.09 ms with zero calls to
cudaHostAlloc, which is a cache hit rather than a fast allocation. With the flag
on, the same thread got 65536 of 65536 pages local.

Split the default pool per node. A block records the node of the pool it was
registered in, never a fresh sample of the calling thread, so a thread that
migrates mid-allocation cannot register a block in one pool and free it into
another. Freeing routes on that recorded node rather than on the freeing
thread's node, so the split does not decay. The node is read from the calling
thread only when picking a pool, so no caller and no allocator signature
changes; threads are already bound in the deployments where this matters. No
placement work is needed either: cudaHostAlloc already places pages on the
calling thread's node, so recording the node at allocation is enough.

Pools are sized by the host's highest node id, not by how many nodes the task
may use. CPU and node ids are host-global -- a cpuset restricts which CPUs a
thread may run on, it does not renumber them -- so a container confined to
node 1 reports one usable node while its threads still see node id 1. Sizing by
the task's node count would leave that container with a single pool and clamp
every thread onto it. An unused node costs one empty HostBlockPool, about 16 KB
and no pinned memory.

Off by default via PYTORCH_ALLOC_CONF=pinned_numa_aware:True. The reason is
memory rather than performance: the cache footprint becomes
nodes x per-node working set. With the flag off the node index folds to a
constant and the code path is unchanged.

Three ways the setting can be wrong are reported rather than absorbed:

- Requesting it on a build without usable NUMA support fails, instead of
  silently behaving like a single node.
- Requesting it alongside an allocation mode that decides placement somewhere
  other than the calling thread fails: the process-wide reserve segment, or
  cudaHostRegister with more than one pre-fault thread. Backends declare that
  through numa_placement_untrustworthy_reason().
- The clamp in current_numa_node() warns once when taken. It stays because it
  is reachable for reasons the sizing cannot fix, such as the query failing or
  a node hot-added after the pools were sized, but falling back to pool 0
  silently would recreate exactly the invisible failure this flag exists to
  remove.

The setting is read once, at first use, and cannot be changed afterwards;
trying is an error rather than a silent no-op.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⚠️ 5 Awaiting Approval

As of commit 5b894f4 with merge base b6131af (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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

@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@sujuyu

sujuyu commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

@galv this is the use case you asked for in #160420, with the measurements. It
also builds directly on your #167507 — the per-pool partitioning machinery is
already there, this adds a node dimension to it.

@ngimel @eqy you reviewed #167507 and #183067, so you have the most context on
this allocator. I have flagged two things in the description that I would rather
have challenged early than discovered later: per-bucket peak is now summed
across pools and therefore over-reports, and enabling the flag makes 11 existing
tests in TestCachingHostAllocatorCudaGraph fail because they use a setting
combination the compatibility check rejects. Both have a cheaper alternative
shape that I did not take unilaterally because it is your call.

@ezyang ezyang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Sep 21, 2026
@ngimel

ngimel commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

What's preventing you from running process per GPU or process per NUMA node?

@sujuyu

sujuyu commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Nothing categorically prevents it. Process per NUMA node would avoid the allocator problem, but it would require either duplicating the CPU feature computation, which is already the bottleneck, or adding IPC to the latency-critical path. The service computes dense features on CPU once per tick and feeds all six GPUs from that one result; in a single process that is a pointer hand-off.

Process per GPU multiplies the same cost by six. It also changes model swapping: we cycle models in and out while the service keeps serving, and with N processes each swap needs cross-process agreement. Without that coordination, a tick can be served by a mix of old and new models.

So the split is possible; we would just be taking on that work to accommodate the allocator's NUMA assumption.

On the allocator itself, I don't think one process per GPU is wrong, and the comment in CachingHostAllocator.cpp is honest about the assumption it relies on. What I would flag is that a process whose threads span two nodes gets remote pinned memory every time, not sometimes: the node-1 thread always finds a node-0 block on the free list, so the slow path that would call cudaHostAlloc never runs. There is no warning and no counter for it, and PyTorch supports single-process multi-GPU broadly. @galv opened #160420 asking for this case.

The pooling is opt-in and off by default (pinned_numa_aware_{false}); with the flag off the allocator takes the same path it does today. The first commit is independent of the flag, though. It fixes a data race: the per-bucket stat vectors are documented as protected by free_list_[i].mutex_, but that mutex is per pool, so a CUDA graph private pool and the default pool mutate the same counters under different locks. Happy to land that one separately if you would rather review it on its own.

@sujuyu

sujuyu commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

Correction to a number in the description, before anyone spends time on it.

I wrote that the added work on the allocation path is sched_getcpu() at 5.56 ns,
less than half the uncontended mutex already on that path. That is wrong. I had
benchmarked only sched_getcpu(), not the function the code actually calls.
GetCurrentNUMANode() is numa_node_of_cpu(sched_getcpu()), and on this host:

sched_getcpu()                       8.47 ns
numa_node_of_cpu(cpu)              562.02 ns
GetCurrentNUMANode() together      563.34 ns

numa_node_of_cpu() walks the per-node cpumasks; strace shows 9 syscalls per
1000 calls, so this is CPU work, not I/O. So the real figure is 563 ns, about
46x the mutex
, not half of it. I have corrected the description.

It stays invisible for the workload this is aimed at -- a 64 MiB staging copy is
milliseconds, and the call happens once per allocation, not per byte -- but it is
not the free lookup I claimed, and a workload doing many small pinned allocations
would pay it. A thread_local cache takes it to 2.4 ns, and is safe because a
block's pool is recorded at creation, so a thread that migrated would lose its own
locality but could not corrupt the partition. I have deliberately not added it to
this PR: it is a separate concern and I would rather land the structure first, but
I am happy to include it if you would prefer it in one go.


Disclosure per AI_POLICY.md: the measurements are mine; I used AI assistance to
prepare this comment and have verified the numbers myself.

@albanD

albanD commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the careful explanation and presentation of the concerns @sujuyu
To be fully transparent, I think the main concern here is the tradeoff of complexity with how broadly usage it is for our end users.

I would be amenable to reviewing this but I am not sure how to thing about this new system along the existing (pretty weird) "per stream" and all the new locking required.

@ngimel

ngimel commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

I think you want a more generic functionality here, like beginAllocateToPool in cudaCachingAllocator, with your filter function sending threads from the same numa node to the same pool, instead of hardcoding just this particular filter in the host allocator. Having mempool-like functionality for host allocator would be pretty good, and we are half way there already with pools for cudagraphs for the pinned allocator.

@sujuyu

sujuyu commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, that makes sense: a generic host pool keeps NUMA policy out of the pinned allocator. I prototyped a host version of use_mem_pool. The summary below was drafted with Claude Code and checked against the code and the prototype; the numbered points are where I need your call.

Proposal. torch.cuda.HostMemPool and torch.cuda.use_host_mem_pool(pool), which routes the current thread's pinned allocations to pool, and unlike today's host graph pools is not tied to capture. use_mem_pool keeps leaving pinned memory alone, for the reason given in #167507. For NUMA, each loader thread enters its node's pool; the allocator knows nothing about nodes.

Points that need your call:

  1. Several threads may be in the same pool at once, and a thread may re-enter a pool it is already in. A pool per NUMA node needs the first; the device rejects both ("already recording to mempool_id"). OK?
  2. Graph capture routing wins over the thread's pool whatever the entry order, where on the device the innermost scope wins. Pinned blocks used during capture are never recycled, so letting them land in a user pool would keep that pool alive for good. With this rule a graph never retains a user host pool and CUDAGraph.cpp is untouched. OK?
  3. torch.cuda.graph(g, pool=hp.id): an eagerly used host pool can have pending events, and draining them during capture calls cudaEventQuery on the capturing thread. Either (a) reject such ids for now, or (b) skip that drain while the stream is capturing, as the device does in prepare_for_malloc, which would also let warmup and capture share a host pool as you asked about in Make CachingHostAllocator work with memory pools. #167507. I'd start with (a); do you want (b)?
  4. A HostMemPool's cached blocks are freed by the next empty_cache() after the object is gone; a live pool is never flushed. empty_cache(pool) now or as a follow-up?

Why thread_local rather than a filter in captures_underway_. On the device the filter runs under the mutex malloc already holds, with the stream passed in; on the host both would be new. While any filter route exists, every pinned allocation in the process takes instance_mutex_ and queries the current stream and its capture state: about 1.7 µs per allocate+free instead of 110 ns on an A100 host, and 8 µs against 0.7 µs with 4 threads. A thread_local route adds neither outside capture, and behind a relaxed flag next to captures_underway_empty_ a process with no host pools pays one extra relaxed load. Routed threads still drain their own pool's events inline; the background thread keeps serving only the default pool.

Existing bugs to fix first, as small separate PRs: the per-bucket stats race (the first commit here); a self-deadlock in empty_cache() on a released private pool with completed events ("Resource deadlock avoided"), fixed by storing the pool pointer on the block and checking blocks_.empty() under blocks_mutex_; and a use_count > 0 assert when re-capturing into a reset graph_pool_handle() whose earlier capture used a pinned buffer on a stream (reproduced on an A100).

The mock-backend prototype of the header changes passes its routing, lifetime and nesting tests with no TSAN or ASAN reports in the allocator; the Python side, the flag and 3(a) are not written yet. If this direction works for you, I'll close this PR and send the prerequisites first.

@sujuyu

sujuyu commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel I'm prototyping the generic host mempool as you suggested, and along the way I found two issues and sent a fix for each: #199144 fixes a race on the stat counters that multiple pools share, and #199145 fixes empty_cache() taking the same lock twice for private pools. Both changes are fairly small and don't depend on how the questions above are settled, so they can be reviewed first. Once those questions are settled, I'll open the host mempool PR and close this one.

pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
While prototyping the generic host mempool that ngimel suggested in #197868, I found that all pools share one set of stat counters, but each pool updates them under its own locks. In our multi-GPU inference setup the pools are split by NUMA node, and several threads use different pools at the same time, so these counters can lose updates and also become a point of contention between threads. This fix can be merged independently of the interface design that is still open in #197868. I have reviewed the change, and the tests have been run on an A100.

The change gives each pool its own per-bucket stats, guarded by the free-list locks it already takes. The global allocations and allocated_bytes counters get a separate lock that is only taken when a block is created or destroyed, so the allocate and free paths that hit the cache need no extra locking. getStats() adds up the stats of all pools. When private pools are in use, the active peaks, which were already an estimate, can be higher than before; allocations and allocated_bytes stay exact.

The technical summary below was drafted with Claude, and I checked it against the code.

<details>
<summary>Technical details and test plan (drafted with Claude)</summary>

> Since #167507 added host private pools, the default pool and a private pool
> update the same HostStatsStaged counters. Each pool guards them with its own
> mutexes, the bucket stats with free_list_[i].mutex_ and allocations and
> allocated_bytes with blocks_mutex_, so updates from two pools race. For
> example, pinned allocations into a graph's private pool during capture can
> race with a DataLoader pin_memory thread and lose updates. In debug builds,
> free() can then fail the current >= 0 assert in Stat::decrease.
>
> Move the bucket stats into HostBlockPool, next to the free-list mutexes that
> already guard them, and give allocations and allocated_bytes their own
> mutex. Those two only change when a block is created or destroyed, so the
> cached allocate and free paths take no new lock. getStats() and the reset
> functions now walk every pool. When empty_cache() erases a private pool, it
> adds that pool's bucket stats to default_pool_'s, so the totals don't drop.
>
> A single stats mutex would also fix the race, but it would add a global lock
> to every cached allocate and free. Atomic counters would keep every pool
> writing the same cache lines.
>
> getStats() already estimates the total peak by summing per-bucket peaks. It
> now also sums per-pool peaks, and an erased pool's peaks stay counted until
> reset_peak_host_memory_stats(). So with private pools in use, the reported
> active_requests and active_bytes peaks can be higher than before, and can
> grow with each erased pool. allocations and allocated_bytes stay exact.
>
> Test Plan:
>
> ```bash
> python -m pip install -e . -v --no-build-isolation
> build/bin/cuda_caching_host_allocator_test --gtest_filter='CachingHostAllocatorTest.*'
> f=0
> for i in $(seq 1 20); do
>   build/bin/cuda_caching_host_allocator_test \
>     --gtest_filter=CachingHostAllocatorTest.stats_concurrent_pools >/dev/null 2>&1 || f=$((f+1))
> done
> echo "failed $f of 20"
> python -m pytest test/test_cuda.py \
>   -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
> ```
>
> All 10 gtests pass, and stats_concurrent_pools passes 20 of 20 runs. The
> pytest set gives 41 passed and 3 skipped, all disabled upstream. With the
> header reverted to 2a20f3e, stats_concurrent_pools fails 20 of 20 runs
> with lost counts. It is a stress test, so a run could pass by chance.
> stats_include_private_pools passes there as well, since it checks the
> summing across pools and not the race. No test covers the allocations and
> allocated_bytes half, because the cached path creates at most one block per
> pool. CI does not run cuda_caching_host_allocator_test, so the gtests were
> run locally.
>
> This change was prepared with assistance from Claude, an AI assistant.

</details>

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

Pull Request resolved: #199144
Approved by: https://github.com/ngimel

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…h#199144)

While prototyping the generic host mempool that ngimel suggested in pytorch#197868, I found that all pools share one set of stat counters, but each pool updates them under its own locks. In our multi-GPU inference setup the pools are split by NUMA node, and several threads use different pools at the same time, so these counters can lose updates and also become a point of contention between threads. This fix can be merged independently of the interface design that is still open in pytorch#197868. I have reviewed the change, and the tests have been run on an A100.

The change gives each pool its own per-bucket stats, guarded by the free-list locks it already takes. The global allocations and allocated_bytes counters get a separate lock that is only taken when a block is created or destroyed, so the allocate and free paths that hit the cache need no extra locking. getStats() adds up the stats of all pools. When private pools are in use, the active peaks, which were already an estimate, can be higher than before; allocations and allocated_bytes stay exact.

The technical summary below was drafted with Claude, and I checked it against the code.

<details>
<summary>Technical details and test plan (drafted with Claude)</summary>

> Since pytorch#167507 added host private pools, the default pool and a private pool
> update the same HostStatsStaged counters. Each pool guards them with its own
> mutexes, the bucket stats with free_list_[i].mutex_ and allocations and
> allocated_bytes with blocks_mutex_, so updates from two pools race. For
> example, pinned allocations into a graph's private pool during capture can
> race with a DataLoader pin_memory thread and lose updates. In debug builds,
> free() can then fail the current >= 0 assert in Stat::decrease.
>
> Move the bucket stats into HostBlockPool, next to the free-list mutexes that
> already guard them, and give allocations and allocated_bytes their own
> mutex. Those two only change when a block is created or destroyed, so the
> cached allocate and free paths take no new lock. getStats() and the reset
> functions now walk every pool. When empty_cache() erases a private pool, it
> adds that pool's bucket stats to default_pool_'s, so the totals don't drop.
>
> A single stats mutex would also fix the race, but it would add a global lock
> to every cached allocate and free. Atomic counters would keep every pool
> writing the same cache lines.
>
> getStats() already estimates the total peak by summing per-bucket peaks. It
> now also sums per-pool peaks, and an erased pool's peaks stay counted until
> reset_peak_host_memory_stats(). So with private pools in use, the reported
> active_requests and active_bytes peaks can be higher than before, and can
> grow with each erased pool. allocations and allocated_bytes stay exact.
>
> Test Plan:
>
> ```bash
> python -m pip install -e . -v --no-build-isolation
> build/bin/cuda_caching_host_allocator_test --gtest_filter='CachingHostAllocatorTest.*'
> f=0
> for i in $(seq 1 20); do
>   build/bin/cuda_caching_host_allocator_test \
>     --gtest_filter=CachingHostAllocatorTest.stats_concurrent_pools >/dev/null 2>&1 || f=$((f+1))
> done
> echo "failed $f of 20"
> python -m pytest test/test_cuda.py \
>   -k "CachingHostAllocator or host_memory or pinned or pin_memory or host_emptyCache"
> ```
>
> All 10 gtests pass, and stats_concurrent_pools passes 20 of 20 runs. The
> pytest set gives 41 passed and 3 skipped, all disabled upstream. With the
> header reverted to 2a20f3e, stats_concurrent_pools fails 20 of 20 runs
> with lost counts. It is a stress test, so a run could pass by chance.
> stats_include_private_pools passes there as well, since it checks the
> summing across pools and not the race. No test covers the allocations and
> allocated_bytes half, because the cached path creates at most one block per
> pool. CI does not run cuda_caching_host_allocator_test, so the gtests were
> run locally.
>
> This change was prepared with assistance from Claude, an AI assistant.

</details>

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

Pull Request resolved: pytorch#199144
Approved by: https://github.com/ngimel

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@ngimel

ngimel commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator

@sujuyu are there any blockers/unresolved questions? Device pool rejecting multiple threads doesn't need to affect the host pool, so you can relax that requirement there. We'd need to figure out the interaction between graph-associated pools for host memory, and arbitrary pools that you need.

@sujuyu

sujuyu commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel No blockers; both PRs are up:

#200733: while writing the host mempool, I found that the host empty_cache() calls cudaFreeHost while holding allocator locks, which stalls pinned copies on other GPUs. It now frees after releasing the locks, and destroying a host mempool will rely on it too.

#200762: the host mempool itself, stacked on #200733.

I relaxed point 1 as you suggested: several threads can share a pool, and a thread can re-enter one. The rules between graph pools and HostMemPools are in the description of #200762. In short: during capture, allocations always go to the graph's pool; a graph does not hold a HostMemPool; and a HostMemPool cannot be used as a graph pool. Could you help confirm them?

Also note that point 4 differs from what I proposed earlier: deleting a HostMemPool frees its cached blocks right away, like a device MemPool does; blocks still in use are left to a later empty_cache().

I'll close this PR for now and continue the discussion on #200762.

@sujuyu sujuyu closed this Oct 13, 2026
sujuyu added a commit to sujuyu/pytorch that referenced this pull request Nov 5, 2026
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 detach_then_free() 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 detach_then_free(), 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]>
sujuyu added a commit to sujuyu/pytorch that referenced this pull request Nov 12, 2026
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 detach_then_free() 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 detach_then_free(), 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]>
sujuyu added a commit to sujuyu/pytorch that referenced this pull request Nov 12, 2026
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 detach_then_free() 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 detach_then_free(), 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]>
sujuyu added a commit to sujuyu/pytorch that referenced this pull request Nov 17, 2026
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]>
pytorchmergebot pushed a commit that referenced this pull request Nov 19, 2026
- [x] Passes lint (`spin fixlint`)
- [x] Added/updated tests
- [ ] Updated documentation (if applicable)
- [x] 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.

<details>
<summary>Root cause, fix, alternatives, and test plan</summary>

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

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

</details>

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

Pull Request resolved: #200733
Approved by: https://github.com/ngimel, https://github.com/kapilsh

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Kapil Sharma <[email protected]>
sujuyu added a commit to sujuyu/pytorch that referenced this pull request Nov 20, 2026
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]>
@sujuyu
sujuyu deleted the split/numa-pools branch November 20, 2026 01:41
pytorchmergebot pushed a commit to sujuyu/pytorch that referenced this pull request Nov 25, 2026
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]>
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

open source 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.

5 participants