mirror of
https://github.com/leejet/stable-diffusion.cpp.git
synced 2026-11-28 19:16:33 +00:00
A request that ran the machine out of memory ended in a 500 and left the
server on the configuration that had just failed, so every later request
of that size failed the same way. The context now belongs to a
ContextKeeper (examples/server/recovery.*) and every generation of the
OpenAI, sdapi and sdcpp endpoints goes through ContextKeeper::run().
On out_of_memory or backend (the codes of sd_get_last_error()) it frees
the model, loads it again with the next lighter profile of
max > balanced > lite > lite-disk > lite-cpu and runs the same request
again. Steps that would load the same configuration are skipped, a
device failure jumps to lite-cpu, and from lite on the VAE is decoded in
tiles whatever the request asked. --profile sets the top of the ladder.
After --degradation-cooldown seconds (300; 0 = never) the server climbs
back one profile at the start of the next request. A climb that fails
on its first use is undone and doubles the wait, up to an hour. If the
model cannot be loaded again, requests get 503 "unavailable" and the
load is retried no more than every 15 seconds. --disable-degradation
keeps the old behavior of answering with the error.
Failures are answered with 503 and Retry-After (out of memory, no
context), 400 (invalid_argument) or 500, with a body of
{"error", "code", "retry_after_seconds"}. Async jobs report the same
code in error.code, 429 carries Retry-After, and std::bad_alloc in a
handler becomes a 503. New endpoints: GET /sdcpp/v1/health (status,
profile, counters, last error, queue; it never waits for a running
generation) and GET /sdcpp/v1/resources (system memory and devices).
sd-server now exits with code 1 and a message when it cannot listen or
create its HTTP threads; the second used to end in std::terminate and
the first in a silent exit 0. The lite-disk profile clears --eager-load,
which read every weight into memory and so saved nothing.
test/server_recovery_test.cpp checks the ladder, the step downs, the
climb back, the reload after a failure, the HTTP answers and use from
several threads with a scripted library and clock (114 checks, also
under ASan/UBSan and TSan). Checked with a synthetic SD 1.5 model on
the CPU under address-space limits: a 384x384 request at 2400 MiB steps
down to lite-disk and succeeds, below 2200 MiB it answers 503 and the
server stays up, the climb back and a failed climb behave as described,
and nine parallel requests of the three kinds are all served. The server
and the whole engine built with ASan/UBSan went through the ladder, the
CPU memory-guard scenarios and injected read errors without a report.
Not checked: Windows, GPUs, real models.
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
428 lines
15 KiB
C++
428 lines
15 KiB
C++
#include "runtime.h"
|
|
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <chrono>
|
|
#include <cstdlib>
|
|
#include <filesystem>
|
|
#include <mutex>
|
|
#include <regex>
|
|
#include <sstream>
|
|
|
|
#include "common/common.h"
|
|
#include "common/log.h"
|
|
#include "recovery.h"
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
static std::string lower_ascii(std::string value) {
|
|
std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) {
|
|
return static_cast<char>(std::tolower(c));
|
|
});
|
|
return value;
|
|
}
|
|
|
|
static bool is_supported_model_ext(const fs::path& p) {
|
|
auto ext = lower_ascii(p.extension().string());
|
|
return ext == ".gguf" || ext == ".pt" || ext == ".pth" || ext == ".safetensors";
|
|
}
|
|
|
|
static const std::string k_base64_chars =
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
"abcdefghijklmnopqrstuvwxyz"
|
|
"0123456789+/";
|
|
|
|
std::string base64_encode(const std::vector<uint8_t>& bytes) {
|
|
std::string ret;
|
|
int val = 0;
|
|
int valb = -6;
|
|
for (uint8_t c : bytes) {
|
|
val = (val << 8) + c;
|
|
valb += 8;
|
|
while (valb >= 0) {
|
|
ret.push_back(k_base64_chars[(val >> valb) & 0x3F]);
|
|
valb -= 6;
|
|
}
|
|
}
|
|
if (valb > -6) {
|
|
ret.push_back(k_base64_chars[((val << 8) >> (valb + 8)) & 0x3F]);
|
|
}
|
|
while (ret.size() % 4) {
|
|
ret.push_back('=');
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
std::string normalize_output_format(std::string output_format) {
|
|
std::transform(output_format.begin(), output_format.end(), output_format.begin(),
|
|
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
|
return output_format;
|
|
}
|
|
|
|
std::vector<std::string> supported_img_output_formats(bool allow_webp) {
|
|
std::vector<std::string> formats = {"png", "jpeg"};
|
|
#ifdef SD_USE_WEBP
|
|
if (allow_webp) {
|
|
formats.push_back("webp");
|
|
}
|
|
#else
|
|
(void)allow_webp;
|
|
#endif
|
|
return formats;
|
|
}
|
|
|
|
std::vector<std::string> supported_vid_output_formats() {
|
|
std::vector<std::string> formats;
|
|
#ifdef SD_USE_WEBM
|
|
formats.push_back("webm");
|
|
#endif
|
|
#ifdef SD_USE_WEBP
|
|
formats.push_back("webp");
|
|
#endif
|
|
formats.push_back("avi");
|
|
return formats;
|
|
}
|
|
|
|
static std::string valid_vid_output_formats_message() {
|
|
const std::vector<std::string> formats = supported_vid_output_formats();
|
|
|
|
std::string message = "invalid output_format, must be one of [";
|
|
for (size_t i = 0; i < formats.size(); ++i) {
|
|
if (i > 0) {
|
|
message += ", ";
|
|
}
|
|
message += formats[i];
|
|
}
|
|
message += "]";
|
|
return message;
|
|
}
|
|
|
|
bool assign_output_options(ImgGenJobRequest& request,
|
|
std::string output_format,
|
|
int output_compression,
|
|
bool allow_webp,
|
|
std::string& error_message) {
|
|
request.output_format = normalize_output_format(std::move(output_format));
|
|
request.output_compression = std::clamp(output_compression, 0, 100);
|
|
|
|
const std::vector<std::string> valid_formats = supported_img_output_formats(allow_webp);
|
|
const bool valid_format = std::find(valid_formats.begin(),
|
|
valid_formats.end(),
|
|
request.output_format) != valid_formats.end();
|
|
if (!valid_format) {
|
|
error_message = "invalid output_format, must be one of [";
|
|
for (size_t i = 0; i < valid_formats.size(); ++i) {
|
|
if (i > 0) {
|
|
error_message += ", ";
|
|
}
|
|
error_message += valid_formats[i];
|
|
}
|
|
error_message += "]";
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool assign_output_options(VidGenJobRequest& request,
|
|
std::string output_format,
|
|
int output_compression,
|
|
std::string& error_message) {
|
|
request.output_format = normalize_output_format(std::move(output_format));
|
|
request.output_compression = std::clamp(output_compression, 0, 100);
|
|
|
|
if (request.output_format == "avi") {
|
|
return true;
|
|
}
|
|
|
|
if (request.output_format == "webm") {
|
|
#ifdef SD_USE_WEBM
|
|
return true;
|
|
#else
|
|
error_message = valid_vid_output_formats_message();
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
if (request.output_format == "webp") {
|
|
#ifdef SD_USE_WEBP
|
|
return true;
|
|
#else
|
|
error_message = valid_vid_output_formats_message();
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
error_message = valid_vid_output_formats_message();
|
|
return false;
|
|
}
|
|
|
|
std::string video_mime_type(const std::string& output_format) {
|
|
if (output_format == "webm") {
|
|
return "video/webm";
|
|
}
|
|
if (output_format == "webp") {
|
|
return "image/webp";
|
|
}
|
|
return "video/x-msvideo";
|
|
}
|
|
|
|
bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) {
|
|
if (mode == VID_GEN) {
|
|
return runtime.keeper->supports_video_generation();
|
|
}
|
|
if (mode == IMG_GEN) {
|
|
return runtime.keeper->supports_image_generation();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string unsupported_generation_mode_error(const ServerRuntime& runtime, SDMode mode) {
|
|
if (!runtime.keeper->has_model()) {
|
|
return "no model loaded; restart the server with -m/--diffusion-model";
|
|
}
|
|
if (mode == VID_GEN) {
|
|
return "loaded model does not support vid_gen";
|
|
}
|
|
if (mode == IMG_GEN) {
|
|
return "loaded model does not support img_gen";
|
|
}
|
|
return "loaded model does not support requested mode";
|
|
}
|
|
|
|
ArgOptions SDSvrParams::get_options() {
|
|
ArgOptions options;
|
|
|
|
options.string_options = {
|
|
{"-l", "--listen-ip", "server listen ip (default: 127.0.0.1)", 0, &listen_ip},
|
|
{"", "--serve-html-path", "path to HTML file to serve at root (optional)", 0, &serve_html_path},
|
|
{"", "--api-key", "require this API key on every request, via 'Authorization: Bearer <key>' or 'X-API-Key: <key>' (default: empty, no authentication)", 0, &api_key},
|
|
{"", "--cors-origins", "comma-separated list of allowed CORS origins, e.g. http://localhost:3000 (default: empty, any origin is reflected)", 0, &cors_origins},
|
|
};
|
|
|
|
options.int_options = {
|
|
{"", "--listen-port", "server listen port (default: 1234)", &listen_port},
|
|
{"", "--degradation-cooldown", "seconds the server waits, after stepping down to a lighter profile, before it tries the next heavier one again; a failed attempt doubles the wait up to one hour (default: 300, 0 = never go back up)", °radation_cooldown},
|
|
};
|
|
|
|
options.bool_options = {
|
|
{"", "--color", "colors the logging tags according to level", true, &color},
|
|
{"", "--disable-degradation", "answer a request that runs out of memory with an error (503) instead of loading the model again with a lighter profile and repeating the request", true, &disable_degradation},
|
|
};
|
|
|
|
auto on_help_arg = [&](int, const char**, int, bool& valid) {
|
|
normal_exit = true;
|
|
valid = true;
|
|
return -1;
|
|
};
|
|
|
|
options.manual_options = {
|
|
{"-h", "--help", "show this help message and exit", on_help_arg},
|
|
};
|
|
add_log_options(options, log_level);
|
|
return options;
|
|
}
|
|
|
|
bool SDSvrParams::validate() {
|
|
if (listen_ip.empty()) {
|
|
LOG_ERROR("error: the following arguments are required: listen_ip");
|
|
return false;
|
|
}
|
|
|
|
if (listen_port < 0 || listen_port > 65535) {
|
|
LOG_ERROR("error: listen_port should be in the range [0, 65535]");
|
|
return false;
|
|
}
|
|
|
|
if (degradation_cooldown < 0) {
|
|
LOG_ERROR("error: --degradation-cooldown must be 0 or more seconds");
|
|
return false;
|
|
}
|
|
|
|
if (!serve_html_path.empty() && !fs::exists(serve_html_path)) {
|
|
LOG_ERROR("error: serve_html_path file does not exist: %s", serve_html_path.c_str());
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool SDSvrParams::resolve_and_validate() {
|
|
if (!validate()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string SDSvrParams::to_string() const {
|
|
std::ostringstream oss;
|
|
oss << "SDSvrParams {\n"
|
|
<< " log_level: " << log_level_name(log_level) << ",\n"
|
|
<< " listen_ip: " << listen_ip << ",\n"
|
|
<< " listen_port: \"" << listen_port << "\",\n"
|
|
<< " serve_html_path: \"" << serve_html_path << "\",\n"
|
|
<< " api_key: " << (api_key.empty() ? "(not set)" : "(set)") << ",\n"
|
|
<< " cors_origins: \"" << cors_origins << "\",\n"
|
|
<< " disable_degradation: " << (disable_degradation ? "true" : "false") << ",\n"
|
|
<< " degradation_cooldown: " << degradation_cooldown << ",\n"
|
|
<< "}";
|
|
return oss.str();
|
|
}
|
|
|
|
void refresh_lora_cache(ServerRuntime& rt) {
|
|
std::vector<LoraEntry> new_cache;
|
|
|
|
if (rt.ctx_params->lora_model_dir.empty()) {
|
|
std::lock_guard<std::mutex> lock(*rt.lora_mutex);
|
|
rt.lora_cache->clear();
|
|
return;
|
|
}
|
|
|
|
fs::path lora_dir = rt.ctx_params->lora_model_dir;
|
|
std::error_code ec;
|
|
if (fs::exists(lora_dir, ec) && !ec && fs::is_directory(lora_dir, ec) && !ec) {
|
|
try {
|
|
auto it = fs::recursive_directory_iterator(
|
|
lora_dir,
|
|
fs::directory_options::skip_permission_denied,
|
|
ec);
|
|
auto end = fs::recursive_directory_iterator();
|
|
while (!ec && it != end) {
|
|
std::error_code entry_ec;
|
|
bool is_reg = it->is_regular_file(entry_ec);
|
|
if (entry_ec || !is_reg) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
const fs::path& p = it->path();
|
|
if (!is_supported_model_ext(p)) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
|
|
LoraEntry lora_entry;
|
|
lora_entry.name = p.stem().u8string();
|
|
lora_entry.fullpath = p.u8string();
|
|
std::string rel = p.lexically_relative(lora_dir).u8string();
|
|
std::replace(rel.begin(), rel.end(), '\\', '/');
|
|
lora_entry.path = rel;
|
|
|
|
new_cache.push_back(std::move(lora_entry));
|
|
it.increment(ec);
|
|
}
|
|
} catch (const std::exception& e) {
|
|
LOG_WARN("error while scanning lora directory '%s': %s", lora_dir.string().c_str(), e.what());
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (ec) {
|
|
LOG_WARN("error while scanning lora directory '%s': %s", lora_dir.string().c_str(), ec.message().c_str());
|
|
return;
|
|
}
|
|
|
|
std::sort(new_cache.begin(), new_cache.end(), [](const LoraEntry& a, const LoraEntry& b) {
|
|
return a.path < b.path;
|
|
});
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(*rt.lora_mutex);
|
|
*rt.lora_cache = std::move(new_cache);
|
|
}
|
|
}
|
|
|
|
std::string get_lora_full_path(ServerRuntime& rt, const std::string& path) {
|
|
std::lock_guard<std::mutex> lock(*rt.lora_mutex);
|
|
auto it = std::find_if(rt.lora_cache->begin(), rt.lora_cache->end(),
|
|
[&](const LoraEntry& entry) { return entry.path == path; });
|
|
return it != rt.lora_cache->end() ? it->fullpath : "";
|
|
}
|
|
|
|
void refresh_upscaler_cache(ServerRuntime& rt) {
|
|
std::vector<UpscalerEntry> new_cache;
|
|
std::vector<UpscalerEntry> previous_cache;
|
|
{
|
|
std::lock_guard<std::mutex> lock(*rt.upscaler_mutex);
|
|
previous_cache = *rt.upscaler_cache;
|
|
}
|
|
|
|
fs::path upscaler_dir = rt.ctx_params->hires_upscalers_dir;
|
|
std::error_code ec;
|
|
if (fs::exists(upscaler_dir, ec) && !ec && fs::is_directory(upscaler_dir, ec) && !ec) {
|
|
try {
|
|
auto it = fs::directory_iterator(
|
|
upscaler_dir,
|
|
fs::directory_options::skip_permission_denied,
|
|
ec);
|
|
auto end = fs::directory_iterator();
|
|
while (!ec && it != end) {
|
|
std::error_code entry_ec;
|
|
bool is_reg = it->is_regular_file(entry_ec);
|
|
if (entry_ec || !is_reg) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
const fs::path& p = it->path();
|
|
if (!is_supported_model_ext(p)) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
|
|
UpscalerEntry upscaler_entry;
|
|
upscaler_entry.name = p.stem().u8string();
|
|
std::error_code abs_ec;
|
|
fs::path abs_path = fs::absolute(p, abs_ec);
|
|
upscaler_entry.fullpath = (abs_ec ? p : abs_path.lexically_normal()).u8string();
|
|
upscaler_entry.model_name = "ESRGAN_4x";
|
|
upscaler_entry.path = p.filename().u8string();
|
|
|
|
std::error_code size_ec;
|
|
upscaler_entry.file_size = it->file_size(size_ec);
|
|
if (size_ec) {
|
|
it.increment(ec);
|
|
continue;
|
|
}
|
|
|
|
std::error_code time_ec;
|
|
upscaler_entry.last_modified = it->last_write_time(time_ec);
|
|
auto previous = std::find_if(previous_cache.begin(), previous_cache.end(), [&](const UpscalerEntry& cached) {
|
|
return cached.fullpath == upscaler_entry.fullpath &&
|
|
cached.file_size == upscaler_entry.file_size &&
|
|
(!time_ec && cached.last_modified == upscaler_entry.last_modified);
|
|
});
|
|
upscaler_entry.image_upscale_factor = previous != previous_cache.end()
|
|
? previous->image_upscale_factor
|
|
: get_upscaler_model_scale(upscaler_entry.fullpath.c_str());
|
|
if (upscaler_entry.image_upscale_factor > 0) {
|
|
upscaler_entry.scale = upscaler_entry.image_upscale_factor;
|
|
upscaler_entry.model_name = "ESRGAN_" + std::to_string(upscaler_entry.scale) + "x";
|
|
}
|
|
|
|
new_cache.push_back(std::move(upscaler_entry));
|
|
it.increment(ec);
|
|
}
|
|
} catch (const std::exception& e) {
|
|
LOG_WARN("error while scanning upscalers directory '%s': %s", upscaler_dir.string().c_str(), e.what());
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (ec) {
|
|
LOG_WARN("error while scanning upscalers directory '%s': %s", upscaler_dir.string().c_str(), ec.message().c_str());
|
|
return;
|
|
}
|
|
|
|
std::sort(new_cache.begin(), new_cache.end(), [](const UpscalerEntry& a, const UpscalerEntry& b) {
|
|
return a.name < b.name;
|
|
});
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lock(*rt.upscaler_mutex);
|
|
*rt.upscaler_cache = std::move(new_cache);
|
|
}
|
|
}
|
|
|
|
int64_t unix_timestamp_now() {
|
|
return std::chrono::duration_cast<std::chrono::seconds>(
|
|
std::chrono::system_clock::now().time_since_epoch())
|
|
.count();
|
|
}
|