Commit ca21536 for stable-diffusion.cpp

commit ca2153690292f139f6a82a5eefe7fde0890d8c62
Author: Shogo Iwano <shiwano@gmail.com>
Date:   Thu Dec 3 22:54:02 2026 +0900

    feat: add sd_device_memory to query device memory (#2483)

diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h
index 50c3267..47de984 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 3569556..863054f 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(&current) == CUDA_SUCCESS && current != previous) {
+        cuCtxSetCurrent(previous);
+    }
+#endif
+    return dev != nullptr;
+}
+
 bool sd_backend_is_cpu(ggml_backend_t backend) {
     if (backend == nullptr) {
         return false;