Skip to content
Merged
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
5 changes: 5 additions & 0 deletions docs/guides/c_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`.
Expand Down
14 changes: 14 additions & 0 deletions examples/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
43 changes: 42 additions & 1 deletion examples/server/async_jobs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -704,14 +704,54 @@ 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;

while (true) {
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;
Expand Down Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions examples/server/async_jobs.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 3 additions & 3 deletions examples/server/model_catalog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions examples/server/routes_models.cpp
Original file line number Diff line number Diff line change
@@ -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");
Expand All @@ -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");
Expand Down
29 changes: 29 additions & 0 deletions examples/server/runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

#include <algorithm>
#include <cctype>
#include <charconv>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <mutex>
#include <regex>
#include <sstream>
#include <string_view>

#include "common/common.h"
#include "common/log.h"
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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"
<< "}";
Expand Down
2 changes: 2 additions & 0 deletions examples/server/runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 7 additions & 0 deletions include/stable-diffusion.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
3 changes: 2 additions & 1 deletion src/api/api.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion src/api/generation.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
19 changes: 13 additions & 6 deletions src/dgl/context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions src/dgl/context.h
Original file line number Diff line number Diff line change
Expand Up @@ -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_; }
Expand Down
14 changes: 14 additions & 0 deletions src/dgl/dgl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
30 changes: 25 additions & 5 deletions src/model_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading