diff --git a/extension/cuda/cuda_allocator.cpp b/extension/cuda/cuda_allocator.cpp index c3837a703ae..b69988abd07 100644 --- a/extension/cuda/cuda_allocator.cpp +++ b/extension/cuda/cuda_allocator.cpp @@ -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; } diff --git a/extension/cuda/cuda_allocator.h b/extension/cuda/cuda_allocator.h index 2c55785076a..706008ee550 100644 --- a/extension/cuda/cuda_allocator.h +++ b/extension/cuda/cuda_allocator.h @@ -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. diff --git a/extension/cuda/test/cuda_allocator_exit.cpp b/extension/cuda/test/cuda_allocator_exit.cpp index 6370f3ca445..50ecc0137d1 100644 --- a/extension/cuda/test/cuda_allocator_exit.cpp +++ b/extension/cuda/test/cuda_allocator_exit.cpp @@ -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; diff --git a/extension/pybindings/README.md b/extension/pybindings/README.md index 5413562e09b..5b18143eef2 100644 --- a/extension/pybindings/README.md +++ b/extension/pybindings/README.md @@ -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 @@ -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. diff --git a/extension/pybindings/pybindings.cpp b/extension/pybindings/pybindings.cpp index 0649d79a395..b4891e12133 100644 --- a/extension/pybindings/pybindings.cpp +++ b/extension/pybindings/pybindings.cpp @@ -1740,8 +1740,18 @@ py::object dlpack_capsule( // and torch reads that from its own state, so a torch that can use CUDA is // asked to switch. py::object cuda_dlpack_capsule(const py::object& producer, int index) { - const auto request = [&producer] { - return dlpack_capsule(producer, py::int_(1)); + py::object stream = py::int_(1); +#ifdef EXECUTORCH_PYBINDINGS_CUDA + // The producer makes the requested stream wait for its work. During a + // capture the call runs on the selected stream, and a wait on the legacy + // default stream would end the capture. + if (caller_stream_is_capturing()) { + stream = py::int_(reinterpret_cast( + *executorch::extension::cuda::getCallerStream())); + } +#endif + const auto request = [&producer, &stream] { + return dlpack_capsule(producer, stream); }; PyObject* torch = loaded_torch_module(); const auto torch_cuda = torch == nullptr @@ -2372,15 +2382,75 @@ py::sequence normalize_inputs(const py::object& inputs) { return py::reinterpret_borrow(inputs); } +// Copying a GPU output waits for the GPU, and a method that ran before hands +// over the buffer that every replay writes, so neither gives the independent +// result that clone_outputs=True promises. Refused before the call records +// anything. Copies of CPU outputs need no GPU, so they stay allowed, and so do +// outputs that live in a caller's tensor (`caller_backed`), which are never +// copied. +void refuse_clone_outputs_during_capture( + bool clone_outputs, + const MethodMeta& method_meta, + const std::vector& caller_backed = {}) { + if (!clone_outputs || !caller_stream_is_capturing()) { + return; + } + for (size_t i = 0; i < method_meta.num_outputs(); ++i) { + if (i < caller_backed.size() && caller_backed[i]) { + continue; + } + const auto tag = method_meta.output_tag(i); + if (!tag.ok() || tag.get() != Tag::Tensor) { + continue; + } + const auto output = method_meta.output_tensor_meta(i); + if (output.ok() && !output->device().is_cpu()) { + throw std::invalid_argument( + "clone_outputs=True is not supported for a method with GPU outputs " + "while the selected stream captures a CUDA graph. Call the method " + "with clone_outputs=False"); + } + } +} + #ifndef USE_ATEN_LIB +// A relaxed capture lets cudaMalloc through, and the graph would keep writing +// the block after the output's owner frees it. +void refuse_device_output_during_capture(size_t index) { + if (caller_stream_is_capturing()) { + throw std::invalid_argument( + "Output " + std::to_string(index) + + " needs new GPU memory during a CUDA graph capture on the selected " + "stream, and the graph would keep writing that memory after the " + "output is freed. Export the method with memory-planned outputs, or " + "capture a method from load_method(): run it once before the capture " + "and let go of the results it returned, so this call reuses that " + "memory, or bind the output with set_output()"); + } +} + std::shared_ptr allocate_device_output( size_t index, size_t nbytes, executorch::aten::Device device) { + refuse_device_output_during_capture(index); auto buffer = DeviceMemoryBuffer::create(nbytes, device.type(), device.index()); THROW_IF_ERROR(buffer.error(), "Failed to allocate device output %zu", index); - return std::make_shared(std::move(buffer.get())); + return std::shared_ptr( + new DeviceMemoryBuffer(std::move(buffer.get())), + [](DeviceMemoryBuffer* kept) { + // As in release_cuda_result, the graph may still use the memory, and + // cudaFree can end the capture. + if (caller_stream_is_capturing()) { + ET_LOG( + Error, + "A method output was dropped during a CUDA graph capture; its " + "memory is not freed"); + return; + } + delete kept; + }); } // Bindings built without CUDA support wait for CUDA work through torch, which @@ -2403,6 +2473,8 @@ void synchronize_device_for_call(int index) { // output from an earlier run, such as a dropped result's buffer or a // memory-planned output, which this run writes again. After the run, its // outputs, and any input it updated in place, are ready on every stream. +// While the selected stream captures a CUDA graph, the capture orders the run +// instead; see caller_stream_is_capturing(). void synchronize_tensor_devices(const Method& method) { std::vector devices; const auto add = [&devices](const EValue& value) { @@ -2422,6 +2494,9 @@ void synchronize_tensor_devices(const Method& method) { for (size_t i = 0; i < method.outputs_size(); ++i) { add(method.get_output(i)); } + if (devices.empty() || caller_stream_is_capturing()) { + return; + } for (const auto index : devices) { synchronize_device_for_call(index); } @@ -3568,6 +3643,16 @@ struct PyModule final { "Failed to get metadata for method %s", method_name.c_str()); const auto method_meta = method_meta_result.get(); + refuse_clone_outputs_during_capture(clone_outputs, method_meta); + // Loading allocates the method's GPU memory, which would end the capture. + if (caller_stream_is_capturing() && + !module_->is_method_loaded(method_name)) { + throw std::invalid_argument( + "Method '" + method_name + + "' is not loaded, and loading it allocates GPU memory, which the " + "CUDA graph capture on the selected stream does not allow. Call the " + "method, or load it with load_method(), before the capture"); + } // Checked before anything is installed: an extra input would otherwise // install every real one and then fail, blocking later partial calls. if (inputs_size > method_meta.num_inputs()) { @@ -4072,18 +4157,20 @@ struct PyModule final { auto method_meta = method_meta_result.get(); const auto num_outputs = method_meta.num_outputs(); - // Create a buffer for each output tensor. Memory planned outputs and non // tensor outputs get an empty buffer in this list which is ignored later. - output_tensors_.clear(); - output_tensors_.reserve(num_outputs); + // Built in a local and moved in only once every output has its buffer, so + // an allocation refused during a CUDA graph capture leaves the previous + // outputs in place: dropped during a capture, they would keep their memory. + std::vector> output_tensors; + output_tensors.reserve(num_outputs); for (size_t i = 0; i < num_outputs; ++i) { auto output_type = method_meta.output_tag(i); THROW_IF_ERROR( output_type.error(), "Failed to get output type for output %zu", i); if (output_type.get() != Tag::Tensor) { // Skip allocating storage for non-tensor outputs. - output_tensors_.emplace_back(std::nullopt); + output_tensors.emplace_back(std::nullopt); continue; } const auto& output_tensor_meta = method_meta.output_tensor_meta(i); @@ -4093,7 +4180,7 @@ struct PyModule final { i); if (output_tensor_meta.get().is_memory_planned()) { // Skip allocating storage for planned memory outputs. - output_tensors_.emplace_back(std::nullopt); + output_tensors.emplace_back(std::nullopt); continue; } const auto method = module_->method(method_name); @@ -4109,7 +4196,7 @@ struct PyModule final { } if (is_input) { // The shared value receives its storage from set_inputs(). - output_tensors_.emplace_back(std::nullopt); + output_tensors.emplace_back(std::nullopt); continue; } #ifndef USE_ATEN_LIB @@ -4134,7 +4221,7 @@ struct PyModule final { .device(device) .deleter([allocation](void*) {}) .make_tensor_ptr(); - output_tensors_.emplace_back(std::move(tensor)); + output_tensors.emplace_back(std::move(tensor)); continue; } #endif @@ -4144,9 +4231,11 @@ struct PyModule final { output_tensor_meta->sizes().end()), std::vector(output_tensor_meta->nbytes()), output_tensor_meta->scalar_type()); - output_tensors_.emplace_back(std::move(tensor_ptr)); + output_tensors.emplace_back(std::move(tensor_ptr)); } + output_tensors_ = std::move(output_tensors); + for (size_t i = 0; i < output_tensors_.size(); ++i) { if (output_tensors_[i].has_value()) { // Set output tensors on module. @@ -4851,6 +4940,7 @@ struct PyMethod final { "old inputs. Call set_inputs() again with every input before " "executing."); } + refuse_new_device_outputs_during_capture(); outputs_valid_ = false; handed_outputs_.clear(); for (const auto& input : borrowed_inputs_) { @@ -4931,6 +5021,8 @@ struct PyMethod final { py::list get_outputs(bool clone_outputs = true) { ObjectLock lock(mutex_); + refuse_clone_outputs_during_capture( + clone_outputs, storage_->method->method_meta(), caller_outputs_); if (!outputs_valid_) { throw std::runtime_error( "Method '" + std::string(storage_->method->method_meta().name()) + @@ -4942,6 +5034,9 @@ struct PyMethod final { py::list call(const py::object& inputs, bool clone_outputs = true) { ObjectLock lock(mutex_); + refuse_clone_outputs_during_capture( + clone_outputs, storage_->method->method_meta(), bound_outputs_); + refuse_new_device_outputs_during_capture(); set_inputs(inputs); const auto output = tensor_output(bound_outputs_); execute_installed(/*inputs_just_installed=*/true); @@ -5348,6 +5443,32 @@ struct PyMethod final { } #endif + // replace_held_device_outputs() refuses new GPU memory during a capture only + // after the call has installed its inputs and dropped its outputs, so a call + // that would need it is refused here first and changes nothing. A method's + // first call has no outputs yet, and its inputs decide which outputs need + // memory, so allocate_output_storages() refuses that one itself. + void refuse_new_device_outputs_during_capture() { +#ifndef USE_ATEN_LIB + if (!caller_stream_is_capturing() || + storage_->output_storages.size() != storage_->method->outputs_size()) { + return; + } + // The call lets go of the results kept for get_outputs() anyway, and that + // frees nothing, since each slot keeps its buffer. A buffer that a result + // still holds after that needs a new one, unless its spare is free. + handed_outputs_.clear(); + for (size_t i = 0; i < storage_->device_output_storages.size(); ++i) { + const auto& spare = spare_device_outputs_[i]; + if (storage_->device_output_storages[i] && !is_bound_output(i) && + !handed_buffers_[i].expired() && + !(spare.buffer && spare.handed.expired())) { + refuse_device_output_during_capture(i); + } + } +#endif + } + void allocate_output_storages() { const auto num_outputs = storage_->method->outputs_size(); if (storage_->output_storages.size() == num_outputs) { @@ -5419,7 +5540,8 @@ struct PyMethod final { #ifndef USE_ATEN_LIB for (size_t i = 0; i < storage_->device_output_storages.size(); ++i) { auto& buffer = storage_->device_output_storages[i]; - if (!buffer || handed_buffers_[i].expired()) { + // A bound output is written into the caller's tensor, not this buffer. + if (!buffer || is_bound_output(i) || handed_buffers_[i].expired()) { continue; } const auto device = storage_->method->get_output(i).toTensor().device(); @@ -5831,6 +5953,7 @@ PYBIND11_MODULE(EXECUTORCH_PYTHON_MODULE_NAME, m) { const py::object&, const py::object&, const py::object&) { scope.exit(); }); + m.def("_empty_cache", &empty_cuda_cache, call_guard); #endif #ifdef USE_ATEN_LIB diff --git a/extension/pybindings/pybindings_cuda.h b/extension/pybindings/pybindings_cuda.h index bf852c2348e..f13a10a2755 100644 --- a/extension/pybindings/pybindings_cuda.h +++ b/extension/pybindings/pybindings_cuda.h @@ -8,12 +8,17 @@ #pragma once +#include #include #include +#include #include #include +#include +#include #ifdef EXECUTORCH_PYBINDINGS_CUDA +#include #include #include #include @@ -21,12 +26,170 @@ namespace executorch::extension::pybindings { -inline std::shared_ptr allocate_cuda_result(size_t nbytes, int index) { +// Whether the stream selected with executorch.runtime.cuda.stream() is +// capturing a CUDA graph. Nothing runs during a capture, so the boundary has +// nothing to wait for: the capture orders a call after the work recorded on +// that stream before it, and before the work recorded after it. A device wait +// would also end the capture. A failed query counts as no capture, so the call +// goes on as it would outside one. +inline bool caller_stream_is_capturing() { #ifdef EXECUTORCH_PYBINDINGS_CUDA + const auto stream = executorch::extension::cuda::getCallerStream(); + if (!stream.has_value()) { + return false; + } + cudaStreamCaptureStatus capture = cudaStreamCaptureStatusNone; + if (cudaStreamIsCapturing(*stream, &capture) != cudaSuccess) { + (void)cudaGetLastError(); + return false; + } + return capture != cudaStreamCaptureStatusNone; +#else + return false; +#endif +} + +#if defined(EXECUTORCH_PYBINDINGS_CUDA) && !defined(EXECUTORCH_USE_HIP) +// Memory of dropped results, freed after the next wait for its device. Another +// library may still use a dropped result's memory on a stream the default +// stream does not wait for, such as a torch side stream, and the pool would +// hand it out again at once. A drop runs on whatever thread lets go of the last +// reference, and waiting there would end a CUDA graph capture on another +// thread, so the drop only records the memory. +struct DroppedCudaResults { + std::mutex mutex; + std::vector> blocks; +}; + +inline DroppedCudaResults& dropped_cuda_results() { + // Never destroyed: results can still be dropped while the process exits. + static auto* dropped = new DroppedCudaResults(); + return *dropped; +} + +inline bool has_dropped_cuda_results(int index) { + auto& dropped = dropped_cuda_results(); + const std::lock_guard lock(dropped.mutex); + for (const auto& block : dropped.blocks) { + if (block.second == index) { + return true; + } + } + return false; +} + +/// Waits for device `index`, which must be selected, then gives the memory of +/// results dropped before the wait started back to the pool. Results dropped +/// during the wait stay recorded for the next one. If the wait fails, the +/// memory stays recorded and the error is cleared, so the next CUDA call, even +/// in another library, does not report it. +inline cudaError_t synchronize_and_free_dropped_cuda_results(int index) { + auto& dropped = dropped_cuda_results(); + std::vector freed; + { + const std::lock_guard lock(dropped.mutex); + auto& blocks = dropped.blocks; + for (auto it = blocks.begin(); it != blocks.end();) { + if (it->second == index) { + freed.push_back(it->first); + it = blocks.erase(it); + } else { + ++it; + } + } + } + const auto status = cudaDeviceSynchronize(); + if (status != cudaSuccess) { + (void)cudaGetLastError(); + const std::lock_guard lock(dropped.mutex); + for (void* data : freed) { + dropped.blocks.emplace_back(data, index); + } + return status; + } + for (void* data : freed) { + executorch::extension::cuda::CudaAllocator::deallocate_async( + data, index, nullptr); + } + return cudaSuccess; +} + +/// Records memory from allocate_cuda_result for +/// synchronize_and_free_dropped_cuda_results. +/// Memory dropped while the selected stream captures a CUDA graph is kept, +/// since the graph may still use it. +inline void release_cuda_result(void* data, int index) { + if (caller_stream_is_capturing()) { + ET_LOG( + Error, + "An ExecuTorchResult was dropped during a CUDA graph capture; its " + "memory is not freed"); + return; + } + auto& dropped = dropped_cuda_results(); + const std::lock_guard lock(dropped.mutex); + dropped.blocks.emplace_back(data, index); +} + +/// Memory for allocate_cuda_result, on the default stream, which the copies +/// into and out of results use. A device wait would end a CUDA graph capture on +/// another thread, so the memory of dropped results is taken back only when the +/// pool cannot grow without it. +inline executorch::runtime::Result allocate_result_memory( + size_t nbytes, + int index) { + auto allocation = executorch::extension::cuda::CudaAllocator::allocate_async( + nbytes, index, nullptr); + if (allocation.ok() || !has_dropped_cuda_results(index)) { + return allocation; + } + const auto status = synchronize_and_free_dropped_cuda_results(index); + if (status != cudaSuccess) { + throw std::runtime_error( + std::string("Failed to synchronize CUDA device ") + + std::to_string(index) + ": " + cudaGetErrorString(status)); + } + return executorch::extension::cuda::CudaAllocator::allocate_async( + nbytes, index, nullptr); +} +#endif + +// Memory for uploads, clones and DLPack copies. Callers make and drop these on +// every call, and cudaMalloc and cudaFree can each wait in the driver behind +// other processes, so on a device with memory pools they use the CUDA +// allocator's pool, which keeps freed memory for later allocations. ROCm builds +// keep cudaMalloc and cudaFree, since the ROCm allocator has no fallback for a +// device without memory pools. +inline std::shared_ptr allocate_cuda_result(size_t nbytes, int index) { + if (caller_stream_is_capturing()) { + throw std::invalid_argument( + "An ExecuTorchResult needs new GPU memory during a CUDA graph capture " + "on the selected stream, and the graph could keep using that memory " + "after the result is freed. Make uploads and copies before the " + "capture"); + } +#if defined(EXECUTORCH_PYBINDINGS_CUDA) && !defined(EXECUTORCH_USE_HIP) + // The allocator serves the pool of the current device, so this also keeps the + // memory on the requested device. + auto guard = executorch::extension::cuda::CUDAGuard::create(index); + if (!guard.ok()) { + (void)cudaGetLastError(); + throw std::runtime_error( + "Failed to select CUDA device " + std::to_string(index)); + } + auto allocation = allocate_result_memory(nbytes, index); + if (!allocation.ok()) { + throw std::runtime_error( + "Failed to allocate CUDA memory for an ExecuTorchResult"); + } + return std::shared_ptr(allocation.get(), [index](void* data) { + release_cuda_result(data, index); + }); +#elif defined(EXECUTORCH_PYBINDINGS_CUDA) && defined(EXECUTORCH_USE_HIP) const auto type = executorch::runtime::etensor::DeviceType::CUDA; auto* allocator = executorch::runtime::get_device_allocator(type); if (allocator == nullptr) { - // Windows ships the allocator without registering the CUDA delegate. + // The CUDA delegate registers the allocator, and may not be linked. allocator = &executorch::extension::cuda::CudaAllocator::instance(); } auto allocation = allocator->allocate(nbytes, index); @@ -35,8 +198,17 @@ inline std::shared_ptr allocate_cuda_result(size_t nbytes, int index) { "Failed to allocate CUDA memory for an ExecuTorchResult"); } return std::shared_ptr( - allocation.get(), - [allocator, index](void* data) { allocator->deallocate(data, index); }); + allocation.get(), [allocator, index](void* data) { + // As in release_cuda_result, the graph may still use the memory. + if (caller_stream_is_capturing()) { + ET_LOG( + Error, + "An ExecuTorchResult was dropped during a CUDA graph capture; " + "its memory is not freed"); + return; + } + allocator->deallocate(data, index); + }); #else (void)nbytes; (void)index; @@ -65,17 +237,38 @@ inline std::shared_ptr allocate_pinned_host_buffer(size_t nbytes) { #endif } +// A device wait cannot finish while the selected stream captures a graph, and +// the failed wait would end the capture, so the call is refused with what to +// change instead. +inline void refuse_device_wait_during_capture() { + if (caller_stream_is_capturing()) { + throw std::invalid_argument( + "This call has to wait for the GPU, which the CUDA graph capture on " + "the selected stream does not allow. Converting a torch input into " + "the exported layout waits, so pass inputs in that layout. " + "ExecuTorchResult.to_host(), get_attribute(), torch.from_dlpack() and " + "other __dlpack__() calls without stream=-1 wait too, so make them " + "outside the capture"); + } +} + // A tensor handed across the Python boundary carries no readiness event, and // another library may write it on any stream, so the boundary waits for the -// whole device, even inside an executorch.runtime.cuda stream block. +// whole device, even inside an executorch.runtime.cuda stream block, except +// while that block's stream captures a CUDA graph. inline void synchronize_cuda_device(int index) { #ifdef EXECUTORCH_PYBINDINGS_CUDA + refuse_device_wait_during_capture(); auto guard = executorch::extension::cuda::CUDAGuard::create(index); if (!guard.ok()) { throw std::runtime_error( "Failed to select CUDA device " + std::to_string(index)); } +#ifndef EXECUTORCH_USE_HIP + const auto status = synchronize_and_free_dropped_cuda_results(index); +#else const auto status = cudaDeviceSynchronize(); +#endif if (status != cudaSuccess) { throw std::runtime_error( std::string("Failed to synchronize CUDA tensor storage: ") + @@ -88,6 +281,53 @@ inline void synchronize_cuda_device(int index) { #endif } +// Gives memory the CUDA allocator's pools hold but no result uses back to the +// GPU, for other processes, as torch.cuda.empty_cache() does for torch. +inline void empty_cuda_cache() { +#if defined(EXECUTORCH_PYBINDINGS_CUDA) && !defined(EXECUTORCH_USE_HIP) + refuse_device_wait_during_capture(); + std::vector devices; + { + auto& dropped = dropped_cuda_results(); + const std::lock_guard lock(dropped.mutex); + for (const auto& block : dropped.blocks) { + devices.push_back(block.second); + } + } + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess) { + (void)cudaGetLastError(); + count = 0; + } + for (int device = 0; device < count; ++device) { + if (executorch::extension::cuda::CudaAllocator::pool_for_device(device) != + nullptr) { + devices.push_back(device); + } + } + std::sort(devices.begin(), devices.end()); + devices.erase(std::unique(devices.begin(), devices.end()), devices.end()); + for (const int device : devices) { + // The first wait queues the frees of dropped results, and a trim gives + // back only memory whose free has finished. + synchronize_cuda_device(device); + synchronize_cuda_device(device); + auto* pool = + executorch::extension::cuda::CudaAllocator::pool_for_device(device); + if (pool == nullptr) { + continue; + } + const auto status = cudaMemPoolTrimTo(pool, 0); + if (status != cudaSuccess) { + (void)cudaGetLastError(); + throw std::runtime_error( + std::string("Failed to release cached CUDA memory: ") + + cudaGetErrorString(status)); + } + } +#endif +} + // Checked before selecting the device: a failed selection leaves an error // pending that the next CUDA call, even in another library, would report. inline void require_cuda_device(int index) { diff --git a/extension/pybindings/pybindings_executorch_result.h b/extension/pybindings/pybindings_executorch_result.h index 05757ecfcd4..88286811c44 100644 --- a/extension/pybindings/pybindings_executorch_result.h +++ b/extension/pybindings/pybindings_executorch_result.h @@ -128,6 +128,7 @@ inline PyObject* loaded_torch_module() { } inline void synchronize_torch_cuda_device(int index) { + refuse_device_wait_during_capture(); py::reinterpret_borrow(loaded_torch_module()) .attr("cuda") .attr("synchronize")(index); diff --git a/extension/pybindings/test/test_pybindings_cuda_dlpack.py b/extension/pybindings/test/test_pybindings_cuda_dlpack.py index ef9b2f13c3c..0d3f2c068f4 100644 --- a/extension/pybindings/test/test_pybindings_cuda_dlpack.py +++ b/extension/pybindings/test/test_pybindings_cuda_dlpack.py @@ -404,6 +404,223 @@ def test_stream_block_leaves_a_graph_capture_intact(self): torch.cuda.synchronize() self.assertEqual(y.tolist(), [6.0] * 4) + def test_call_on_a_capturing_stream_leaves_the_capture_intact(self): + from executorch.runtime import cuda + + # No in-tree delegate can be captured from outside yet, so a program + # without one shows that the call itself keeps the capture intact. + data = self._device_identity(0, torch.ones(2, 3, 4, 5)) + method = self.bindings._load_program_from_buffer(data).load_method("forward") + module = self.bindings._load_for_executorch_from_buffer(data) + from executorch.exir import to_edge + + class AddOne(torch.nn.Module): + def forward(self, value): + return value + 1.0 + + host_program = to_edge(torch.export.export(AddOne(), (torch.ones(2),))) + host_method = self.bindings._load_program_from_buffer( + host_program.to_executorch().buffer + ).load_method("forward") + value = torch.ones(2, 3, 4, 5, device=self.device) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + doubled = value * 2 + stream = torch.cuda.current_stream() + with cuda.stream(stream): + output = method(doubled, clone_outputs=False)[0] + # A wait on any other stream would end the capture. + producer = CudaDLPackOnly(doubled, stream) + produced = method(producer, clone_outputs=False)[0] + # Refused before they record anything, so the capture goes on. + with self.assertRaisesRegex(ValueError, "clone_outputs=True is not"): + method.get_outputs() + with self.assertRaisesRegex(ValueError, "clone_outputs=True is not"): + module.forward(doubled) + # Copying a CPU output needs no GPU. + host = torch.from_dlpack(host_method(torch.ones(2))[0]) + self.assertEqual(producer.requested_streams, [stream.cuda_stream]) + torch.testing.assert_close(host, torch.full((2,), 2.0)) + value.fill_(3.0) + graph.replay() + torch.cuda.synchronize() + for result in (output, produced): + torch.testing.assert_close( + self._tensor(result), torch.full_like(value, 6.0) + ) + + for inputs, clone_outputs, message in ( + (value, True, "clone_outputs=True is not supported"), + # Converting an input's layout waits for the GPU. + (value.to(memory_format=torch.channels_last), False, "has to wait"), + ): + with self.assertRaisesRegex(ValueError, message): + with torch.cuda.graph(torch.cuda.CUDAGraph()): + with cuda.stream(torch.cuda.current_stream()): + method(inputs, clone_outputs=clone_outputs) + + # A relaxed capture lets cudaMalloc through, so only the bindings stop + # an unplanned GPU output from getting new memory. + delegate = self._load_method() + ones = torch.ones(self.shape, device=self.device) + with self.assertRaisesRegex(ValueError, "Output 0 needs new GPU memory"): + with torch.cuda.graph(torch.cuda.CUDAGraph(), capture_error_mode="relaxed"): + with cuda.stream(torch.cuda.current_stream()): + delegate(ones, clone_outputs=False) + + def test_module_outputs_freed_during_a_capture_leave_it_intact(self): + from executorch.runtime import cuda + + program = self.program_path.read_bytes() + data = self.data_path.read_bytes() if self.data_path else None + module = self.bindings._load_for_executorch_from_buffer(program, data) + ones = torch.ones(self.shape, device=self.device) + # The first result becomes the only owner of its output memory, and the + # module the only owner of the second call's. + first = module.forward(ones)[0] + module.forward(ones, clone_outputs=False) + value = torch.ones(self.shape, device=self.device) + graph = torch.cuda.CUDAGraph() + # Torch captures in global mode, where cudaFree ends the capture. + with torch.cuda.graph(graph): + with cuda.stream(torch.cuda.current_stream()): + with self.assertRaisesRegex( + ValueError, "Output 0 needs new GPU memory" + ): + module.forward(ones, clone_outputs=False) + del first + gc.collect() + doubled = value * 2 + value.fill_(3.0) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(doubled, torch.full_like(value, 6.0)) + + def test_results_made_or_dropped_during_a_capture_leave_it_intact(self): + from executorch.runtime import cuda + + count = torch.Size(self.shape).numel() + host = ( + memoryview(array.array("f", [3.0]) * count).cast("B").cast("f", self.shape) + ) + uploaded = self.bindings.ExecuTorchResult.from_host(host, self.device.index) + value = torch.ones(self.shape, device=self.device) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + with cuda.stream(torch.cuda.current_stream()): + # Reading a result back waits for the device. + with self.assertRaisesRegex( + ValueError, r"has to wait.*to_host\(\).*outside the capture" + ): + uploaded.to_host() + # Freeing the memory would wait for the device. + del uploaded + with self.assertRaisesRegex( + ValueError, "An ExecuTorchResult needs new GPU memory" + ): + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + doubled = value * 2 + value.fill_(3.0) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(doubled, torch.full_like(value, 6.0)) + + def test_refused_calls_during_a_capture_change_nothing(self): + import io + + from executorch.runtime import cuda + + program = self.program_path.read_bytes() + data = self.data_path.read_bytes() if self.data_path else None + module = self.bindings._load_for_executorch_from_buffer(program, data) + method = self._load_method() + ones = torch.ones(self.shape, device=self.device) + twos = torch.full(self.shape, 2.0, device=self.device) + # Both of the method's buffers stay with these handed-over results. + held = [method(ones)[0], method(ones)[0]] + expected = self._tensor(held[1]).clone() + # The module is the only owner of this call's output memory. + module.forward(ones, clone_outputs=False) + logs = io.StringIO() + with torch.cuda.graph(torch.cuda.CUDAGraph(), capture_error_mode="relaxed"): + with cuda.stream(torch.cuda.current_stream()): + for call in ( + lambda: method(twos, clone_outputs=False), + method.execute, + lambda: module.forward(twos, clone_outputs=False), + ): + with contextlib.redirect_stderr(logs): + with self.assertRaisesRegex( + ValueError, "Output 0 needs new GPU memory" + ): + call() + # Nothing was dropped, installed or marked stale. + self.assertNotIn("not freed", logs.getvalue()) + torch.testing.assert_close( + self._tensor(method.get_outputs(clone_outputs=False)[0]), expected + ) + method.execute() + torch.testing.assert_close( + self._tensor(method.get_outputs(clone_outputs=False)[0]), expected + ) + + def test_first_module_call_during_a_capture_is_refused(self): + from executorch.runtime import cuda + + program = self.program_path.read_bytes() + data = self.data_path.read_bytes() if self.data_path else None + module = self.bindings._load_for_executorch_from_buffer(program, data) + ones = torch.ones(self.shape, device=self.device) + value = torch.ones(self.shape, device=self.device) + graph = torch.cuda.CUDAGraph() + # Loading a method can allocate its planned GPU memory, which would end + # the capture. + with torch.cuda.graph(graph): + with cuda.stream(torch.cuda.current_stream()): + with self.assertRaisesRegex(ValueError, "is not loaded"): + module.forward(ones, clone_outputs=False) + doubled = value * 2 + value.fill_(3.0) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(doubled, torch.full_like(value, 6.0)) + torch.testing.assert_close( + self._tensor(module.forward(ones)[0]), + torch.full(self.shape, 4.0, device=self.device), + ) + + def test_bound_outputs_are_not_refused_during_a_capture(self): + from executorch.runtime import cuda + from torch.profiler import profile, ProfilerActivity + + method = self._load_method() + ones = torch.ones(self.shape, device=self.device) + wrong = torch.ones(self.shape[0] // 2, self.shape[1], device=self.device) + # This result keeps the buffer of the method's first run. + held = method(ones)[0] + bound = torch.empty(self.shape, device=self.device) + method.set_output(bound, 0) + with torch.cuda.graph(torch.cuda.CUDAGraph(), capture_error_mode="relaxed"): + with cuda.stream(torch.cuda.current_stream()): + # Neither the held result nor the default clone_outputs stops + # these calls, since the output goes into the bound tensor; only + # their input does. + for clone_outputs in (False, True): + with self.assertRaisesRegex( + RuntimeError, "resizing tensor at input 0" + ): + method(wrong, clone_outputs=clone_outputs) + # The bound output needs no new buffer while the held one is in use. + with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as trace: + method(ones, clone_outputs=False) + calls = {event.key: event.count for event in trace.key_averages()} + self.assertEqual(calls.get("cudaMalloc", 0), 0) + with torch.cuda.graph(torch.cuda.CUDAGraph(), capture_error_mode="relaxed"): + with cuda.stream(torch.cuda.current_stream()): + outputs = method.get_outputs() + self.assertEqual(outputs[0].data_ptr(), bound.data_ptr()) + torch.testing.assert_close(bound, self._tensor(held)) + @staticmethod def _close_after_teardown(stream): import threading @@ -1314,6 +1531,217 @@ def chain(): torch.from_dlpack(final), torch.full(self.shape, expected) ) + def _memory_pools_supported(self): + supported = ctypes.c_int() + device = ctypes.c_int() + memory_pools_supported = 115 # CU_DEVICE_ATTRIBUTE_MEMORY_POOLS_SUPPORTED + self.assertEqual( + self.driver.cuDeviceGet(ctypes.byref(device), self.device.index), 0 + ) + self.assertEqual( + self.driver.cuDeviceGetAttribute( + ctypes.byref(supported), memory_pools_supported, device + ), + 0, + ) + return bool(supported.value) + + def test_host_uploads_take_memory_from_the_pool(self): + # cudaMalloc and cudaFree enter the driver, where one call can wait + # behind other processes, so an upload made and dropped on every call + # takes its memory from a pool. + from torch.profiler import profile, ProfilerActivity + + if not self._memory_pools_supported(): + self.skipTest("the device has no memory pools") + count = torch.Size(self.shape).numel() + host = ( + memoryview(array.array("f", [3.0]) * count).cast("B").cast("f", self.shape) + ) + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as trace: + for _ in range(8): + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + calls = {event.key: event.count for event in trace.key_averages()} + # Seeing the pool allocations shows the profiler traces these calls. + self.assertEqual(calls.get("cudaMallocFromPoolAsync", 0), 8) + self.assertEqual(calls.get("cudaMalloc", 0) + calls.get("cudaFree", 0), 0) + # Each upload is dropped after the next one is made, so two blocks serve + # them all. + addresses = set() + for _ in range(8): + uploaded = self.bindings.ExecuTorchResult.from_host(host, self.device.index) + addresses.add(torch.from_dlpack(uploaded).data_ptr()) + self.assertLessEqual(len(addresses), 2) + + def test_another_device_writes_an_upload(self): + if torch.cuda.device_count() < 2: + self.skipTest("needs two CUDA devices") + if not torch.cuda.can_device_access_peer(1, 0): + self.skipTest("device 1 cannot access device 0") + count = torch.Size(self.shape).numel() + host = ( + memoryview(array.array("f", [0.0]) * count).cast("B").cast("f", self.shape) + ) + uploaded = self.bindings.ExecuTorchResult.from_host(host, 0) + # torch copies between devices that can access each other on the source + # device, which then writes the upload's memory directly. + torch.from_dlpack(uploaded).copy_(torch.full(self.shape, 7.0, device="cuda:1")) + torch.cuda.synchronize(0) + torch.testing.assert_close( + torch.from_dlpack(uploaded).cpu(), torch.full(self.shape, 7.0) + ) + + def test_side_stream_reads_of_dropped_uploads_stay_intact(self): + # torch side streams do not wait for the default stream, so a dropped + # upload's memory must not serve the next upload while one still reads + # it. + count = torch.Size(self.shape).numel() + side = torch.cuda.Stream(device=self.device) + doubled = [] + with torch.cuda.stream(side): + for value in range(4): + host = ( + memoryview(array.array("f", [float(value)]) * count) + .cast("B") + .cast("f", self.shape) + ) + uploaded = torch.from_dlpack( + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + ) + # Still reading when the next upload is made. + torch.cuda._sleep(100_000_000) + doubled.append(uploaded * 2) + del uploaded + torch.cuda.synchronize(self.device) + for value, result in enumerate(doubled): + torch.testing.assert_close( + result.cpu(), torch.full(self.shape, 2.0 * value) + ) + + def test_results_dropped_on_another_thread_leave_a_capture_intact(self): + import threading + + count = torch.Size(self.shape).numel() + host = ( + memoryview(array.array("f", [3.0]) * count).cast("B").cast("f", self.shape) + ) + held = [self.bindings.ExecuTorchResult.from_host(host, self.device.index)] + address = torch.from_dlpack(held[0]).data_ptr() + value = torch.ones(self.shape, device=self.device) + graph = torch.cuda.CUDAGraph() + # torch.compile's reduce-overhead mode captures in thread_local mode, + # where a wait for the device on another thread ends the capture. + with torch.cuda.graph(graph, capture_error_mode="thread_local"): + doubled = value * 2 + dropper = threading.Thread(target=held.clear) + dropper.start() + dropper.join() + value.fill_(3.0) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(doubled, torch.full_like(value, 6.0)) + # The next wait for the device, here the one torch.from_dlpack() makes, + # gives the dropped memory back to the pool. + torch.from_dlpack( + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + ) + uploaded = self.bindings.ExecuTorchResult.from_host(host, self.device.index) + self.assertEqual(torch.from_dlpack(uploaded).data_ptr(), address) + + def test_uploads_on_another_thread_leave_a_capture_intact(self): + import threading + + count = torch.Size(self.shape).numel() + host = ( + memoryview(array.array("f", [3.0]) * count).cast("B").cast("f", self.shape) + ) + # Dropped memory waits for the next wait for the device, which an upload + # on another thread must not make during the capture. + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + uploaded = [] + value = torch.ones(self.shape, device=self.device) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, capture_error_mode="thread_local"): + doubled = value * 2 + uploader = threading.Thread( + target=lambda: uploaded.append( + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + ) + ) + uploader.start() + uploader.join() + self.assertEqual(len(uploaded), 1) + value.fill_(3.0) + graph.replay() + torch.cuda.synchronize() + torch.testing.assert_close(doubled, torch.full_like(value, 6.0)) + torch.testing.assert_close( + torch.from_dlpack(uploaded[0]).cpu(), torch.full(self.shape, 3.0) + ) + + def test_full_pool_takes_back_dropped_upload_memory(self): + from executorch.runtime import cuda + + if not self._memory_pools_supported(): + self.skipTest("the device has no memory pools") + size = 256 << 20 + host = memoryview(bytearray(size)) + cuda.empty_cache() + torch.cuda.empty_cache() + free, _ = torch.cuda.mem_get_info(self.device) + # Leaves room for one upload, but not for two. + filler = torch.empty( + free - size - size // 2, dtype=torch.uint8, device=self.device + ) + try: + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + # The pool cannot grow, so the upload waits for the device and takes + # back the dropped memory. + self.bindings.ExecuTorchResult.from_host(host, self.device.index) + finally: + del filler + torch.cuda.empty_cache() + + def _pool_reserved_bytes(self, pool): + reserved = ctypes.c_uint64() + reserved_mem_current = 5 # CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT + self.assertEqual( + self.driver.cuMemPoolGetAttribute( + pool, reserved_mem_current, ctypes.byref(reserved) + ), + 0, + ) + return reserved.value + + def test_empty_cache_releases_dropped_upload_memory(self): + from executorch.runtime import cuda + + if not self._memory_pools_supported(): + self.skipTest("the device has no memory pools") + host = memoryview(bytearray(256 << 20)) + uploaded = self.bindings.ExecuTorchResult.from_host(host, self.device.index) + # Reads the upload's own pool, which other processes on the GPU cannot + # change. + pool = ctypes.c_void_p() + mempool_handle = 17 # CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE + self.assertEqual( + self.driver.cuPointerGetAttribute( + ctypes.byref(pool), + mempool_handle, + torch.from_dlpack(uploaded).data_ptr(), + ), + 0, + ) + del uploaded + kept = self._pool_reserved_bytes(pool) + cuda.empty_cache() + self.assertGreaterEqual(kept - self._pool_reserved_bytes(pool), 256 << 20) + with self.assertRaisesRegex(ValueError, "has to wait"): + with torch.cuda.graph(torch.cuda.CUDAGraph()): + with cuda.stream(torch.cuda.current_stream()): + cuda.empty_cache() + def _require_linux(self): # The torch-free chain checks loaded libraries through /proc. if not sys.platform.startswith("linux"): diff --git a/runtime/cuda.py b/runtime/cuda.py index 6bdc02f0837..63d961e78c8 100644 --- a/runtime/cuda.py +++ b/runtime/cuda.py @@ -32,6 +32,34 @@ blocking streams. Weights an older export keeps in one blob wait for the whole GPU. A call with GPU inputs or outputs, and ``ExecuTorchResult.to_host()``, also wait for the whole GPU, so GPU data written on other streams stays safe. +While ``s`` captures a CUDA graph, a call does not wait: the capture records +its GPU work on ``s``, and a replay of the graph runs it. What the call does on +the host, such as copying a CPU input into the program's memory, happens once, +during the capture, so export the method with its inputs and outputs on the +GPU. A program's own copy to host memory fails and ends the capture. A +delegate in the method has to queue its GPU work on ``s`` without waiting; the +CUDA delegate cannot do that yet. The bindings refuse a call that would have to +wait for the GPU, or allocate GPU memory for an output, so pass torch inputs in +the exported layout and, for GPU outputs, call with ``clone_outputs=False``. +They also refuse ``ExecuTorchResult.from_host()`` and other copies to GPU +memory, and waits such as ``ExecuTorchResult.to_host()`` and +``torch.from_dlpack()`` of a result. A DLPack input is asked to order its +producer's work before ``s``, so write it on ``s``: a producer that works on +another stream makes CUDA end the capture. A result or output dropped in the +block during the capture keeps its memory until the process exits, so drop +them before or after the capture. A call also lets go of the inputs and +outputs the bindings kept from the previous call, so make the last call before +the capture with the inputs it uses. Loading a method allocates GPU memory, so +a method's first call is refused during a capture: call it, or load it with +``load_method()``, before. A result of ``ExecuTorchResult.from_host()`` +or of a copy into an ``ExecuTorchResult``, dropped on another thread, makes no +CUDA call, so the capture goes on; its memory goes back to the pool after the +next wait for the GPU. +Keep the method loaded and its inputs and outputs alive while the graph is in +use, and wait for a replay to finish before reading its outputs. Do not let go +of the last owner of a method, such as a result it returned with +``clone_outputs=False``, during any capture: that frees its GPU memory and ends +the capture. Limits for now: a stream known to be on a CUDA device other than 0 is refused, so is the legacy default stream (handle 0, or 1 for ``cudaStreamLegacy``), and @@ -220,3 +248,21 @@ def stream(s: Any) -> _StreamScope: A context manager whose ``as`` value is ``s``. """ return _StreamScope(s) + + +def empty_cache() -> None: + """Gives GPU memory that the CUDA allocator's pool holds unused back to the GPU. + + The memory of a dropped ``ExecuTorchResult`` upload or copy stays in the + CUDA allocator's pool, so later results reuse it without asking the driver, + as torch keeps freed tensors in its cache. Like ``torch.cuda.empty_cache()``, + this releases everything the pool holds unused, so other processes can use + it. The CUDA delegates share the pool, so their next run grows it again. It + waits for each GPU it releases memory on, so it is refused while the + selected stream captures a CUDA graph. It does nothing in a build without + CUDA support. + """ + from executorch.extension.pybindings import _C as native + + if hasattr(native, "_empty_cache"): + native._empty_cache()