Repository navigation
[PyBindings] Take ExecuTorchResult memory from the CUDA pool, and record method calls into CUDA graphs - #25624
shoumikhin wants to merge 2 commits into
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25624
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 6 PendingAs of commit 3a87f95 with merge base e1d2e24 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 36m 7s —— View job PR Review: #25624This PR moves Detailed reviewSummaryThe PR sends The main problem is retention: dropped result memory no longer goes back to the driver, and in common setups nothing ever trims it. The other findings are minor:
Code Quality
Testing
API Design
Backward Compatibility
Performance
RecommendationNeeds Discussion. The author needs to decide on retention: either add an API to release the memory, or state the behavior accurately in the description and README. The other findings are minor fixes:
|
9d341af to
a5a61b6
Compare
|
@claude review effort=max |
|
Claude encountered an error after 19m 11s —— View job PR Review: #25624
|
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 43m 12s —— View job PR Review: #25624The PR moves Detailed reviewSummaryI reviewed both commits: a5a61b6 (the pool) and f34bb98 (graph capture). The diff is against the PR parent The description makes two promises about captures:
Both hold for Code Quality
Testing
API Design
Thread Safety
Backward Compatibility
Performance
RecommendationRequest Changes The method-output Two design questions need the author's view: whether to refuse methods with a delegate while capturing, and whether the peer grants should cover the whole pool. The remaining findings are fixes to docs, error messages and tests.
|
There was a problem hiding this comment.
🟡 Changes recommended
Generic CUDA DLPack inputs can still invalidate graph capture because capsule export requests the legacy default stream instead of the capturing stream, and the wrapper case needs a regression test.
1 open issue
Review effort: Balanced
| if (devices.empty() || caller_stream_is_capturing()) { | ||
| return; |
…tor's pool A Python caller that runs a program with inputs on the GPU uploads them with ExecuTorchResult.from_host on every call and drops them afterwards. Each upload called cudaMalloc and each drop called cudaFree. Both go into the CUDA driver, and on a GPU that other processes also use, one of those calls can wait there for a long time, so a call that is normally fast is sometimes much slower. Uploads (from_host and to_device), output clones into an ExecuTorchResult and __dlpack__(copy=True) copies now take their memory from CudaAllocator::allocate_async and give it back with deallocate_async, on the legacy default stream that the result copies already use. On a device with memory pools that is the allocator's own pool, which the CUDA delegates already share, so making and dropping these results no longer calls cudaMalloc or cudaFree. Outputs handed over without a copy still come from the registered device allocator, as before. A device without memory pools still uses cudaMalloc and cudaFree, through the allocator's fallback. ROCm builds keep the previous code, because the ROCm allocator has no fallback for a device without memory pools. A dropped result's memory is not freed at once, because another library may still use it on a stream the legacy default stream does not wait for, such as a torch side stream, and the next upload can reuse it from the pool at once. A drop runs on whatever thread lets go of the last reference, and a wait for the device there would end a CUDA graph capture on another thread, so the drop makes no CUDA call and only records the memory. The memory goes back to the pool after the next wait for the whole device that the bindings already make, such as the waits of a method call, to_host() or __dlpack__. An upload or copy waits only when the pool cannot grow: it then waits for the device, frees the recorded memory and tries once more. Waiting on every upload would end a thread_local capture on another thread, such as the one torch.compile makes in reduce-overhead mode. The allocator now grants every peer device that can access a device access to that device's pool when it creates it. cudaMalloc memory is reachable from a peer once peer access is enabled, but pool memory only after the pool grants access, so without this a torch copy from another GPU into an upload failed. Freed memory stays reserved in the pool for later results and delegates of the same process, as torch's allocator keeps freed tensors. Other processes on the same GPU cannot use reserved memory. The new function executorch.runtime.cuda.empty_cache() gives it back, like torch.cuda.empty_cache(): it waits for each device and trims this allocator's pools, which the CUDA delegates share, so their next run grows them again. It leaves alone the device-wide CUDA graph memory, which other libraries share. The pool also gives memory back when the last CUDA delegate is destroyed. The README says so. New tests check that uploads take their memory from the pool, make no cudaMalloc or cudaFree call and reuse the memory of dropped uploads; that another GPU can copy into an upload; that uploads dropped while a torch side stream still reads them keep their data; that an upload dropped on another thread during a CUDA graph capture leaves the capture intact, and so does an upload on another thread; that an upload takes back the memory of dropped uploads when the pool cannot grow; and that empty_cache() gives the memory of a dropped upload back to the GPU. The device chain test still sees two waits per call, since the memory of dropped uploads goes back after those waits. The allocator exit test reports a single device, so the new peer loop stays quiet on a machine with several GPUs. Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
A common way to cut launch overhead is to record a whole inference step
into one CUDA graph and replay it:
from executorch.runtime import cuda
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
with cuda.stream(torch.cuda.current_stream()):
out = method.execute([static_input], clone_outputs=False)[0]
static_input.copy_(new_input)
graph.replay()
Today the first call fails with "Failed to synchronize CUDA tensor
storage: operation not permitted when stream is capturing", and the
caller's capture is lost. The bindings wait for the whole GPU before and
after every call that has GPU inputs or outputs, so that memory another
library writes on its own streams is ready. A capture cannot take that
wait.
While the selected stream is capturing, nothing runs yet, and the capture
already puts the work in order. So the bindings now skip those two waits
when the stream selected with executorch.runtime.cuda.stream() is
capturing. Nothing changes outside a capture, or for a caller that has
not selected a stream.
Some steps of a call still need a GPU wait or new GPU memory, and neither
works inside a capture: converting a torch input into the exported
layout, copying a GPU output (clone_outputs=True), and allocating a new
output buffer. During a capture these are refused with a clear message
before the call records or changes anything, instead of failing inside
CUDA and ending the capture: for a method that already ran, the
previous outputs, the installed inputs and what get_outputs() returns
stay as they were. Outputs bound with set_output() are neither copied
nor given a new buffer, so they are not refused. A method's first call
through a Module is refused too, since loading the method allocates GPU
memory. Method output memory dropped during the capture is kept, since
cudaFree can end the capture.
A generic DLPack input is asked to order its work on the capturing
stream, since a wait on the legacy default stream would end the capture
too, so its producer has to work on that stream. The
executorch.runtime.cuda docs describe this, and also that work a call
does on the host, such as copying a CPU input into the program's memory,
happens once, during the capture.
ExecuTorchResult uploads and copies take their memory from the CUDA
allocator's pool. During a capture on the selected stream, from_host()
and other copies to GPU memory are refused too, and so are to_host(),
empty_cache() and other calls that wait for the GPU. A result dropped on
the capturing thread during the capture keeps its memory until the
process exits, since the graph may still use it.
Whether a whole call can be captured also depends on the delegate: it has
to queue its work on the selected stream and must not wait for it. The
method call test therefore uses a program without a delegate. Other
tests check that refused calls leave the outputs and inputs as they
were, that a first Module call is refused, and that bound outputs are
not.
Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
f34bb98 to
12c4901
Compare
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 39m 0s —— View job PR Review: #25624Approve: nothing blocks merging, but a refused Detailed reviewSummaryThe PR moves
I reviewed both commits (4265809 and 12c4901) against the PR parent f748232 and covered all 7 changed files. Code Quality
Testing
API Design
Thread Safety
Performance
RecommendationApprove Nothing blocks merging. The Code Quality and Testing fixes are small and worth making first. The author can decide on the two capture refusals, the deferred-free option, and the peer-grant question from the previous review.
|
12c4901 to
e7c6b3a
Compare
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 46m 2s —— View job PR Review: #25624Request changes: an upload or copy now waits for the whole GPU whenever a dropped result is pending. That wait ends a CUDA graph capture running on another thread, even a Detailed reviewSummaryThe PR makes four changes:
The blocking problem is the device wait that the deferred frees added to the allocation path (see Thread Safety). The other findings are:
Both commits (a25b0d9, e7c6b3a) were diffed against the PR parent e1d2e24, because the shallow checkout has no merge base with Code Quality
Testing
API Design
Thread Safety
Performance
RecommendationRequest Changes The wait on the allocation path brings back the cross-thread device wait that the PR removes from drops. It breaks
|
e7c6b3a to
3a87f95
Compare
|
@claude review effort=max |
|
Claude finished @shoumikhin's task in 57m 44s —— View job PR Review: #25624Request Changes for two README statements that contradict the code: a copy of a CUDA result on another thread ends a Detailed reviewSummaryThe PR moves Problems found:
Scope: diffed against the PR parent e1d2e24, because the shallow checkout has no merge base with Code Quality
Testing
API Design
Thread Safety
Backward Compatibility
RecommendationRequest Changes The README statements under Thread Safety and Backward Compatibility are wrong, and users act on them during captures and under memory pressure. Both are small documentation fixes, and neither needs a code change. The remaining four items are minor. Review steps
|


Summary
This PR changes how the Python bindings use GPU memory.
Take result memory from the CUDA allocator's pool.
Programs without torch often upload GPU inputs with
ExecuTorchResult.from_hostevery call, so each rancudaMallocandcudaFree, which can stall on a shared GPU.Now uploads and
ExecuTorchResultoutput copies, including__dlpack__(copy=True), take memory fromCudaAllocator::allocate_async, the pool the CUDA delegates use. In torch output mode, copies still use torch's allocator. GPUs without memory pools and ROCm builds keep the old code.thread_localcapture on another thread.executorch.runtime.cuda.empty_cache()gives it back, liketorch.cuda.empty_cache().Let a method call be recorded into the caller's CUDA graph.
Today the bindings wait for the whole GPU, which ends the capture. While the stream selected with
executorch.runtime.cuda.stream()captures, they skip those waits, since the capture orders the work.Steps that need a wait or new GPU memory are refused before the call records or changes anything: a torch input layout conversion,
clone_outputs=Truefor GPU outputs, a new output buffer, a method's firstModulecall, GPU copies such asfrom_host(), and waits such asto_host(). Outputs bound withset_output()are allowed. A delegate has to queue its work on the selected stream without waiting; the CUDA delegate cannot yet. Nothing changes outside a capture.Test plan
New tests in
extension/pybindings/test/test_pybindings_cuda_dlpack.pycheck that uploads reuse pool memory, also from a full pool; that drops and uploads on another thread leave a capture intact; thatempty_cache()returns dropped memory; that another GPU can write an upload; and that refused calls keep the capture, outputs and inputs as they were. No in-tree delegate runs in a capture yet, so replays check the capture, not a kernel.Each new test fails without its change. The whole file passes in both output modes on x86_64 Linux with an NVIDIA A100, and the multi-GPU test on 2 A100s. Not run: GPUs without memory pools, Windows, ROCm.