stable-diffusion.cpp/examples/common/profile.cpp
Claude 6a01873d73
feat: keep sd-server serving when a request runs out of memory
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
2026-10-11 10:40:29 +02:00

205 lines
7.4 KiB
C++

#include "profile.h"
#include <algorithm>
#include <cstdio>
#include <filesystem>
#include <system_error>
#include <vector>
namespace sd_profile {
namespace {
constexpr int64_t GiB = 1024ll * 1024ll * 1024ll;
std::string format_gib(int64_t bytes) {
char text[32];
snprintf(text, sizeof(text), "%.1f GiB", static_cast<double>(bytes) / static_cast<double>(GiB));
return text;
}
int64_t file_size_or_zero(const std::string& path) {
if (path.empty()) {
return 0;
}
std::error_code error;
const auto size = std::filesystem::file_size(path, error);
return error ? 0 : static_cast<int64_t>(size);
}
bool mentions_module(const std::string& spec, const char* name) {
return spec.find(std::string(name) + "=") != std::string::npos;
}
} // namespace
const char* level_name(Level level) {
switch (level) {
case Level::MAX:
return "max";
case Level::BALANCED:
return "balanced";
case Level::LITE:
return "lite";
case Level::LITE_DISK:
return "lite-disk";
case Level::LITE_CPU:
return "lite-cpu";
}
return "max";
}
bool parse(const std::string& text, Level& level, bool& automatic) {
automatic = false;
if (text == "max") {
level = Level::MAX;
} else if (text == "balanced") {
level = Level::BALANCED;
} else if (text == "lite") {
level = Level::LITE;
} else if (text == "auto") {
automatic = true;
} else {
return false;
}
return true;
}
Level lighter(Level level) {
switch (level) {
case Level::MAX:
return Level::BALANCED;
case Level::BALANCED:
return Level::LITE;
case Level::LITE:
return Level::LITE_DISK;
case Level::LITE_DISK:
case Level::LITE_CPU:
return Level::LITE_CPU;
}
return Level::LITE_CPU;
}
Resources probe(const SDContextParams& ctx) {
Resources resources;
const std::vector<const std::string*> files = {
&ctx.model_path, &ctx.diffusion_model_path, &ctx.high_noise_diffusion_model_path,
&ctx.uncond_diffusion_model_path, &ctx.clip_l_path, &ctx.clip_g_path, &ctx.clip_vision_path,
&ctx.t5xxl_path, &ctx.llm_path, &ctx.llm_vision_path, &ctx.vae_path, &ctx.control_net_path,
&ctx.ip_adapter_path, &ctx.motion_module_path, &ctx.photo_maker_path, &ctx.pulid_weights_path};
for (const std::string* path : files) {
resources.model_bytes += file_size_or_zero(*path);
}
sd_system_memory_t memory;
if (sd_get_system_memory(&memory) && memory.available_bytes > 0) {
resources.ram_available = static_cast<int64_t>(memory.available_bytes);
}
// An integrated GPU draws on the system RAM, so only discrete GPUs and accelerators count.
for (size_t i = 0; i < sd_get_device_count(); ++i) {
sd_device_info_t info;
if (!sd_get_device_info(i, &info)) {
continue;
}
if (info.type == SD_DEVICE_TYPE_GPU || info.type == SD_DEVICE_TYPE_ACCEL) {
resources.gpu_free = std::max<int64_t>(resources.gpu_free, static_cast<int64_t>(info.free_memory_bytes));
}
}
return resources;
}
Level choose(const Resources& resources, std::string* reason) {
auto explain = [&](const std::string& text) {
if (reason != nullptr) {
*reason = text;
}
};
if (resources.model_bytes <= 0) {
explain("the size of the model is unknown");
return Level::MAX;
}
if (resources.ram_available < 0 && resources.gpu_free <= 0) {
explain("the memory of this machine is unknown");
return Level::MAX;
}
const int64_t reserve = GiB + resources.model_bytes / 5;
const int64_t need = resources.model_bytes + reserve;
const int64_t ram = std::max<int64_t>(resources.ram_available, 0);
const int64_t fast = resources.gpu_free > 0 ? resources.gpu_free : ram;
std::string facts = "model " + format_gib(resources.model_bytes) + " + " + format_gib(reserve) + " working memory, ";
facts += resources.ram_available >= 0 ? "RAM available " + format_gib(ram) : std::string("RAM unknown");
if (resources.gpu_free > 0) {
facts += ", GPU free " + format_gib(resources.gpu_free);
}
if (need + need / 4 <= fast && (resources.ram_available < 0 || ram >= GiB)) {
explain(facts + ": fits with room to spare");
return Level::MAX;
}
if (need <= std::max(fast, ram)) {
explain(facts + ": fits with little margin");
return Level::BALANCED;
}
explain(facts + ": does not fit, weights will be streamed");
return Level::LITE;
}
void apply(Level level, SDContextParams& ctx, SDGenerationParams& gen, bool respect_explicit) {
auto free_to_set = [&](const char* option) {
return !respect_explicit || !option_was_given(option);
};
if (level >= Level::BALANCED && free_to_set("--memory-guard")) {
const int target = level >= Level::LITE ? 85 : 90;
ctx.memory_guard = ctx.memory_guard <= 0 ? target : std::min(ctx.memory_guard, target);
}
if (level >= Level::LITE) {
if ((free_to_set("--backend") || ctx.backend.empty()) &&
!mentions_module(ctx.backend, "te") && !mentions_module(ctx.backend, "clip")) {
ctx.clip_on_cpu = true;
}
gen.vae_tiling_params.enabled = true;
if (free_to_set("--batched-cfg")) {
ctx.batched_cfg = false;
}
}
if (level >= Level::LITE_DISK && free_to_set("--params-backend")) {
ctx.params_backend = "disk";
ctx.offload_params_to_cpu = false;
ctx.eager_load = false;
}
if (level >= Level::LITE_CPU && free_to_set("--backend")) {
ctx.backend = "cpu";
ctx.clip_on_cpu = false;
ctx.vae_on_cpu = false;
ctx.control_net_cpu = false;
}
}
bool apply_from_options(SDContextParams& ctx, SDGenerationParams& gen, Level& applied) {
applied = Level::MAX;
if (ctx.profile.empty()) {
return true;
}
Level level = Level::MAX;
bool automatic = false;
if (!parse(ctx.profile, level, automatic)) {
LOG_ERROR("error: --profile must be one of max, balanced, lite, auto (got '%s')", ctx.profile.c_str());
return false;
}
if (automatic) {
std::string reason;
level = choose(probe(ctx), &reason);
LOG_INFO("profile auto -> %s (%s)", level_name(level), reason.c_str());
} else {
LOG_INFO("profile %s", level_name(level));
}
apply(level, ctx, gen, /*respect_explicit=*/true);
applied = level;
return true;
}
} // namespace sd_profile