diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 50c32678a..47de984b2 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -545,6 +545,11 @@ SD_API void disable_imatrix_collection(void); // assignment specs. Returns the number of bytes required, excluding the null // terminator. Passing nullptr or buffer_size 0 only queries the required size. SD_API size_t sd_list_devices(char* buffer, size_t buffer_size); +// Report the free and total memory in bytes of the device named `device`, a +// name from sd_list_devices such as CUDA0. The figures come from the backend +// and may be estimates; both are zero when the backend has none available. +// Returns false if the device is not found or a pointer is null. +SD_API bool sd_device_memory(const char* device, size_t* free_bytes, size_t* total_bytes); // Register comma-separated RPC endpoints (host:port) before listing devices. // Repeated endpoints are safe; nullptr or an empty string is a no-op. diff --git a/src/core/ggml_extend_backend.cpp b/src/core/ggml_extend_backend.cpp index 356955629..863054ff8 100644 --- a/src/core/ggml_extend_backend.cpp +++ b/src/core/ggml_extend_backend.cpp @@ -483,6 +483,36 @@ static ggml_backend_t init_named_backend(const std::string& name) { return ggml_backend_init_by_name(resolved.c_str(), nullptr); } +bool sd_device_memory(const char* device, size_t* free_bytes, size_t* total_bytes) { + if (device == nullptr || free_bytes == nullptr || total_bytes == nullptr) { + return false; + } +#ifdef SD_USE_CUDA + // ggml's device discovery and memory query can leave another GPU selected + // on the calling thread. + CUcontext previous = nullptr; + if (cuCtxGetCurrent(&previous) != CUDA_SUCCESS) { + previous = nullptr; + } +#endif + if (ggml_backend_dev_count() == 0) { + ggml_backend_load_all(); + } + ggml_backend_dev_t dev = resolve_device_by_name(device); + if (dev != nullptr) { + *free_bytes = 0; + *total_bytes = 0; + ggml_backend_dev_memory(dev, free_bytes, total_bytes); + } +#ifdef SD_USE_CUDA + CUcontext current = nullptr; + if (cuCtxGetCurrent(¤t) == CUDA_SUCCESS && current != previous) { + cuCtxSetCurrent(previous); + } +#endif + return dev != nullptr; +} + bool sd_backend_is_cpu(ggml_backend_t backend) { if (backend == nullptr) { return false;