Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions extension/cuda/cuda_allocator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,42 @@ cudaMemPool_t mem_pool_for(int device) {
(void)cudaGetLastError();
}

// A peer device can use cudaMalloc memory once peer access is enabled, but
// pool memory only after the pool grants it access. Libraries such as torch
// read and write memory handed to them from kernels and copies on any device.
int count = 0;
if (cudaGetDeviceCount(&count) != cudaSuccess) {
(void)cudaGetLastError();
count = 0;
}
for (int peer = 0; peer < count; ++peer) {
int can_access = 0;
if (peer == device) {
continue;
}
if (cudaDeviceCanAccessPeer(&can_access, peer, device) != cudaSuccess) {
(void)cudaGetLastError();
continue;
}
if (can_access == 0) {
continue;
}
cudaMemAccessDesc access{};
access.location.type = cudaMemLocationTypeDevice;
access.location.id = peer;
access.flags = cudaMemAccessFlagsProtReadWrite;
err = cudaMemPoolSetAccess(pool, &access, 1);
if (err != cudaSuccess) {
ET_LOG(
Error,
"Granting device %d access to the pool of device %d failed: %s",
peer,
device,
cudaGetErrorString(err));
(void)cudaGetLastError();
}
}

state.pools.emplace(device, pool);
return pool;
}
Expand Down
4 changes: 2 additions & 2 deletions extension/cuda/cuda_allocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ class EXECUTORCH_EXTENSION_CUDA_API CudaAllocator final
* The shared memory pool this allocator uses on a device, or nullptr if it
* has not allocated there or the pool could not be created.
*
* Exposed so a test can observe what the pool is holding, which is not
* visible through the device default pool. No production caller.
* Exposed so a caller can observe or trim this pool alone, which is not
* visible through the device default pool.
*
* Not declared on ROCm: the pool code is compiled out there, so there is
* nothing to observe and the pool type needs no HIP alias.
Expand Down
5 changes: 5 additions & 0 deletions extension/cuda/test/cuda_allocator_exit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ cudaError_t cudaGetDevice(int* device) {
return cudaSuccess;
}

cudaError_t cudaGetDeviceCount(int* count) {
*count = 1;
return cudaSuccess;
}

cudaError_t cudaMalloc(void** ptr, size_t) {
*ptr = storage + 256;
return cudaSuccess;
Expand Down
52 changes: 50 additions & 2 deletions extension/pybindings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,11 @@ and import torch to do so unless `EXECUTORCH_PYBINDINGS_TENSOR_OUTPUT` is
CUDA inputs, torch tensors or DLPack, and return borrowed CUDA results.

Execution is synchronous at the Python boundary: a call returns after its device
work has finished, so its outputs are ready on any stream. How long a call with
only host inputs and outputs waits depends on where it runs:
work has finished, so its outputs are ready on any stream. The exception is a
call while the stream selected with `executorch.runtime.cuda.stream()` captures
a CUDA graph: it does not wait, and the graph writes its outputs when it
replays, as the `executorch.runtime.cuda` documentation describes. How long a
call with only host inputs and outputs waits depends on where it runs:

- Inside an `executorch.runtime.cuda.stream()` block with a non-blocking stream,
such as `executorch.runtime.cuda.Stream()`, it waits for that stream. A
Expand Down Expand Up @@ -200,6 +203,51 @@ that needs the GIL makes the wait hang. Bindings built without CUDA wait through
short: `cudaDeviceSynchronize` took a median of 1.5 microseconds on an A100. The
synchronization has no C++ ATen dependency.

On a device with memory pools, `from_host()`, a copy that `clone_outputs=True`
makes of a CUDA output into an `ExecuTorchResult`, and `__dlpack__(copy=True)`
take their memory from the pool that the CUDA delegates use, so making and
dropping them does not call `cudaMalloc` or `cudaFree`. In torch output mode
such a copy is a torch tensor from torch's own allocator. Output memory that the
bindings allocate for a call still uses `cudaMalloc` and `cudaFree`. An output
returned without a copy can also be the memory of an input, such as a
`from_host()` result. Pool memory cannot be shared with another process through
`cudaIpcGetMemHandle`, so copy it into a torch tensor first for that.

Dropping a result that uses the pool makes no CUDA call. Its memory goes back
to the pool after the next wait for its device, such as the wait of a method
call or of `to_host()`, since work on another stream, such as a torch side
stream, may still use it. If the pool cannot grow while dropped memory is
still waiting, `from_host()` and the copies above wait for the device, give
that memory back, and try once more. While the stream selected with
`executorch.runtime.cuda.stream()` captures a CUDA graph, a result or method
output dropped on that thread keeps its memory until the process exits, since
the graph may still use it, so drop results before or after a capture. A
`from_host()` result or a copy above, dropped on another thread, makes no CUDA
call, so it cannot end the capture. An upload or copy on another thread waits
only when the pool runs out, so it does not end a `thread_local` capture, such
as the one `torch.compile` makes in `reduce-overhead` mode. A method output
whose memory the bindings allocated is freed with `cudaFree`, which a `global`
capture refuses on every thread, so keep method outputs alive until the capture
ends.

Like torch's allocator, the pool keeps freed memory reserved for later results
and delegates of the same process. Other processes on the same GPU cannot use
reserved memory: after dropping a 16 GiB result, the process still holds
16 GiB of the device. As `torch.cuda.empty_cache()` does for torch,
`executorch.runtime.cuda.empty_cache()` gives the unused memory back to the
GPU:

```python
from executorch.runtime import cuda

del device_input
cuda.empty_cache()
```

The pool also gives memory back when the last CUDA delegate is destroyed. In
the same process, CUDA takes unused pool memory back when a `cudaMalloc`, such
as one from torch, needs it.

For bfloat16 inputs, raw byte buffers use the shape declared by the exported
method. NumPy and PEP 3118 do not define bfloat16, so the buffer protocol shows
a bfloat16 result as 16-bit unsigned integers in its real shape and layout.
Expand Down
Loading
Loading