Commit 3b12781 for stable-diffusion.cpp
commit 3b12781fac1a22eda27ad0f08d0884ef816f24d7
Author: leejet <leejet714@gmail.com>
Date: Tue Nov 24 01:17:22 2026 +0800
feat(server): add idle TTLs for model weights (#2406)
diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md
index fe1f836..18f6391 100644
--- a/docs/guides/c_api.md
+++ b/docs/guides/c_api.md
@@ -81,6 +81,11 @@ file-access callbacks for generated programs and scripts through
`sd_ctx_set_file_access_callback()` and `sd_dgl_ctx_set_file_access_callback()`
respectively.
+Use `sd_dgl_ctx_release_staging()` to release idle GPU staging copies backed by
+RAM weights. Use `sd_dgl_ctx_unload_models()` to release cached model components
+and reload them on demand. Both return `SD_STATUS_BUSY` while the context is
+running a script or generation.
+
Use `sd_generate_video()` with options from `sd_vid_gen_opt_create()` to generate video. Its result
exposes frames through the same image accessors, optional audio through
`sd_result_get_audio()`, and effective frame rate through `sd_result_get_fps()`.
diff --git a/examples/server/README.md b/examples/server/README.md
index a657acf..12ca94c 100644
--- a/examples/server/README.md
+++ b/examples/server/README.md
@@ -437,6 +437,20 @@ configured defaults.
| `--max-pending-jobs <count>` | `64` | Maximum async jobs queued or generating |
| `--completed-ttl-seconds <seconds>` | `600` | Retention time for completed async jobs |
+### Idle weight release
+
+| Option | Default | Memory released when idle |
+| --- | --- | --- |
+| `--weight-staging-ttl <seconds>` | `-1` | GPU staging copies of weights backed by RAM, including components placed on CPU by `--params-backend cpu` or auto-fit. The next request uploads the needed weights from RAM. |
+| `--weight-residency-ttl <seconds>` | `-1` | Cached model components, including RAM weights, GPU weights, staging copies, and component caches. The next request loads the needed components from their files. |
+
+For either option, `-1` disables release, `0` releases as soon as the shared
+context is idle, and a positive integer sets the idle time in seconds. The
+timer starts when the last job finishes. Running and queued generation or DGL
+jobs defer release. Status and progress requests do not reset the timer. If
+both deadlines are due, the server unloads the model components in one step.
+The configured model and the model catalog remain available after unloading.
+
### Logging
Logging defaults to `info`. Use `--log-level <level>` to select `debug`, `verbose`,
diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp
index 13ca2a4..09c5291 100644
--- a/examples/server/async_jobs.cpp
+++ b/examples/server/async_jobs.cpp
@@ -704,6 +704,46 @@ static bool execute_dgl_job(ServerRuntime& runtime,
}
}
+void AsyncJobManager::record_context_job_completion(const SDSvrParams& params) {
+ const auto now = std::chrono::steady_clock::now();
+ if (params.weight_staging_ttl >= 0)
+ staging_deadline = now + std::chrono::seconds(params.weight_staging_ttl);
+ if (params.weight_residency_ttl >= 0)
+ residency_deadline = now + std::chrono::seconds(params.weight_residency_ttl);
+}
+
+static void wait_for_job(ServerRuntime& runtime, std::unique_lock<std::mutex>& lock) {
+ auto& manager = *runtime.async_job_manager;
+ using Clock = std::chrono::steady_clock;
+ const auto disabled = Clock::time_point::max();
+ while (!manager.stop && manager.queue.empty()) {
+ const auto deadline = std::min(manager.staging_deadline, manager.residency_deadline);
+ if (deadline == disabled || manager.synchronous_jobs != 0) {
+ manager.cv.wait(lock);
+ continue;
+ }
+ const auto now = Clock::now();
+ if (now < deadline) {
+ manager.cv.wait_until(lock, deadline);
+ continue;
+ }
+
+ // Keep job admission serialized with the idle check and the DGL release.
+ const bool unload = now >= manager.residency_deadline;
+ auto* ctx = sd_ctx_get_dgl_ctx(runtime.sd_ctx);
+ const auto status = unload ? sd_dgl_ctx_unload_models(ctx) : sd_dgl_ctx_release_staging(ctx);
+ if (status == SD_STATUS_BUSY) {
+ manager.cv.wait_for(lock, std::chrono::milliseconds(100));
+ continue;
+ }
+ if (status != SD_STATUS_OK)
+ LOG_WARN("idle weight release failed: %s", sd_dgl_error());
+ if (unload)
+ manager.residency_deadline = disabled;
+ manager.staging_deadline = disabled;
+ }
+}
+
void async_job_worker(ServerRuntime& runtime) {
AsyncJobManager& manager = *runtime.async_job_manager;
@@ -711,7 +751,7 @@ void async_job_worker(ServerRuntime& runtime) {
std::shared_ptr<AsyncGenerationJob> job;
{
std::unique_lock<std::mutex> lock(manager.mutex);
- manager.cv.wait(lock, [&]() { return manager.stop || !manager.queue.empty(); });
+ wait_for_job(runtime, lock);
if (manager.stop && manager.queue.empty()) {
break;
@@ -766,6 +806,7 @@ void async_job_worker(ServerRuntime& runtime) {
{
std::lock_guard<std::mutex> lock(manager.mutex);
+ manager.record_context_job_completion(*runtime.svr_params);
auto it = manager.jobs.find(job->id);
if (it == manager.jobs.end()) {
continue;
diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h
index 3c940fe..283910a 100644
--- a/examples/server/async_jobs.h
+++ b/examples/server/async_jobs.h
@@ -86,6 +86,12 @@ struct AsyncJobManager {
size_t max_pending_jobs = 64;
int64_t completed_ttl_seconds = 600;
int64_t failed_ttl_seconds = 600;
+
+ size_t synchronous_jobs = 0;
+ std::chrono::steady_clock::time_point staging_deadline = std::chrono::steady_clock::time_point::max();
+ std::chrono::steady_clock::time_point residency_deadline = std::chrono::steady_clock::time_point::max();
+
+ void record_context_job_completion(const SDSvrParams& params);
};
void purge_expired_jobs(AsyncJobManager& manager);
diff --git a/examples/server/model_catalog.cpp b/examples/server/model_catalog.cpp
index 4d51541..668e896 100644
--- a/examples/server/model_catalog.cpp
+++ b/examples/server/model_catalog.cpp
@@ -733,12 +733,12 @@ ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json&
const auto found = models.recipes.find(recipe_id);
if (found == models.recipes.end())
throw std::runtime_error("unknown recipe");
- const auto& recipe = found->second;
+ const auto& recipe = found->second;
const auto recipe_defaults = recipe.value("defaults", json::object());
if (mode == VID_GEN && !recipe_defaults.contains("video_frames"))
throw std::runtime_error("selected recipe does not support vid_gen: " + recipe_id);
- auto context = models.base_context;
- auto defaults = models.base_defaults;
+ auto context = models.base_context;
+ auto defaults = models.base_defaults;
apply_recipe_context(recipe.value("context", json::object()), context);
apply_recipe_defaults(recipe_defaults, defaults);
// Recipe-provided default models fill any slot the request did not select.
diff --git a/examples/server/routes_models.cpp b/examples/server/routes_models.cpp
index 7072aa1..adb2b5c 100644
--- a/examples/server/routes_models.cpp
+++ b/examples/server/routes_models.cpp
@@ -1,7 +1,32 @@
#include "routes.h"
+#include "async_jobs.h"
#include "model_catalog.h"
+class SynchronousContextJob {
+ AsyncJobManager& manager_;
+ const SDSvrParams& params_;
+
+public:
+ explicit SynchronousContextJob(const ServerRuntime& runtime)
+ : manager_(*runtime.async_job_manager), params_(*runtime.svr_params) {
+ std::lock_guard<std::mutex> lock(manager_.mutex);
+ ++manager_.synchronous_jobs;
+ }
+
+ SynchronousContextJob(const SynchronousContextJob&) = delete;
+ SynchronousContextJob& operator=(const SynchronousContextJob&) = delete;
+
+ ~SynchronousContextJob() {
+ {
+ std::lock_guard<std::mutex> lock(manager_.mutex);
+ --manager_.synchronous_jobs;
+ manager_.record_context_job_completion(params_);
+ }
+ manager_.cv.notify_one();
+ }
+};
+
static void model_error(httplib::Response& res, int status, const std::string& code, const std::string& message) {
res.status = status;
res.set_content(json({{"error", message}, {"code", code}}).dump(), "application/json");
@@ -13,6 +38,7 @@ httplib::Server::Handler RuntimeRoutes::protect(httplib::Server::Handler handler
const bool generation = req.path == "/sdapi/v1/txt2img" || req.path == "/sdapi/v1/img2img" ||
req.path == "/v1/images/generations" || req.path == "/v1/images/edits";
if (generation) {
+ SynchronousContextJob job(*runtime);
std::lock_guard<std::mutex> lock(*runtime->sd_ctx_mutex);
if (!has_current_model(*runtime)) {
model_error(res, 503, "model_not_loaded", "No current model is configured");
diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp
index 7b9c4ac..46cd87a 100644
--- a/examples/server/runtime.cpp
+++ b/examples/server/runtime.cpp
@@ -2,6 +2,7 @@
#include <algorithm>
#include <cctype>
+#include <charconv>
#include <chrono>
#include <cmath>
#include <cstdlib>
@@ -9,6 +10,7 @@
#include <mutex>
#include <regex>
#include <sstream>
+#include <string_view>
#include "common/common.h"
#include "common/log.h"
@@ -280,6 +282,21 @@ std::string unsupported_generation_mode_error(SDMode mode) {
return "current model does not support requested mode";
}
+static int parse_weight_ttl(int argc, const char** argv, int index, int& ttl) {
+ if (index + 1 < argc) {
+ const std::string_view value = argv[index + 1];
+ const auto* end = value.data() + value.size();
+ int seconds = 0;
+ const auto parsed = std::from_chars(value.data(), end, seconds);
+ if (parsed.ec == std::errc{} && parsed.ptr == end && seconds >= -1) {
+ ttl = seconds;
+ return 1;
+ }
+ }
+ LOG_ERROR("%s expects an integer greater than or equal to -1", argv[index]);
+ return -1;
+}
+
ArgOptions SDSvrParams::get_options() {
ArgOptions options;
@@ -311,6 +328,16 @@ ArgOptions SDSvrParams::get_options() {
options.manual_options = {
{"-h", "--help", "show this help message and exit", on_help_arg},
+ {"", "--weight-staging-ttl",
+ "idle seconds before releasing GPU staging copies of RAM weights (-1 disabled, 0 immediate; default: -1)",
+ [this](int argc, const char** argv, int index) {
+ return parse_weight_ttl(argc, argv, index, weight_staging_ttl);
+ }},
+ {"", "--weight-residency-ttl",
+ "idle seconds before unloading model components from RAM and VRAM (-1 disabled, 0 immediate; default: -1)",
+ [this](int argc, const char** argv, int index) {
+ return parse_weight_ttl(argc, argv, index, weight_residency_ttl);
+ }},
{"", "--model-dir", "model root; repeat to search multiple directories (default: models)",
[this](int argc, const char** argv, int index) {
if (++index >= argc || argv[index][0] == '\0')
@@ -370,6 +397,8 @@ std::string SDSvrParams::to_string() const {
<< " listen_port: \"" << listen_port << "\",\n"
<< " max_pending_jobs: " << max_pending_jobs << ",\n"
<< " completed_ttl_seconds: " << completed_ttl_seconds << ",\n"
+ << " weight_staging_ttl: " << weight_staging_ttl << ",\n"
+ << " weight_residency_ttl: " << weight_residency_ttl << ",\n"
<< " serve_html_path: \"" << serve_html_path << "\",\n"
<< " dgl_dir: \"" << dgl_dir << "\",\n"
<< "}";
diff --git a/examples/server/runtime.h b/examples/server/runtime.h
index 40d6d4f..dbd8a7a 100644
--- a/examples/server/runtime.h
+++ b/examples/server/runtime.h
@@ -24,6 +24,8 @@ struct SDSvrParams {
int listen_port = 1234;
int max_pending_jobs = 64;
int completed_ttl_seconds = 600;
+ int weight_staging_ttl = -1;
+ int weight_residency_ttl = -1;
std::string serve_html_path;
std::string dgl_dir = "dgl";
std::vector<std::string> model_dirs;
diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h
index f23fd8a..92a7fba 100644
--- a/include/stable-diffusion.h
+++ b/include/stable-diffusion.h
@@ -364,6 +364,13 @@ SD_API void sd_dgl_ctx_free(sd_dgl_ctx_t* ctx);
// Threading, placement and weight-loading options invalidate cached models when changed.
SD_API bool sd_dgl_ctx_set(sd_dgl_ctx_t* ctx, const char* key, const char* value);
+// Releases idle GPU staging buffers that have RAM originals.
+// Returns SD_STATUS_BUSY during DGL execution or generation.
+SD_API sd_status_t sd_dgl_ctx_release_staging(sd_dgl_ctx_t* ctx);
+// Unloads cached model components. The context keeps its settings and callbacks.
+// Subsequent requests reload components as needed. Returns SD_STATUS_BUSY during execution.
+SD_API sd_status_t sd_dgl_ctx_unload_models(sd_dgl_ctx_t* ctx);
+
// Optional per-context callback. A null callback restores unrestricted file access.
SD_API bool sd_dgl_ctx_set_file_access_callback(sd_dgl_ctx_t* ctx, sd_dgl_file_access_cb_t callback, void* userdata);
diff --git a/src/api/api.cpp b/src/api/api.cpp
index 054e6ef..fa6b766 100644
--- a/src/api/api.cpp
+++ b/src/api/api.cpp
@@ -135,7 +135,8 @@ static sd_status_t set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* opti
engine.model = std::move(candidate);
sd::api::clear_error();
return SD_STATUS_OK;
- }, kind == SD_RESULT_INVALID ? SD_STATUS_INVALID_ARGUMENT : SD_STATUS_LOAD_FAILED);
+ },
+ kind == SD_RESULT_INVALID ? SD_STATUS_INVALID_ARGUMENT : SD_STATUS_LOAD_FAILED);
}
sd_status_t sd_ctx_set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* options) {
diff --git a/src/api/generation.h b/src/api/generation.h
index 43632ef..09f3c44 100644
--- a/src/api/generation.h
+++ b/src/api/generation.h
@@ -36,7 +36,7 @@ namespace sd::api {
sd_dgl_ctx_t execution;
FileAccessPolicy file_access;
std::recursive_mutex mutex;
- bool executing = false;
+ bool executing = false;
bool probing_model = false;
std::atomic<sd_cancel_mode_t> cancellation{SD_CANCEL_RESET};
dgl::RunEvents* active_run = nullptr;
diff --git a/src/dgl/context.cpp b/src/dgl/context.cpp
index 6e5843b..77eb42d 100644
--- a/src/dgl/context.cpp
+++ b/src/dgl/context.cpp
@@ -51,6 +51,18 @@ namespace sd::dgl {
return true;
}
+ void Context::unload_models() {
+ const auto cached = resources.size();
+ for (auto it = resources.begin(); it != resources.end();) {
+ if (is_model_kind(it->second.value.type().kind))
+ it = resources.erase(it);
+ else
+ ++it;
+ }
+ if (const auto unloaded = cached - resources.size(); unloaded != 0)
+ LOG_VERBOSE("DGL unloaded %zu cached model components", unloaded);
+ }
+
static size_t parse_max_ram(const std::string& value) {
constexpr long double gib_bytes = 1024.0L * 1024 * 1024;
size_t end = 0;
@@ -103,12 +115,7 @@ namespace sd::dgl {
current = enabled;
}
// Runner sessions and weight storage take their settings from the model at initialization.
- for (auto it = resources.begin(); it != resources.end();) {
- if (is_model_kind(it->second.value.type().kind))
- it = resources.erase(it);
- else
- ++it;
- }
+ unload_models();
}
void Context::set(const std::string& key, const std::string& value) {
diff --git a/src/dgl/context.h b/src/dgl/context.h
index 90fbfc7..db57d30 100644
--- a/src/dgl/context.h
+++ b/src/dgl/context.h
@@ -51,6 +51,7 @@ namespace sd::dgl {
Value derive_model(const Value& base, std::shared_ptr<const models::LoraConfig> loras);
bool evict_idle_resource();
void prune_expired_resources();
+ void unload_models();
sd::ParallelExecutor* tensor_executor() const { return model_execution_.tensor_executor.get(); }
bool auto_fit() const { return auto_fit_; }
diff --git a/src/dgl/dgl.cpp b/src/dgl/dgl.cpp
index 5f5b0a3..5439f20 100644
--- a/src/dgl/dgl.cpp
+++ b/src/dgl/dgl.cpp
@@ -141,6 +141,20 @@ bool sd_dgl_ctx_set(sd_dgl_ctx_t* ctx, const char* key, const char* value) {
}) == SD_STATUS_OK;
}
+sd_status_t sd_dgl_ctx_release_staging(sd_dgl_ctx_t* ctx) {
+ return api_call([&] {
+ auto lock = lock_idle(ctx);
+ ctx->models->release_idle_gpu_staging();
+ });
+}
+
+sd_status_t sd_dgl_ctx_unload_models(sd_dgl_ctx_t* ctx) {
+ return api_call([&] {
+ auto lock = lock_idle(ctx);
+ ctx->unload_models();
+ });
+}
+
bool sd_dgl_ctx_set_file_access_callback(sd_dgl_ctx_t* ctx, sd_dgl_file_access_cb_t callback, void* userdata) {
return api_call([&] {
auto lock = lock_idle(ctx);
diff --git a/src/model_manager.cpp b/src/model_manager.cpp
index 3880fe8..b13cd0e 100644
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -1342,8 +1342,7 @@ bool ModelManager::ensure_host_capacity(size_t pending, const std::vector<Tensor
if (!weight_allocation || !max_ram_bytes_ || pending <= max_ram_bytes_) {
std::unordered_set<TensorState*> protected_states(required_states.begin(), required_states.end());
- for (const auto& entry : prefetch_blocks_)
- protected_states.insert(entry.second->states.begin(), entry.second->states.end());
+ protect_prefetched_states(protected_states);
while (evict_host_weight_block(protected_states) || (evict_idle_resource_ && evict_idle_resource_())) {
if (fits())
return true;
@@ -1729,6 +1728,29 @@ void ModelManager::free_compute_staging_block(ComputeStagingBlock& block) {
block.staged_tensors.clear();
}
+void ModelManager::protect_prefetched_states(std::unordered_set<TensorState*>& states) const {
+ for (const auto& entry : prefetch_blocks_)
+ states.insert(entry.second->states.begin(), entry.second->states.end());
+}
+
+void ModelManager::release_idle_gpu_staging() {
+ std::unordered_set<TensorState*> protected_states;
+ protect_prefetched_states(protected_states);
+ std::unordered_set<TensorState*> target_states;
+ for (const auto& block : compute_staging_blocks_) {
+ if (!block->buffer || ggml_backend_buffer_is_host(block->buffer))
+ continue;
+ // Staging swaps the original storage into the block's tensor metadata.
+ for (const auto& [state, original] : block->staged_tensors) {
+ if (state && state->loaded_to_params_backend && original && original->data && original->buffer &&
+ ggml_backend_buffer_is_host(original->buffer) && !protected_states.count(state))
+ target_states.insert(state);
+ }
+ }
+ if (!target_states.empty())
+ release_compute_staging_blocks(false, &target_states);
+}
+
void ModelManager::release_compute_staging_blocks(bool force,
const std::unordered_set<TensorState*>* target_states) {
struct ReleaseStats {
@@ -2501,9 +2523,7 @@ std::vector<WeightResidencyBlock> ModelManager::evictable_compute_backend_blocks
return result;
}
std::unordered_set<TensorState*> protected_states(protected_list.begin(), protected_list.end());
- for (const auto& entry : prefetch_blocks_) {
- protected_states.insert(entry.second->states.begin(), entry.second->states.end());
- }
+ protect_prefetched_states(protected_states);
const auto device = ggml_backend_get_device(backend);
const bool cpu = sd_backend_is_cpu(backend);
auto on_device = [&](ggml_backend_buffer_t buffer) {
diff --git a/src/model_manager.h b/src/model_manager.h
index 08c37e6..d92f73b 100644
--- a/src/model_manager.h
+++ b/src/model_manager.h
@@ -169,6 +169,7 @@ private:
bool populate_prefetch_block(PrefetchBlock& block);
void synchronize_prefetch_block(PrefetchBlock& block);
void free_prefetch_block(PrefetchBlock& block);
+ void protect_prefetched_states(std::unordered_set<TensorState*>& states) const;
void clear_all_prefetched_params();
void release_prefetch();
@@ -253,6 +254,7 @@ public:
bool remove_resource(ResourceId id);
void set_retain_weights(bool retain) { retain_weights_ = retain; }
bool retains_idle_weights() const override { return retain_weights_; }
+ void release_idle_gpu_staging();
void set_max_vram(sd::ggml_graph_cut::MaxVramAssignment limit) { max_vram_ = std::move(limit); }
bool set_max_ram(size_t bytes);
const sd::ggml_graph_cut::MaxVramAssignment& max_vram() const { return max_vram_; }