Skip to content

[PyBindings] Take ExecuTorchResult memory from the CUDA pool, and record method calls into CUDA graphs - #25624

Open
shoumikhin wants to merge 2 commits into
pytorch:mainfrom
shoumikhin:result-pool-main
Open

shoumikhin wants to merge 2 commits into
pytorch:mainfrom
shoumikhin:result-pool-main

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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_host every call, so each ran cudaMalloc and cudaFree, which can stall on a shared GPU.

Now uploads and ExecuTorchResult output copies, including __dlpack__(copy=True), take memory from CudaAllocator::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.

  • A drop makes no CUDA call; the memory returns to the pool after the next device wait, since a torch side stream may still use it. An upload waits only when the pool cannot grow, so neither ends a thread_local capture on another thread.
  • Peer GPUs get access to the pool, so they can copy into an upload.
  • Freed memory stays reserved for reuse; the new executorch.runtime.cuda.empty_cache() gives it back, like torch.cuda.empty_cache().

Let a method call be recorded into the caller's CUDA graph.

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 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=True for GPU outputs, a new output buffer, a method's first Module call, GPU copies such as from_host(), and waits such as to_host(). Outputs bound with set_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.py check that uploads reuse pool memory, also from a full pool; that drops and uploads on another thread leave a capture intact; that empty_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.

@shoumikhin shoumikhin added the release notes: api Changes to public facing apis (any interfaces, pybinded runtime methods, etc.) label Nov 23, 2026
Copilot AI balanced review requested due to automatic review settings November 23, 2026 22:43
@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🔗 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 Pending

As of commit 3a87f95 with merge base e1d2e24 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 23, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 36m 7s —— View job


PR Review: #25624

This PR moves ExecuTorchResult device memory onto the CUDA allocator's pool so uploads no longer call cudaMalloc/cudaFree, but freed result memory can now stay reserved until the process exits with no way to release it from Python, and a few error paths, tests and docs need small fixes, so the recommendation is Needs Discussion.

Detailed review

Summary

The PR sends ExecuTorchResult device memory (uploads, clones and __dlpack__(copy=True) copies) through CudaAllocator::allocate_async and deallocate_async on the default stream. It waits for the device before each free and updates the CUDA DLPack tests.

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:

  • two error paths
  • a pool test that cannot detect a missing free
  • output buffers that still use cudaMalloc
  • the README

Code Quality

  • A failed device switch leaves a CUDA error pending (pybindings_cuda.h:72-76).
    • require_cuda_device checks only the device count. A visible device that is unavailable or in prohibited compute mode passes that check and then fails cudaSetDevice, as cuda_allocator.cpp:426-430 describes.
    • CUDAGuard::create does not clear that error, and this branch throws without (void)cudaGetLastError(). The next cudaGetLastError() in another library, such as a torch kernel-launch check, then reports it as its own failure. The comment at pybindings_cuda.h:152-153 warns about exactly this.
    • The CudaAllocator::allocate path this replaces cleared the error (cuda_allocator.cpp:413-417, :436).
    • Fix: clear it before throwing, as release_cuda_result already does at line 30.
  • The device-selection failure branch of release_cuda_result frees pool memory without waiting (pybindings_cuda.h:29-40).
    • For memory from cudaMallocFromPoolAsync, cudaFree does no implicit synchronization; the CUDA docs leave it to the caller to make sure all accesses have finished. This branch therefore returns the memory to the pool while another library may still use it, which is exactly the case lines 42-45 wait for.
    • The description's "freed with cudaFree, as before" no longer holds, because before, cudaFree waited for the device.
    • It also contradicts the policy at lines 48-57, which leaks memory it cannot wait for. Logging and returning here as well would make the two failure paths agree.

Testing

  • test_host_uploads_take_memory_from_the_pool cannot detect a drop that never frees (test_pybindings_cuda_dlpack.py:1352-1355).
    • The pool grows by mapping memory inside the driver, which never shows up in the trace as cudaMalloc. So the comment's inference, "no cudaMalloc means the dropped uploads' memory served the later ones", does not hold.
    • A deleter that leaked would still give 8 cudaMallocFromPoolAsync calls and no cudaMalloc. That covers taking the branch at pybindings_cuda.h:48-57 or losing the deallocate_async call.
    • Fix: also assert 8 cudaFreeAsync calls.
  • Two load-bearing parts of the new code have no test:
    • What the drop wait protects (pybindings_cuda.h:42-45). The case is a torch kernel on a side stream that still reads an exported upload when the upload is dropped and the next upload reuses its memory. The chain test only counts cudaDeviceSynchronize events, so it shows that a wait happens, not that it protects the memory. test_reused_output_memory_waits_for_pending_readers (:1007) is the same test for outputs; a from_host version would cover this.
    • An upload to a non-current device. Without the guard at pybindings_cuda.h:72, allocate_async falls back to cudaMallocAsync on whichever device is current (cuda_allocator.cpp:643-653), while the result records index. test_dlpack_input_on_a_non_current_device (:883) already has the two-GPU subprocess pattern.

API Design

  • The README's list of device-wide waits is now incomplete (extension/pybindings/README.md:184-201).
    • Dropping a CUDA result now runs an explicit cudaDeviceSynchronize (pybindings_cuda.h:46-47) wherever Python drops the last reference, so it runs with the GIL held. As with the waits the README lists, a queued host callback that needs the GIL can make it hang.
    • The README also does not say that dropped result memory stays reserved (see Backward Compatibility).

Backward Compatibility

  • Freed result memory can stay reserved until the process exits, and nothing can release it. The pool's release threshold is UINT64_MAX (cuda_allocator.cpp:65), so the only release is release_cached_memory(-1) when the last CUDA delegate handle is destroyed (cuda_backend.cpp:944-960):

    • Linux: an upload or clone that outlives the module, or is made after it, goes back to the pool after that one trim and stays there until exit. That contradicts the description's "keeps what it has reserved until the last CUDA delegate handle is destroyed, which trims it".
    • Windows: the Python extension never links the delegate (CMakeLists.txt:1369-1374; see also the comment that is now at pybindings_cuda.h:90), so every Windows process is the "never loads one" case, not an edge case.
    • No release path: no binding calls release_cached_memory, and torch's OOM retry, which empties only torch's own cache, cannot reach this pool. Before this PR, a process that alternates large ExecuTorch uploads with torch work got that memory back on every drop. It can now hit an OOM in torch.

    One option is a trim next to the stream API in runtime/cuda.py, the counterpart of torch.cuda.empty_cache(), that waits for the device and then calls CudaAllocator::release_cached_memory(-1). Otherwise, the description and README should state the retention accurately.

  • Low confidence: pool memory loses peer access and legacy IPC (cuda_allocator.cpp:108-112).

    • The pool uses handleTypes = cudaMemHandleTypeNone and never calls cudaMemPoolSetAccess. Pool allocations ignore cudaDeviceEnablePeerAccess, and cudaIpcGetMemHandle does not accept them.
    • Uploads, clones and copies used to be cudaMalloc memory, which supports both. A consumer that reads an imported result from a kernel on another GPU through peer access would now fault, and sharing one through legacy IPC would fail.
    • Handed-over outputs still come from cudaMalloc, so the kinds of result now behave differently. I could not confirm that any caller relies on either feature.

Performance

  • Per-call device output buffers still go through cudaMalloc and cudaFree.
    • PyModule::run_method reallocates every device output that is not memory planned on every call (pybindings.cpp:3753, :4050). allocate_device_output goes through DeviceMemoryBuffer::create to CudaAllocator::allocate, which calls cudaMalloc (cuda_allocator.cpp:442).
    • PyMethod does the same whenever the caller still holds the outputs of the two previous calls (pybindings.cpp:5359-5366), for example when it collects outputs in a list.
    • These callers still make the driver calls the PR blames for slow calls. Handed-over outputs are results too, so "This covers every result these bindings allocate on a GPU" overstates the change.
    • Fix: route allocate_device_output through the pool, or say in the description that outputs are follow-up work.

Recommendation

Needs 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:

  • clear the pending error and make the two failure paths agree
  • assert the cudaFreeAsync count
  • document the drop wait
  • possibly move the output buffers onto the pool

  • Load the pr-review skill and gather PR context
  • Run three independent reviews
  • Consolidate the findings
  • Fact-check findings
  • Post the final review

Copilot AI balanced review requested due to automatic review settings November 24, 2026 06:29
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 19m 11s —— View job


PR Review: #25624

  • Load the pr-review skill and gather PR context
  • Run three independent reviews
  • Consolidate the findings
  • Fact-check findings
  • Post the final review

Checked so far:

  • Retention: confirmed. The pool's release threshold is UINT64_MAX, and the only trim runs when the last delegate handle is destroyed.
  • Drop wait: confirmed that a drop now calls cudaDeviceSynchronize, and that the memory is never freed if that wait fails.

Next: the README's clone_outputs=True claim, the peer-access grant, and the tests.

Copilot AI balanced review requested due to automatic review settings December 1, 2026 10:25
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 43m 12s —— View job


PR Review: #25624

The PR moves ExecuTorchResult GPU memory onto the CUDA allocator's pool and lets a method call be recorded into a caller's CUDA graph. However, method output buffers can still be freed with cudaFree in the middle of a capture, which ends the very capture the new refusals are meant to protect, so I recommend Request Changes.

Detailed review

Summary

I reviewed both commits: a5a61b6 (the pool) and f34bb98 (graph capture). The diff is against the PR parent ec5937f, because the shallow checkout has no merge base with origin/main. All 7 changed files were covered.

The description makes two promises about captures:

  • steps that cannot run are "refused up front … instead of failing inside CUDA and ending the capture";
  • "A result dropped during the capture keeps its memory".

Both hold for allocate_cuda_result memory. Neither holds for method output buffers, which still come from DeviceMemoryBuffer and go back with cudaFree. The other findings are a design question about delegates, inaccurate docs and error messages, and test coverage.

Code Quality

  • Method output buffers can still be freed with cudaFree during a capture, which ends a global-mode capture (extension/pybindings/pybindings.cpp:4025, :2392-2395). I confirmed this by reading the code path; I did not run it.

    • During a refused call. PyModule::allocate_output_tensors runs output_tensors_.clear() (4025) before the capture refusal in allocate_device_output (4068 → 2382).
      • If nothing else holds the previous call's output, the clear frees it: ~DeviceMemoryBuffer → CudaAllocator::deallocate → cudaFree (extension/cuda/cuda_allocator.cpp:573, which has no capture check).
      • Trigger: take a method with an unplanned GPU output, call module.forward(x, clone_outputs=False) once and drop the result. Then call it again inside torch.cuda.graph(g) and cuda.stream(torch.cuda.current_stream()).
      • The ValueError arrives after the capture is already invalidated, so capture_end fails. That is the outcome the refusal exists to prevent.
    • When a result is dropped. A result that is the last owner of its buffer hits the same path when it is dropped inside a capture.
      • Module results pin their allocation (dlpack_output_owner, 2194-2200; handed_over_device_outputs, 3986-4009). So after r1 = module.forward(x)[0]; r2 = module.forward(x)[0], a del r1 inside a capture calls cudaFree.
      • In PyMethod, the same happens after the spare rotation releases a spare whose result is still alive (5383).
      • So "A result dropped during the capture keeps its memory" is true only for allocate_cuda_result memory.
    • Fix:
      • Build the list in a local and move it in after the loop, as allocate_output_storages does (5306-5358). The refusal then fires before anything is freed.
      • Give the shared_ptr<DeviceMemoryBuffer> returned by allocate_device_output a deleter that keeps the memory while caller_stream_is_capturing(), as release_cuda_result does (pybindings_cuda.h:55-61).
      • Add a global-mode module test. The only output-buffer test (test_pybindings_cuda_dlpack.py:441-448) uses relaxed mode on a fresh PyMethod, where nothing gets freed.
      • Fix this →
  • Methods with a delegate are not refused while capturing, although the docs say none can be captured yet (extension/pybindings/pybindings.cpp:2439, runtime/cuda.py:39-40).

    • The docstring says "the CUDA delegate cannot run inside a capture yet", and the test notes that no in-tree delegate can be captured (test_pybindings_cuda_dlpack.py:410-411). Yet a method with a delegate still runs: the bindings skip their waits and leave the outcome to the delegate.
    • Skipping the waits is only safe if every delegate in the method queues its work on the selected stream and never waits. Nothing checks that.
    • A delegate that uses its own stream would run eagerly during the capture and read inputs whose producers have only been recorded. Its work would also be missing from replays, and nothing would report an error. This part is suspected, not confirmed. Before this PR, the bindings' device wait made such a call fail loudly.
    • Suggested fix: while capturing, refuse a call whose MethodMeta::num_backends() > 0 (runtime/executor/method_meta.h:286) before any state changes. That extends "refused up front" to delegates until one is known to be capture-safe.
    • A related gap: cuda.py:39 says a program's own copy to host memory "waits for s and fails". In fact copy_impl calls cudaStreamSynchronize on the capturing stream (extension/cuda/cuda_allocator.cpp:379-380), which also ends the capture. Checking stream_is_capturing() (same file, 230-237) before the cudaMemcpyAsync would make the copy fail without ending the capture.
    • Fix this →
  • Minor: PyMethod refuses a new output buffer only after it has changed its own state (extension/pybindings/pybindings.cpp:4822).

    • The refusal comes from allocate_output_storages(). By then, call() has already run set_inputs (4894), and execute_installed has reset outputs_valid_ and handed_outputs_ (4801-4802).
    • So after a refused call, the method holds the new inputs, and a later get_outputs() raises "has no outputs to return".
    • Only the clone_outputs refusal (4893) is up front, but the description says this one is too.
    • Fix this →

Testing

  • The capture test's replay check cannot catch an ExecuTorch failure (extension/pybindings/test/test_pybindings_cuda_dlpack.py:412-429).
    • _device_identity returns its input, and its inputs and outputs are not memory-planned (909-925). So output aliases doubled, and the assert after graph.replay() only checks torch's value * 2.
    • The call could record nothing, or the wrong thing, and the test would still pass.
    • The test plan says these tests show "a call records and replays correctly", and runtime/cuda.py:35-36 says a replay runs the call's GPU work. No test covers that recording.
    • If no in-tree program can show it yet, the test plan should say so.

API Design

  • The wait refusal gives method-input advice to every caller (extension/pybindings/pybindings_cuda.h:186-192).

    • The message ends "A method call waits to convert a torch input into the exported layout, so pass inputs in that layout".
    • It is also raised by:
      • ExecuTorchResult.to_host() (pybindings_executorch_result.h:427; the new test hits it at 463-464);
      • __dlpack__ with a consumer stream, which is how torch.from_dlpack calls it (pybindings_executorch_result.h:369-371);
      • get_attribute() (pybindings.cpp:4961).
    • For those callers the advice is wrong. runtime/cuda.py:40-45 does not list them among the refusals either.
    • Make the message generic, or pass a hint from each caller.
    • Fix this →
  • The README overstates which results use the pool (extension/pybindings/README.md:203-206).

    • It says a CUDA ExecuTorchResult with clone_outputs=True takes its memory from the pool, so making and dropping it calls neither cudaMalloc nor cudaFree.
    • Two cases still get their memory from DeviceMemoryBuffer and release it with cudaFree:
      • an unplanned output handed over without a copy (hand_over_device_output, pybindings.cpp:5189-5223; README:56-57);
      • the output memory a module allocates on each call (README:65).
    • Say "a copy made by clone_outputs=True" instead.
    • Fix this →

Thread Safety

  • Minor: a drop on another thread, or outside the cuda.stream() block, now ends captures that survived cudaFree (extension/pybindings/pybindings_cuda.h:55, :80).
    • The keep-memory check only sees a capture on the stream this thread selected. caller_stream_is_capturing() reads the thread-local caller stream (extension/cuda/caller_stream.cpp:14), so every other drop runs cudaDeviceSynchronize.
    • CUDA rejects cudaDeviceSynchronize in every capture mode while any stream on the device captures. cudaFree, which it replaces, is allowed in relaxed mode, and from other threads in thread_local mode.
    • So these drops now end a capture that used to survive:
      • a result released on a worker thread during a thread_local capture (native DLPack consumers do this, pybindings_executorch_result.h:567-568);
      • a result dropped outside the cuda.stream() block during a relaxed capture.
    • README:206-212 says the drop waits "as cudaFree did", which is not true in these cases. At least document it.
    • Fix this →

Backward Compatibility

  • Torch in the same process cannot use the reserved pool memory either (extension/pybindings/README.md:213-218).

    • Before this PR, a dropped from_host() upload went straight back to the driver. Now it stays in the pool.
    • So a process that mixes torch with large uploads can run out of memory in torch where it did not before, and torch.cuda.empty_cache() does not help.
    • The README only mentions other processes. One more sentence would cover this; I'm not asking for a new API.
    • Fix this →
  • Minor: clone_outputs=True is now refused for methods without GPU outputs (extension/pybindings/pybindings.cpp:3515, 4881, 4893).

    • The refusal does not look at the outputs. So inside a capturing cuda.stream() block, a CPU-only method called with the default clone_outputs=True now raises.
    • Cloning CPU outputs never waits for the GPU, and that call worked before this PR.
    • Refuse only when an output is on a GPU.
    • Fix this →

Performance

  • The new peer grants cover the whole shared pool, not just results (extension/cuda/cuda_allocator.cpp:142-176).
    • cudaMemPoolSetAccess applies to every allocation in the pool. This pool also serves SlimTensor storage (backends/aoti/slim/core/storage.h:120) and the KV pool (backends/cuda/runtime/cuda_kv_pool.cpp:235).
    • On a multi-GPU host, every allocation the CUDA delegate makes is therefore mapped into each peer that can access the device: 7 peers per pool on an 8-GPU NVLink node. Pool growth pays for those mappings.
    • This was not measured, and CI has a single GPU.
    • Consider granting a peer only when a result first moves to another device, or measure the growth cost on a multi-GPU host.
    • The scope is confirmed from the code; the cost is my estimate.

Recommendation

Request Changes

The method-output cudaFree path breaks the PR's own capture contract under torch's default global capture mode: a refused module call, or a dropped module result, ends the capture.

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.

  • Read the PR context and both commits
  • Ran three independent reviews
  • Merged duplicate findings
  • Fact-checked each finding against the code
  • Posted the review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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

Comment on lines +2439 to +2440
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>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 16:01
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 39m 0s —— View job


PR Review: #25624

Approve: nothing blocks merging, but a refused module.forward() during a capture leaks its previous output buffers, two capture refusals are stricter than they need to be, the executorch.runtime.cuda docstring leaves out the drop hazard the README describes, and three tests need hardening.

Detailed review

Summary

The PR moves ExecuTorchResult uploads, clones and DLPack copies onto the CUDA allocator's stream-ordered pool, and lets a method call be recorded into a CUDA graph that the caller's selected stream is capturing. Nothing here blocks merging. The findings are:

  • one leak and one unclear failure on refused calls;
  • two refusals that are stricter than needed;
  • a gap in the executorch.runtime.cuda docstring;
  • three tests that need hardening;
  • a question from the previous review that is still open.

I reviewed both commits (4265809 and 12c4901) against the PR parent f748232 and covered all 7 changed files.

Code Quality

  • Two PyModule::run_method paths touch GPU memory before the capture refusal runs (extension/pybindings/pybindings.cpp).
    • allocate_output_tensors clears output_tensors_ (:4073) before allocate_device_output refuses the call (:4116). If the module was the last owner of the previous call's output buffers, they are released during the capture, and the new deleter (:2432-2443) then keeps them until the process exits. So every refused call leaks one set of buffers. Build the buffers in a local vector and move it in after the loop, as PyMethod::allocate_output_storages does (:5405-5408).
    • The first module.forward() inside a capture loads the method (:3801), and loading allocates GPU memory (extension/module/module.cpp:480). Unless the capture is relaxed, that cudaMalloc ends it, and the caller only sees "Failed to execute method". Refuse an unloaded method during a capture, before load_method runs.
    • Fix this →

Testing

  • The allocator exit test now calls into the real CUDA driver (extension/cuda/test/cuda_allocator_exit.cpp:45-101).
    • The new peer loop in mem_pool_for (extension/cuda/cuda_allocator.cpp:145-176) calls cudaGetDeviceCount, cudaDeviceCanAccessPeer and cudaMemPoolSetAccess, and the test has no stand-in for any of them.
    • On a host with peer-capable GPUs, the real cudaMemPoolSetAccess receives fake_pool, a pointer into the test's storage. At best that logs an error; I did not check what the driver does with the bad handle.
    • The comment at line 45 says the stand-ins keep the test independent of the GPUs, and that no longer holds. Add a cudaGetDeviceCount stand-in that reports one device.
    • Fix this →
  • Two new pool tests pass even when the case they guard never happens (extension/pybindings/test/test_pybindings_cuda_dlpack.py).
    • test_results_made_or_dropped_during_a_capture_leave_it_intact (:499) checks that the capture survives, but the graph never reads uploaded. A drop that freed its memory without ending the capture would pass too. After the capture, upload the same size again and assert that the address is different.
    • test_side_stream_reads_of_dropped_uploads_stay_intact (:1502) only sets up the race if a later upload reuses the block of a dropped one. When pools are supported, assert that some uploaded.data_ptr() repeats.
    • Fix this →

API Design

  • torch.from_dlpack(result) is refused during a capture, even when torch asks for the capturing stream (extension/pybindings/pybindings_executorch_result.h:369-372).
    • Inside torch.cuda.graph, torch passes its current stream. That is the capture stream, and in the tests' pattern it is also the selected caller stream. to_dlpack waits unless the stream is -1, so refuse_device_wait_during_capture() throws.
    • The rest of the bindings treat that stream as safe. A method call in the same spot skips its waits (pybindings.cpp:2487), and cuda_dlpack_capsule asks other producers for exactly that stream (pybindings.cpp:1748-1751).
    • As a result, a result made inside the capture can reach torch only through a raw __dlpack__(stream=-1) capsule. Skip the wait when the requested stream is the capturing caller stream.
    • Fix this →
  • clone_outputs=True is refused even when every GPU output is bound with set_output() (extension/pybindings/pybindings.cpp:2389-2408, called at :4929 and :4942).
    • read_outputs never clones a bound output (:4961-4984), and the allocation refusal (:2425) itself recommends set_output(). A caller who follows that advice but keeps the default clone_outputs=True is refused a second time.
    • In the PyMethod paths, skip outputs for which is_bound_output(i) is true.
    • Fix this →

Thread Safety

  • Dropping a pool-backed result on another thread, or outside the capturing thread's block, still ends any capture on the device (extension/pybindings/pybindings_cuda.h:55, :80).
    • caller_stream_is_capturing() only sees this thread's selection (extension/cuda/caller_stream.cpp:14), so every other drop runs cudaDeviceSynchronize. That call fails and invalidates the capture in every capture mode. cudaFree used to succeed there in relaxed captures, and on other threads in thread_local captures.
    • Drops come from refcounting and GC, so a worker thread can end another thread's capture without calling any API.
    • The README now covers this (extension/pybindings/README.md:214-218), but the executorch.runtime.cuda docstring does not (runtime/cuda.py:46-52). It covers only drops inside the block and the last owner of a method.
    • There is an option that removes both the hazard and the extra waits that the chain test now expects with pools (test_pybindings_cuda_dlpack.py:1431). Instead of waiting in the deleter, queue freed blocks and return them to the pool after the next device wait the bindings already make.
    • Fix this →

Performance

  • Still unanswered from the previous review: the peer grants cover the whole shared pool (extension/cuda/cuda_allocator.cpp:142-176).
    • Each time the pool grows, the grants also map the CUDA delegate's SlimTensor and KV-pool memory to every peer, not only the results handed to other libraries.
    • The cost has not been measured.

Recommendation

Approve

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.

  • Load the /pr-review skill and the review checklist
  • Get the diff against the PR parent (f748232, 2 commits)
  • Run three independent reviewers over all 7 changed files
  • Merge their findings
  • Fact-check findings
  • Post the final review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

GPU-owner validation is needed for allocator reuse and CUDA graph lifetime safety because captured delegate execution and non-pool, Windows, and ROCm paths remain untested.

1 open issue

Review effort: Balanced

@shoumikhin shoumikhin changed the title [PyBindings] Take ExecuTorchResult device memory from the CUDA allocator's pool [PyBindings] Take ExecuTorchResult memory from the CUDA pool, and record method calls into CUDA graphs Dec 3, 2026
Copilot AI balanced review requested due to automatic review settings December 3, 2026 06:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 46m 2s —— View job


PR Review: #25624

Request 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 thread_local one that such an upload did not break before this PR. The other findings are minor.

Detailed review

Summary

The PR makes four changes:

  • ExecuTorchResult uploads, clones and DLPack copies take their memory from the CUDA allocator's pool, and their frees wait for the next device wait.
  • It adds executorch.runtime.cuda.empty_cache().
  • It grants peer devices access to the pool.
  • Calls can be recorded into a CUDA graph captured on the stream selected with executorch.runtime.cuda.stream().

The blocking problem is the device wait that the deferred frees added to the allocation path (see Thread Safety). The other findings are:

  • a README sentence that misstates which drops are safe during a capture;
  • memory that the bindings leak on the caller's behalf during a capture;
  • capture refusals that miss some cases or ignore set_output() bindings;
  • a test that needs an otherwise idle GPU.

Both commits (a25b0d9, e7c6b3a) were diffed against the PR parent e1d2e24, because the shallow checkout has no merge base with origin/main. All 9 changed files were covered. No tests were run.

Code Quality

  • A call during a capture can leak memory that the caller dropped before the capture. The leak happens when the call lets go of what the bindings kept from an earlier call.
    • PyModule::run_method replaces the input owners kept from the previous call (extension/pybindings/pybindings.cpp:3920-3923).
    • Example: a warm-up call takes a temporary from_host() result, and the captured call takes the static input. The captured call releases the warm-up input during the capture. release_cuda_result logs "An ExecuTorchResult was dropped during a CUDA graph capture" and never frees the memory.
    • The caller did what runtime/cuda.py:48-50 asks: "drop them before or after the capture".
    • PyMethod::set_inputs does the same to the inputs it keeps (4824-4829).
    • The module-wide output_tensors_.clear() (4190) does it to outputs that another method left there, when a method with planned outputs is captured.
    • At least document this, so that the last call before a capture uses the captured inputs. Fix this →
  • The first call of a method during a capture is not refused.
    • run_method calls module_->load_method() (3870) without checking for a capture.
    • Loading allocates the planned device buffers with DeviceMemoryBuffer::create (extension/module/module.cpp:480), which is a cudaMalloc on the capturing thread.
    • In global and thread_local mode that ends the capture. The caller sees "Failed to execute method ..., error: 0x..." instead of the clear refusal that every other allocation gets.
    • Fix: refuse the call when caller_stream_is_capturing() is true and !module_->is_method_loaded(method_name). Fix this →
  • gets_device_memory (4134-4163) repeats the output rules of allocate_output_tensors (4192-4260).
    • It exists only so that the capture refusal runs before output_tensors_.clear().
    • If the two copies drift apart, one of two things happens. Either a call is refused although it allocates nothing, or it is refused only after the clear has dropped, and so leaked, the previous outputs.
    • Fix: build the outputs in a local vector and move it in at the end, as PyMethod::allocate_output_storages does (5501-5503). The refusal in allocate_device_output (2430) then leaves the old outputs untouched, and the helper can go.
    • The cost is holding the previous outputs until the new ones exist, which PyMethod already does. Fix this →

Testing

  • test_empty_cache_releases_dropped_upload_memory depends on the whole GPU (extension/pybindings/test/test_pybindings_cuda_dlpack.py:1598-1601).
    • It checks free memory for the whole device with torch.cuda.mem_get_info.
    • If another process takes more than about 56 MiB of the GPU between the two reads, the test fails. Another test worker creating its CUDA context is enough.
    • Fix: measure only this process's GPU memory instead. Fix this →

API Design

  • PyMethod's capture refusals ignore outputs bound with set_output(), even though the device-output refusal message recommends binding (pybindings.cpp:2422).
    • refuse_clone_outputs_during_capture (2389-2408) refuses the default clone_outputs=True whenever the MethodMeta has a GPU output. It does so even if every GPU output is bound and read_outputs would clone none of them (5080-5103).
    • refuse_new_device_outputs_during_capture (5484-5490) and replace_held_device_outputs (5564-5582) do not skip is_bound_output(i).
    • set_output() also keeps the slot's old buffer (4837-4838).
    • Together, these mean an output bound after a first run is still refused during a capture while that run's result is held. Outside a capture, the same output gets a new buffer that the run never writes. Fix this →
  • The empty_cache() docstring understates what it releases (runtime/cuda.py:250).
    • It says the function gives back memory "that dropped results no longer use".
    • In fact, cudaMemPoolTrimTo(pool, 0) (extension/pybindings/pybindings_cuda.h:296) releases everything unused in the pool. The CUDA delegates share that pool (extension/pybindings/README.md:208), so their next run grows it again.
    • Fix: say this in the docstring. Fix this →

Thread Safety

  • Blocking: an upload or copy now waits for the whole device, on whatever thread makes it. That wait ends a CUDA graph capture on another thread.
    • What happens: allocate_cuda_result runs cudaDeviceSynchronize whenever a dropped result is pending on the device (extension/pybindings/pybindings_cuda.h:146-154). It checks only the calling thread's selected stream (129). A wait for the whole device is invalid in every capture mode while any stream on that device is capturing. So the wait ends the capture, and the upload throws.
    • Why it is a regression: the DroppedCudaResults comment (53-58) keeps this wait out of drops. The PR moves it to the next allocation, on any thread. The README (extension/pybindings/README.md:219-220) documents the wait but not this effect.
      • Before this PR, from_host() on another thread made a cudaMalloc and a copy on the legacy stream. thread_local and relaxed captures on a non-blocking stream allow both.
      • The PR's own test notes that torch.compile's reduce-overhead mode captures this way, and that a device wait on another thread ends such a capture (test_pybindings_cuda_dlpack.py:1576-1577).
    • Trigger: a prefetch thread calls from_host() for the next batch. Meanwhile the main thread, which has dropped an earlier result, captures. Method calls on the prefetch thread already waited for the device, but a thread that only uploads did not.
    • Missing test: the test at 1565 drops results on the other thread but never uploads there.
    • Fix:
      • Free pending drops only when allocate_async fails: wait, free, then retry once. This keeps the common path free of waits and leaves the rest to the waits that calls, to_host() and empty_cache() already make.
      • Add a test that uploads on another thread during a thread_local capture while a drop is pending.
      • Wherever a wait stays, clear the error after a failed cudaDeviceSynchronize (147-152), as the guard failure does at 141. Otherwise the next CUDA call on that thread reports the error, and that call may be torch's. Fix this →
  • The README misstates which drops on another thread are safe during a capture (extension/pybindings/README.md:224-225).
    • It says that dropping "such a result" on another thread "makes no CUDA call that could end the capture". The sentence right before it is about "a result or method output".
    • A method output whose memory the bindings allocated is freed through delete kept (pybindings.cpp:2446), which calls cudaFree. A global capture refuses cudaFree on every thread, and global is the default of torch.cuda.graph.
    • runtime/cuda.py:55-58 also warns that letting go of the last owner of a method during any capture ends the capture.
    • Fix: limit the sentence to from_host() results and copies, as runtime/cuda.py:50-53 does. Fix this →
  • Latent: free_dropped_cuda_results collects the blocks after the wait (pybindings_cuda.h:84-103, called at 153 and 251).
    • A block dropped while cudaDeviceSynchronize runs is therefore freed without the wait that the function's own contract requires (82-83).
    • Today the GIL keeps the two apart: the waits hold it, and the DLPack deleters acquire it.
    • A natural later change is to release the GIL around a long wait. Then the pool could hand out memory that a torch side stream still reads.
    • Fix: collect the blocks before the wait. Fix this →

Performance

  • Low confidence: every peer now gets access to every pool up front.
    • mem_pool_for grants every capable peer read-write access to each device's pool (extension/cuda/cuda_allocator.cpp:142-176).
    • The CUDA delegates share the pool. Every growth of the pool therefore has to map the new memory on every peer, not only memory handed to another library. That includes the regrowth after empty_cache().
    • For comparison, torch's cudaMallocAsync backend grants pool access per device pair, when it first enables peer access between them.
    • If the cost was measured on a host with many GPUs, please say so in the comment. Otherwise, consider granting access lazily.

Recommendation

Request Changes

The wait on the allocation path brings back the cross-thread device wait that the PR removes from drops. It breaks thread_local captures that worked before, and the fix is small. Correct the README sentence at the same time. The other findings can follow up.

  • Load the /pr-review skill and gather PR context (2 commits, a25b0d9 and e7c6b3a, diffed against the PR parent e1d2e24 because the shallow checkout has no merge base with origin/main)
  • Run three independent reviews (29 candidate findings in total)
  • Consolidate the findings (21 unique; 5 were raised by two or three reviewers)
  • Fact-check the findings (10 reported; the rest were merged into them or dropped as invalid, too minor or speculative)
  • Post the final review

Copilot AI balanced review requested due to automatic review settings December 3, 2026 10:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 57m 44s —— View job


PR Review: #25624

Request Changes for two README statements that contradict the code: a copy of a CUDA result on another thread ends a thread_local capture, and dropped results keep their memory from torch and method outputs until the bindings' next wait. The other four findings are minor.

Detailed review

Summary

The PR moves ExecuTorchResult uploads and copies onto the CUDA allocator's stream-ordered pool, with drops freed after the next device wait. It also lets a method call be recorded into a CUDA graph that the selected stream captures.

Problems found:

  • two README statements don't match the code;
  • a module docstring and a test fall short;
  • two minor issues remain.

Scope: diffed against the PR parent e1d2e24, because the shallow checkout has no merge base with origin/main. All 9 changed files were covered. Nothing was built or run, since the runner has no GPU.

Code Quality

  • A refused PyMethod call still drops the results cached for get_outputs() (extension/pybindings/pybindings.cpp:5460).
    • refuse_new_device_outputs_during_capture clears handed_outputs_ and only then decides whether to refuse.
    • The scenario:
      • r = method(x) runs before the capture, and the caller keeps r.
      • method(x, clone_outputs=False) is refused during the capture.
      • After the capture, method.get_outputs() no longer returns r. hand_over_device_output finds the buffer still held (5344), so the caller gets a new copy, which allocates and waits.
    • This contradicts the comment at 5446-5448 ("changes nothing") and the description ("refused calls keep the capture, outputs and inputs as they were").
    • test_refused_calls_during_a_capture_change_nothing misses it because it reads only with clone_outputs=False (559-565).
    • Fix: keep the cache through a refusal. Otherwise, say in the comment, the test and the description that a refused call lets go of it. Fix this →
  • A retry that succeeds still logs an allocation failure at Error level (extension/pybindings/pybindings_cuda.h:141-153, extension/cuda/cuda_allocator.cpp:691-698).
    • When the pool can't grow, allocate_async logs cudaMallocFromPoolAsync failed: out of memory. Only then does allocate_result_memory free the dropped memory and retry successfully.
    • So a process near the memory limit prints an out-of-memory error for every upload that took the retry and succeeded.
    • Fix: make the first attempt without the log, and log only if the retry fails too. Fix this →

Testing

  • test_full_pool_takes_back_dropped_upload_memory passes even if the retry never runs (extension/pybindings/test/test_pybindings_cuda_dlpack.py:1683-1704).
    • It has no assertion, and it sizes the filler from device-wide free memory (mem_get_info, 1692), which other processes change.
    • If another process frees memory after the measurement, the second upload grows the pool and the test passes without reaching the retry. If another process allocates memory, the test fails.
    • While the filler is held, other processes on the GPU have almost no free memory.
    • Fix: assert that the second upload reuses the first one's address, as lines 1649-1650 do. Fix this →

API Design

  • The executorch.runtime.cuda docstring offers load_method() before a capture as a way to keep a method's first call from being refused, but loading alone isn't enough when its GPU outputs aren't memory-planned (runtime/cuda.py:52-54).
    • The first call of a method from load_method() allocates those outputs (allocate_output_storages, pybindings.cpp:5519-5522).
    • allocate_device_output refuses that allocation during a capture (2436).
    • The refusal message (2425-2428) gives the right advice: run the method once before the capture.
    • Fix: say in the docstring that such a method must be called once before the capture. Fix this →

Thread Safety

  • The README says a copy on another thread does not end a thread_local capture, but a copy of a CUDA result always waits for the whole device (extension/pybindings/README.md:226-228).
    • The README says "an upload or copy on another thread waits only when the pool runs out".
    • In fact, two copies always call synchronize_cuda_device:
      • copy_to of a CUDA result, which serves __dlpack__(copy=True) (pybindings_executorch_result.h:607-612);
      • the clone_outputs=True clone (:193).
    • That call is a cudaDeviceSynchronize, which ends a capture on any thread and in any capture mode. The test comment at test_pybindings_cuda_dlpack.py:1633-1634 says the same.
    • So __dlpack__(stream=-1, copy=True) of a CUDA result on another thread ends a torch.compile reduce-overhead capture, which is exactly the case the sentence calls safe.
    • Only uploads from the host, through from_host() or to_device(), wait just when the pool runs out.
    • Copies waited before this PR too, so the defect is the new sentence, not the code.
    • Fix: limit the sentence to uploads from the host, say that copies of a CUDA result always wait, and add to_device() to the pool users listed at 206-208. Fix this →

Backward Compatibility

  • Memory of dropped results is unavailable to torch and to method outputs until the bindings' next wait (extension/pybindings/pybindings_cuda.h:121-154).
    • release_cuda_result only records the block. Only allocate_result_memory drains the list, and only when its own allocation fails.
    • Before this PR, a drop called cudaFree, so the memory was free at once.
    • Now these can fail with out-of-memory while dropped results still hold the memory:
      • A torch cudaMalloc, for example del upload; torch.empty(n, device="cuda") on a nearly full GPU. torch.cuda.empty_cache() doesn't fix it.
      • A method output from allocate_device_output (pybindings.cpp:2432-2438). Module.run_method allocates its outputs at 3903, before the wait at 3962 that would free the dropped memory.
    • README 247-249 says CUDA hands unused pool memory to a cudaMalloc. That doesn't cover these blocks, which haven't been freed into the pool yet.
    • The description says GPUs without memory pools "keep the old code". They don't: allocate_async falls back to allocate_without_pools (extension/cuda/cuda_allocator.cpp:673-678), and their drops are deferred the same way.
    • Fix: say in the README when this memory comes back, and correct the description. It comes back after the next wait or after executorch.runtime.cuda.empty_cache(). The waits are a call with CUDA inputs or outputs, to_host(), or a __dlpack__ without stream=-1. Fix this →

Recommendation

Request 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
  • Load the /pr-review skill and gather PR context: 2 commits (85e110b, 3a87f95), diffed against the PR parent e1d2e24; 9 files, +948/−21
  • Run three independent reviews (39 candidate findings)
  • Consolidate them (about 12 unique findings)
  • Fact-check them against the code: 6 kept; the rest dropped as invalid, too minor, or already raised in an earlier round
  • Post this review

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. release notes: api Changes to public facing apis (any interfaces, pybinded runtime methods, etc.)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants