Skip to content

Memory pool support for Caching Host Allocator. - #161583

Closed
galv wants to merge 2 commits into
pytorch:mainfrom
galv:memory-pool-support-host-allocator
Closed

galv wants to merge 2 commits into
pytorch:mainfrom
galv:memory-pool-support-host-allocator

Conversation

@galv

@galv galv commented Aug 27, 2025

Copy link
Copy Markdown
Collaborator

Includes basic support for stream capture to a cuda graph of pinned host memory to the memory pool.

We need a concept of memory pools in order to support a few things:

  1. Support of torch.Tensor.pin_memory() during cuda stream capture
  2. Custom allocators, which have a few niche use cases described here: New at::HostAllocator interface prevents using more than one allocator implementation for a device type #159906 (comment)

Note that (1) is most important right now, and therefore I have not added support for (2) at this time.

#146924 was my original attempt at this several months ago, where I thought that the major problem was how to implement a graph search algorithm inside the cuda graph to detect whether a given call to record_event() could be killed. In hindsight, this is not important in almost all use cases of interest today. In addition, this implementation also prevented me from recycling memory across seaprate cuda graphs sharing a memory pool (oops). Finally, it seems that there is preliminary evidence from #158352 (comment) that this graph search on the cuda graph can increase stream capture time substantially. I'm sure that is solvable, but I don't want to hold off on this. Instead, I use the current approach in CUDACachingAllocator.cpp: If a block is used on only one stream, and that stream is the stream that allocated it, then it can be reused. Otherwise, it can never be reused.

The initial use case of this is for offloading cached activations from the forward pass to the host, in order to reduce device memory pressure. Running these training workloads with cuda graphs allows them to run a few percentage points faster. Note that this use case does not ever recycle memory, since all allocations happen in the forward pass, and all frees happen in the backward pass.

@guangyey please give me your feedback on this. I had a choice between making breaking changes to CachingHostAllocatorImpl, which will break your XPU backend and potentially anyone else using your interface (is anyone?), or making a duplicate of it. I did the latter, since I needed to add a new field was_allocated_during_stream_capture_ to the Block template argument. This field needs to be inspected during the allocate() routine, in a way that cannot. Furthermore, I think that keeping implementation separate is good for when I eventually add support for reusing blocks during stream capture (see https://github.com/pytorch/pytorch/pull/146924/files#diff-5d3beb56bf9b6f380f91d5f6f063480ce2e14ca15c415d59d153436018089223R396-R404 for details on the algorithm), which will require two things: (1) usage of cuda graph APIs that exist in cuda but not sycl and (2) eagerly creating events when record_event() is called (which does not fit into the current implementation of CachingHostAllocatorImpl and its virtual methods at all).

Includes support for stream capture to a cuda graph of pinned host
memory to the memory pool
@galv
galv requested review from eqy and syed-ahmed as code owners August 27, 2025 01:04
@pytorch-bot

pytorch-bot Bot commented Aug 27, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 3 New Failures

As of commit 6fd73e8 with merge base 68d395d (image):

NEW FAILURES - The following jobs have failed:

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

@galv
galv requested review from cyyever and ngimel August 27, 2025 01:07
@galv galv added the release notes: cuda release notes category label Aug 27, 2025
@ngimel

ngimel commented Aug 27, 2025

Copy link
Copy Markdown
Collaborator

If a block is used on only one stream, and that stream is the stream that allocated it, then it can be reused. Otherwise, it can never be reused.

It's not good enough for host allocator - current events are to prevent reuse on the cpu while previous copy has not finished. Typical usecase:

def fn(iter):
    x = torch.empty(1024, pin_memory=True).fill_(iter) # prepare some data
    return x.to("cuda")
    
x_c0 = fn(0)
# at this point x went out of scope, next call to fn will reuse the memory, but the copy has not even started yet!
x_c1 = fn(1)
# by the time copies finally happen, both x_c0 and x_c1 will have "1", if nothing else happened to pinned memory in between

@galv

galv commented Aug 27, 2025

Copy link
Copy Markdown
Collaborator Author

@ngimel well that's embarrassing for me. I got so obsessed with offloading activations to host for training that I didn't think about anything else. Thank you. I will need to think this over for a bit.

@guangyey guangyey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for your mention.
I noticed that in this PR, the host caching allocator has multiple implementations, and each implementation maps to a MempoolId_t. Why not introduce a PrivatePool concept similar to what DeviceCachingAllocator uses?
That way, the host caching allocator would only need a single implementation, and each implementation could internally manage multiple PrivatePools. This approach may not break the original design and would also allow us to reuse existing code.
IMO, aside from differences in runtime APIs and some subtle behavioral variations, the core logic for managing pools/blocks is largely consistent across accelerators. It may be worthwhile to consolidate this logic into shareable code, which would also provide other backends an opportunity to benefit.
In addition, several accelerators provide similar graph modes, such as XPUGraph (coming soon), NPUGraph, MLUGraph, and others. Their behavior is quite similar to CUDAGraph, so the allocator logic should remain the same and could be made shareable.

@guangyey
guangyey requested a review from albanD August 27, 2025 08:58
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 27, 2025
@galv

galv commented Aug 27, 2025

Copy link
Copy Markdown
Collaborator Author

IMO, aside from differences in runtime APIs and some subtle behavioral variations, the core logic for managing pools/blocks is largely consistent across accelerators.

My point is that this was true when you made your initial work, but it isn't true today for the following reason:

  • In order to recycle memory fully during stream capture to a graph, we cannot do the "lazy" method of creating an event and recording it only at the end of a stream. This was a decision made back in torch7 IIRC as an attempt to try to minimize the overhead of cudaEventCreate(), which can synchronize the device. So even if you ignore the cuda stream capture issue, it is not crazy to think that you might want to use the non-lazy method today (since created events are now actually cached via the EventPool). Maybe there will be a performance reason for this for one accelerator, but not for another.

It's possible that Natalia's comment above may invalidate my need to make a lot of big changes. I am still trying to evaluate fully and I am slow :(

Again, I think that making the at::HostAllocator abstract interface is good.

My problem is with prescribing how this interface is implemented via insisting upon usage of at::CachingHostAllocatorInterface and an Impl class that implements an implicit interface via this macro:

#define DECLARE_HOST_ALLOCATOR(name, impl, deleter, instance) \
void deleter(void* ptr); \
struct name final \
: public at::CachingHostAllocatorInterface<impl, deleter> {}; \
static name instance; \
void deleter(void* ptr) { \
instance.free(ptr); \
}

Following this suggestion makes it extremely hard to change the implementation in non-trivial ways because, as soon as you need to introduce a new abstract method to do something (e.g., I need to call getCurrentCUDAStream() at one point, so I would need to wrap this in a virtual method that would be added here:

// Allocate page-locked memory on the host.
virtual void allocate_host_memory(size_t size, void** ptr) {
TORCH_CHECK_NOT_IMPLEMENTED(
false, "Not implemented for allocate_host_memory");
}
// Free block and release the pointer contained in block.
virtual void free_block(B* block) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for free_block");
}
// Record an event on stream and store event into events.
virtual void record_stream(std::optional<std::vector<E>>& events, S stream) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for record_stream");
}
// Query event if it is completed.
virtual bool query_event(E& event) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for query_event");
}
), you will break at compile time all other users of this interface unfortunately. When these implementations live outside of pytorch's main repo, we are basically out of luck for making sure there is no compile time breakage. I suppose you could add a "default" implementation which simply throws an exception for API's that don't exist for other implementations, but it would still temporarily break other users before they provide a proper implementation, in case calling this virtual method is unavoidable in CachingHostAllocatorImpl.

I noticed that in this PR, the host caching allocator has multiple implementations, and each implementation maps to a MempoolId_t. Why not introduce a PrivatePool concept similar to what DeviceCachingAllocator uses?

I originally considered doing that. But this approach effectively does the same thing as that, but in a fairly simple way. It also allows each pool to use its own mutexes in a way that will minimize cross-talk across threads. (You do need to use a mutex in CachingHostAllocatorInterface to handle selecting the proper impl, but you can do that via a reader-write lock, aka std::shared_mutex, fortunately.) Since we want pinned host memory allocations to be allocated to the same numa node as the current thread, which (should) be on a numa node next to its current GPU, I think this is a fairly good design that involves minimal changes to CachingHostAllocatorImpl, since it doesn't need to be aware of what a memory pool id is. Ultimately, I am not attached to one particular design, but I think this one is fairly straightforward to understand since it essentially separates out memory pools from the actual allocation logic.

@galv

galv commented Aug 27, 2025

Copy link
Copy Markdown
Collaborator Author

@ngimel Okay, thanks a lot for the pointer. I can write up a more mathematically precise document if desired, but I think my conclusion is as follows:

  1. If a cuda graph's operations read from pinned host memory, that pinned host memory cannot be recycled. This is because cuda stream capture is a form of lazy execution: The actual read from host memory won't happen until after cudaGraphLaunch() is called. So we must keep every host memory allocation used by a cuda graph alive as long as the cuda graph's memory pool is alive, with no opportunity for reuse at all.
  2. If a cuda graph's operations write to pinned host memory, that pinned host memory can be recycled. This is due to the fact that the CPU cannot ever write GPU memory (unless you are using cudaMallocManaged, which we are not), and because all GPU operations are going to be associated with a stream (thus, they will be captured in the cuda graph). Consider this:
import torch

host_data_ptrs = []

def fn(i):
    # d2h copy
    x_cpu = torch.empty(1024, device="cpu", pin_memory=True)
    x_gpu = torch.empty(1024, device="cuda").fill_(i)
    x_cpu.copy_(x_gpu, non_blocking=True)
    host_data_ptrs.append(x_cpu.data_ptr())
    return x_gpu

# warmup
x0_cpu = fn(0)
x1_cpu = fn(1)

g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g, capture_error_mode="thread_local"):
    x0_cpu_graph = fn(0)
    x1_cpu_graph = fn(1)

g.replay()
torch.cuda.synchronize()

# It is safe to reuse this memory
assert host_data_ptrs[-1] == host_data_ptrs[-2]
  1. (cont'd) However, there is not much point of writing to host memory inside of a cuda graph if you are going to delete it before the host even reads from it.

Some possible use cases come to mind:

  • We can write data-dependent shapes or boolean conditions to host memory, have the host allocate memory (or select the next cuda graph to run), and then run the next cuda graph, assuming that we are using the same memory pool for all cuda graphs.
  • More importantly, if you simply want to use pinned host memory as a scratch space to save gpu memory that you will then bring back to GPU memory later, then this can be helpful because you can reuse that pinned memory (e.g., for saving cached activations on host during interleaved pipeline parallelism, where it is no longer true that all forward passes happen before all backward passes), but only if we somehow could mark that the read from memory could be reused. In order to mark the read as "safe", we would have to "prove" that the CPU memory was never touched by the CPU. There is no obvious way to do this with today's infrastructure, though it isn't impossible (if your program is a single fxgraph, we could do it with something like inductor graph partition).

The first case is niche, and the second case is hard to implement without blowing up the scope of this. (Note that we would need to expand the record_event() API to document whether the host memory is being read or written as well.)

Nevertheless, the point still stands that being able to pin memory during stream capture is helpful for the sake of increasing memory capacity during training by offloading cached activations to host. I propose this simple path forward: Never recycle any host memory in a memory pool if it ever is used during stream capture. This would not hamper the main use case at all. This might make @guangyey happy because it means very little will change to CachingHostAllocatorImpl, such that I can use the original implementation without duplicating it. (But I still think the point stands that there is potential for a divergence to happen in the future.)

@ngimel

ngimel commented Aug 28, 2025

Copy link
Copy Markdown
Collaborator

Yeah I agree with a simple path forward if it enables important usecases, my comment was we should avoid breaking the world, which recycling memory had a full potential of doing. Lmk when this PR is ready for review.

@galv

galv commented Aug 28, 2025

Copy link
Copy Markdown
Collaborator Author

my comment was we should avoid breaking the world, which recycling memory had a full potential of doing

Yes, I agree strongly and am a bit disappointed I did not realize the counterexample you gave. Always appreciate your timely feedback.

@galv

galv commented Aug 28, 2025

Copy link
Copy Markdown
Collaborator Author

Okay, so I discussed a bit internally. If we allocate host memory that the host is banned from touching (we can mark the read and write bits to 0 in the page table on the host to guarantee this), we can actually recycle memory via graph search algorithms. This would allow interleaved pipeline parallelism to be able to reuse memory.

This is possible as of CUDA 13.0, since the cuMemCreate and cuMemSetAccess APIs together allow us to allocate memory on the host (that is device readable and writable but not readable or writable by the host):

Added support for cuMemCreate and cudaMallocAsync on the host, with CU_MEM_LOCATION_TYPE_HOST.

https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/index.html#id2

I'm not planning to do this anytime soon. We would need (1) a pluggable allocator API like @syed-ahmed made for CUDACachingAllocator and (2) to change the logic for detecting when memory blocks are reusable depending upon if a particular allocator is used. This is non-trivial and not needed by me or anyone internally right this instant. But I figure it was worth noting here. Honestly, @guangyey, I know I've been belaboring this point a few times, but it's going to get more and more difficult to keep the CachingHostAllocatorImpl and CachingHostAllocatorInterface classes "generic" as time goes on so I unfortunately will likely have to break away from using them for the CUDA implementation at some point.

@guangyey

guangyey commented Aug 29, 2025 •

Copy link
Copy Markdown
Collaborator

Currently, we see two possible approaches here:

  • Option 1 (current design): The host caching allocator has multiple CachingHostAllocatorImpls where each impl maps a memory pool associated with a MempoolId_t;
  • Option 2 (our proposal): Following the device caching allocator design, the host caching allocator keeps a single CachingHostAllocatorImpl and introduces the concept of PrivatePool to manage multiple memory pools.

Option 1 risks diverging the codebase, while Option 2 keeps the implementation generic and shareable across backends. In our view, we should always try to avoid divergence where possible, and evaluate on a case-by-case basis whether keeping the code generic is feasible.
That said, if the PyTorch community prefers CUDA-specific code, we are fine with it. However, we believe Option 2 provides a healthier long-term path for the community by keeping the generic design.

@galv

galv commented Aug 30, 2025

Copy link
Copy Markdown
Collaborator Author

@guangyey Thank you for the summary message. I will go ahead and evaluate option 2 for this PR, in an effort to reduce the amount of new code, once I revamp it to no longer try to memory block recycling. I do understand that there is clear benefit to maintaining abstractions so that the implementations can be similar, especially when they are quite complicated (e.g., see all the locks here). I appreciate you bearing my long messages.

@guangyey

Copy link
Copy Markdown
Collaborator

@galv Thanks a lot for the thoughtful evaluation. Let me know if there’s anything I can help with during your design.

@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Oct 29, 2025
galv added a commit to galv/pytorch that referenced this pull request Oct 31, 2025
I needed to move MemPool from c10 to aten. Otherwise, c10 would depend
upon CachingHostAllocator in aten, which is a circular dependency. An
alternative is to move the CachingHostAllocator to c10, but that is
more likely to break people.

This also works with cudagraphs, but in a pessimizing way: If a block
is ever allocated during stream capture, it will never be reused.

There might be some remaining issues regarding host statistics.

Follow up to pytorch#161583, which did
not work because of pytorch#161583 (comment)
Khanaksahu pushed a commit to Khanaksahu/pytorch that referenced this pull request Nov 17, 2025
Both allocation to a cuda graph's private pool via stream capture and
allocation to a memory pool in non-stream-captured code are supported.

In the case of stream capture, we refuse to reuse a host memory block
as soon as record_event() is called on that block. This is to prevent
a stream-captured CUDA kernel from reading different contents from a
memory block than would be read if, counterfactually, this CUDA
kernels were running eagerly on a cuda stream.

See
pytorch/pytorch#161583 (comment)
for elaboration.

This is lacking test cases for pagedable host memory copies. We must
make sure that record_event() does not fail in that case.


ghstack-source-id: 7f22464
Pull-Request: pytorch/pytorch#167507
@github-actions github-actions Bot closed this Nov 28, 2025
galv added a commit that referenced this pull request Dec 9, 2025
Both allocation to a cuda graph's private pool via stream capture and
allocation to a memory pool in non-stream-captured code are supported.

In the case of stream capture, we refuse to reuse a host memory block
as soon as record_event() is called on that block. This is to prevent
a stream-captured CUDA kernel from reading different contents from a
memory block than would be read if, counterfactually, this CUDA
kernels were running eagerly on a cuda stream.

See
#161583 (comment)
for elaboration.

This is lacking test cases for pagedable host memory copies. We must
make sure that record_event() does not fail in that case.

ghstack-source-id: a9db4f7
Pull-Request: #167507
tiendatngcs pushed a commit to tiendatngcs/pytorch-Dec25 that referenced this pull request Dec 10, 2025
Both allocation to a cuda graph's private pool via stream capture and
allocation to a memory pool in non-stream-captured code are supported.

In the case of stream capture, we refuse to reuse a host memory block
as soon as record_event() is called on that block. This is to prevent
a stream-captured CUDA kernel from reading different contents from a
memory block than would be read if, counterfactually, this CUDA
kernels were running eagerly on a cuda stream.

See
pytorch/pytorch#161583 (comment)
for elaboration.

This is lacking test cases for pagedable host memory copies. We must
make sure that record_event() does not fail in that case.

ghstack-source-id: 1f63f15
Pull-Request: pytorch/pytorch#167507
pytorchmergebot pushed a commit that referenced this pull request Dec 17, 2025
Both allocation to a cuda graph's private pool via stream capture and
allocation to a memory pool in non-stream-captured code are supported.

In the case of stream capture, we refuse to reuse a host memory block
as soon as record_event() is called on that block. This is to prevent
a stream-captured CUDA kernel from reading different contents from a
memory block than would be read if, counterfactually, this CUDA
kernels were running eagerly on a cuda stream.

See
#161583 (comment)
for elaboration.

This is lacking test cases for pagedable host memory copies. We must
make sure that record_event() does not fail in that case.
Pull Request resolved: #167507
Approved by: https://github.com/eqy, https://github.com/eee4017, https://github.com/ngimel
krastogi-in pushed a commit to krastogi-in/pytorch that referenced this pull request Jan 9, 2026
Both allocation to a cuda graph's private pool via stream capture and
allocation to a memory pool in non-stream-captured code are supported.

In the case of stream capture, we refuse to reuse a host memory block
as soon as record_event() is called on that block. This is to prevent
a stream-captured CUDA kernel from reading different contents from a
memory block than would be read if, counterfactually, this CUDA
kernels were running eagerly on a cuda stream.

See
pytorch#161583 (comment)
for elaboration.

This is lacking test cases for pagedable host memory copies. We must
make sure that record_event() does not fail in that case.
Pull Request resolved: pytorch#167507
Approved by: https://github.com/eqy, https://github.com/eee4017, https://github.com/ngimel
SergeyTyshkevich pushed a commit to SergeyTyshkevich/chart2 that referenced this pull request Jan 19, 2026
Only allocation to a cuda graph's private pool via stream capture is
supported.

Allocation to a memory pool in non-stream-captured code is not
supported. There is no obvious usecase at this time for that.

In stream capture, we refuse to reuse a host memory block as soon as
record_event() is called on that block. This is to prevent a
stream-captured CUDA kernel from reading different contents from a
memory block than would be read if, counterfactually, this CUDA
kernels were running eagerly on a cuda stream.

See
pytorch/pytorch#161583 (comment)
for elaboration.

ghstack-source-id: d1e30fc
Pull-Request: pytorch/pytorch#167507
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open source release notes: cuda release notes category Stale 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