diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 4a22df2b..ca4f31dc 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -602,7 +602,7 @@ ArgOptions SDContextParams::get_options() { &max_vram}, {"", "--profile", - "resource profile: max (engine defaults), balanced (memory guard at 90), lite (also text encoder on the CPU, tiled VAE, unbatched CFG, guard at 85) " + "resource profile: max (engine defaults), balanced (memory guard at 90), lite (also tiled VAE, unbatched CFG, guard at 85 and every GPU of the backend; the compute stays on the GPUs) " "or auto (picks one from the model size, the free RAM and the free GPU memory). Options given explicitly on the command line always win", 0, &profile}, diff --git a/examples/common/profile.cpp b/examples/common/profile.cpp index 4b4552a9..2d3dec3b 100644 --- a/examples/common/profile.cpp +++ b/examples/common/profile.cpp @@ -44,10 +44,19 @@ namespace sd_profile { return family; } - bool multi_gpu_off(const std::string& mode) { - std::string lowered = mode; + std::string lowercase(const std::string& text) { + std::string lowered = text; std::transform(lowered.begin(), lowered.end(), lowered.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); - return lowered == "off"; + return lowered; + } + + bool multi_gpu_off(const std::string& mode) { + return lowercase(mode) == "off"; + } + + bool multi_gpu_unset_or_auto(const std::string& mode) { + const std::string lowered = lowercase(mode); + return lowered.empty() || lowered == "auto"; } } // namespace @@ -62,6 +71,8 @@ namespace sd_profile { return "lite"; case Level::LITE_DISK: return "lite-disk"; + case Level::LITE_HYBRID: + return "lite-hybrid"; case Level::LITE_CPU: return "lite-cpu"; } @@ -93,6 +104,8 @@ namespace sd_profile { case Level::LITE: return Level::LITE_DISK; case Level::LITE_DISK: + return Level::LITE_HYBRID; + case Level::LITE_HYBRID: case Level::LITE_CPU: return Level::LITE_CPU; } @@ -223,20 +236,24 @@ namespace sd_profile { 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 (free_to_set("--multi-gpu") && multi_gpu_unset_or_auto(ctx.multi_gpu)) { + ctx.multi_gpu = "on"; + } } 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_HYBRID && + (free_to_set("--backend") || ctx.backend.empty()) && + !mentions_module(ctx.backend, "te") && !mentions_module(ctx.backend, "clip")) { + ctx.clip_on_cpu = true; + } if (level >= Level::LITE_CPU && free_to_set("--backend")) { ctx.backend = "cpu"; ctx.clip_on_cpu = false; diff --git a/examples/common/profile.h b/examples/common/profile.h index 6d5c1eee..e8dbbe95 100644 --- a/examples/common/profile.h +++ b/examples/common/profile.h @@ -12,13 +12,16 @@ namespace sd_profile { // From the lightest on resources to the heaviest. The levels after LITE are not selectable from - // the command line: a server steps down to them when a request runs out of memory. + // the command line: a server steps down to them when a request runs out of memory. Every level up to + // LITE_DISK trades memory for time and keeps all the compute on the GPUs; the CPU takes over only + // from LITE_HYBRID on, the text encoder first and everything at LITE_CPU. enum class Level { - MAX, // the defaults of the engine - BALANCED, // memory guard at 90 - LITE, // + text encoder on the CPU, tiled VAE, unbatched CFG, memory guard at 85 - LITE_DISK, // + weights streamed from disk - LITE_CPU, // + every module computed on the CPU + MAX, // the defaults of the engine + BALANCED, // memory guard at 90 + LITE, // + tiled VAE, unbatched CFG, memory guard at 85, every GPU of the backend used + LITE_DISK, // + weights streamed from disk + LITE_HYBRID, // + text encoder computed on the CPU + LITE_CPU, // + every module computed on the CPU }; const char* level_name(Level level); diff --git a/examples/server/main.cpp b/examples/server/main.cpp index 4f06a1f4..c45caf4c 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -167,6 +167,17 @@ int main(int argc, const char** argv) { } else { LOG_INFO("a request that runs out of memory makes the server step down: %s", keeper.describe_ladder().c_str()); } + const std::string fallback_devices = keeper.describe_devices(); + if (!fallback_devices.empty()) { + LOG_INFO("a device that fails is replaced by the next one before the cpu takes over: %s", fallback_devices.c_str()); + } + const nlohmann::json health = keeper.health_json(); + LOG_INFO("the model runs on device '%s' with profile %s", + health["device"].get().c_str(), + health["profile"].get().c_str()); + if (!health["cpu_modules"].empty()) { + LOG_WARN("the cpu does the work of: %s (the GPUs do the rest)", health["cpu_modules"].dump().c_str()); + } } else { LOG_WARN( "starting without a model: device and upscale endpoints work, " diff --git a/examples/server/recovery.cpp b/examples/server/recovery.cpp index 531c6e8e..64770488 100644 --- a/examples/server/recovery.cpp +++ b/examples/server/recovery.cpp @@ -5,6 +5,7 @@ #include "recovery.h" #include +#include #include #include #include @@ -43,6 +44,23 @@ namespace { return false; } + std::vector list_devices() { + std::vector devices; + const size_t count = sd_get_device_count(); + for (size_t i = 0; i < count; ++i) { + sd_device_info_t info; + if (sd_get_device_info(i, &info)) { + devices.push_back(info); + } + } + return devices; + } + + std::string lowercase(std::string text) { + std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + return text; + } + GenerationFailure capture_failure() { GenerationFailure failure; char message[1024]; @@ -150,6 +168,9 @@ static ContextKeeper::Hooks with_defaults(ContextKeeper::Hooks hooks) { if (!hooks.has_accelerator) { hooks.has_accelerator = has_accelerator; } + if (!hooks.list_devices) { + hooks.list_devices = list_devices; + } if (!hooks.now) { hooks.now = [] { return ContextKeeper::Clock::now(); }; } @@ -173,6 +194,8 @@ ContextKeeper::ContextKeeper(const SDContextParams& base_params, backend_choice_.params_backend = base_params.params_backend; backend_choice_.diffusion_conv_direct = base_params.diffusion_conv_direct; backend_choice_.n_threads = base_params.n_threads; + accelerator_ = hooks_.has_accelerator(); + devices_ = make_devices(); ladder_ = make_ladder(); } @@ -191,12 +214,32 @@ bool ContextKeeper::can_step_down() const { return settings_.degradation && ladder_.size() > 1; } -std::unique_ptr ContextKeeper::params_for(sd_profile::Level level) const { +std::string ContextKeeper::describe_devices() const { + std::lock_guard state(state_mutex_); + std::string text; + for (const std::string& name : devices_) { + text += text.empty() ? "" : " > "; + text += name; + } + return text; +} + +std::unique_ptr ContextKeeper::params_for(sd_profile::Level level, size_t slot) const { auto params = std::make_unique(base_params_); if (level > base_level_) { SDGenerationParams unused; sd_profile::apply(level, *params, unused, /*respect_explicit=*/false); } + // The cpu profile names the cpu itself; below it, a device that fails to start must fail the load, not become a + // quiet cpu fallback, as long as the keeper has somewhere else to go. + if (level != sd_profile::Level::LITE_CPU && lowercase(params->backend) != "cpu") { + if (slot > 0 && slot <= devices_.size()) { + params->backend = devices_[slot - 1]; + } + if (settings_.degradation && accelerator_) { + params->disable_backend_fallback = true; + } + } return params; } @@ -212,11 +255,11 @@ std::vector ContextKeeper::make_ladder() const { std::vector ladder; ladder.push_back(base_level_); std::string previous = fingerprint(base_level_); - const bool accelerator = hooks_.has_accelerator(); sd_profile::Level level = base_level_; while (level != sd_profile::Level::LITE_CPU) { level = sd_profile::lighter(level); - if (level == sd_profile::Level::LITE_CPU && !accelerator) { + // With no accelerator everything already runs on the CPU: the levels that hand work to it would only reload the model. + if (!accelerator_ && level >= sd_profile::Level::LITE_HYBRID) { break; } const std::string current = fingerprint(level); @@ -229,19 +272,110 @@ std::vector ContextKeeper::make_ladder() const { return ladder; } +std::vector ContextKeeper::make_devices() const { + std::vector names; + if (!settings_.degradation || !accelerator_) { + return names; + } + // A placement the host wrote itself (modules assigned to devices, several devices for one module) or a request + // for the cpu is not rewritten; a single device it named is the engine's choice, so it is not an alternative. + const std::string pinned = lowercase(base_params_.backend); + if (pinned.find_first_of("=&,") != std::string::npos || pinned == "cpu") { + return names; + } + + struct Candidate { + std::string name; + int group; // 0 graphics cards, 1 accelerators, 2 integrated GPUs + int rank; // 0 the backend of the vendor, 1 a generic graphics API + uint64_t free_bytes; + }; + std::vector found; + for (const sd_device_info_t& device : hooks_.list_devices()) { + const std::string name = device.name; + const std::string lowered = lowercase(name); + if (name.empty() || device.type == SD_DEVICE_TYPE_CPU || device.type == SD_DEVICE_TYPE_UNKNOWN) { + continue; + } + // The model would be sent over the network, which a device failing here is no reason to do. + if (lowered.compare(0, 3, "rpc") == 0 || lowered == pinned) { + continue; + } + const int group = device.type == SD_DEVICE_TYPE_GPU ? 0 : (device.type == SD_DEVICE_TYPE_ACCEL ? 1 : 2); + const int rank = lowered.find("vulkan") != std::string::npos || lowered.find("opencl") != std::string::npos ? 1 : 0; + found.push_back({name, group, rank, device.free_memory_bytes}); + } + std::stable_sort(found.begin(), found.end(), [](const Candidate& a, const Candidate& b) { + if (a.group != b.group) { + return a.group < b.group; + } + if (a.rank != b.rank) { + return a.rank < b.rank; + } + return a.free_bytes > b.free_bytes; + }); + for (const Candidate& candidate : found) { + names.push_back(candidate.name); + } + return names; +} + +ContextKeeper::Rung ContextKeeper::next_rung(size_t index, size_t slot, const GenerationFailure& failure, bool retry_available) const { + Rung next; + const size_t last = ladder_.size() - 1; + if (failure.code != SD_ERROR_BACKEND) { + // Out of memory: the next lighter profile, on the device the model runs on. + if (index < last) { + next.index = index + 1; + next.slot = slot; + next.valid = true; + } + return next; + } + + // A failing backend is not cured by trimming memory: change where the model runs, the cpu last. + const bool on_cpu = ladder_[index] == sd_profile::Level::LITE_CPU; + if (on_cpu) { + return next; + } + if (retry_available) { + next.index = index; + next.slot = slot; + next.valid = true; + next.retry = true; + } else if (slot < devices_.size()) { + next.index = index; + next.slot = slot + 1; + next.valid = true; + } else if (index != last) { + next.index = last; + next.valid = true; + } + return next; +} + +std::string ContextKeeper::rung_text(size_t index, size_t slot) const { + std::string text = std::string("profile ") + sd_profile::level_name(ladder_[index]); + if (slot > 0 && slot <= devices_.size() && ladder_[index] != sd_profile::Level::LITE_CPU) { + text += " on " + devices_[slot - 1]; + } + return text; +} + bool ContextKeeper::start(GenerationFailure& failure) { std::lock_guard lock(mutex_); return load_locked(failure); } bool ContextKeeper::load_locked(GenerationFailure& failure) { - failure = GenerationFailure(); - if (!build_from(0, failure)) { + failure = GenerationFailure(); + bool retry_used = false; + if (!build_from(0, 0, failure, retry_used)) { return false; } { std::lock_guard state(state_mutex_); - if (index_ > 0) { + if (index_ > 0 || slot_ > 0) { next_promotion_ = hooks_.now() + std::chrono::seconds(cooldown_seconds_); } } @@ -262,11 +396,16 @@ bool ContextKeeper::load(const SDContextParams& params, GenerationFailure& failu std::lock_guard state(state_mutex_); base_params_ = params; } + accelerator_ = hooks_.has_accelerator(); + std::vector devices = make_devices(); std::vector ladder = make_ladder(); { std::lock_guard state(state_mutex_); + devices_ = std::move(devices); ladder_ = std::move(ladder); index_ = 0; + slot_ = 0; + resume_index_ = SIZE_MAX; probation_ = false; cooldown_seconds_ = std::max(settings_.cooldown_seconds, 0); restore_not_before_ = Clock::time_point(); @@ -288,6 +427,8 @@ void ContextKeeper::unload() { std::lock_guard state(state_mutex_); index_ = 0; + slot_ = 0; + resume_index_ = SIZE_MAX; probation_ = false; cooldown_seconds_ = std::max(settings_.cooldown_seconds, 0); restore_not_before_ = Clock::time_point(); @@ -317,13 +458,13 @@ void ContextKeeper::note_build_failure(const GenerationFailure& failure) { restore_failure_ = failure; } -bool ContextKeeper::try_build(size_t index, GenerationFailure& failure) { +bool ContextKeeper::try_build(size_t index, size_t slot, GenerationFailure& failure) { const sd_profile::Level level = ladder_[index]; - std::unique_ptr params = params_for(level); + std::unique_ptr params = params_for(level, slot); // The context may keep pointing into these strings, so they stay where they are for as long as it lives. sd_ctx_params_t raw = params->to_sd_ctx_params_t(); - LOG_INFO("loading the model with profile %s", sd_profile::level_name(level)); + LOG_INFO("loading the model with %s", rung_text(index, slot).c_str()); SDCtxPtr ctx = hooks_.create_context(raw, failure); if (ctx == nullptr) { if (failure.code == SD_ERROR_NONE) { @@ -331,8 +472,8 @@ bool ContextKeeper::try_build(size_t index, GenerationFailure& failure) { failure.message = "the model could not be loaded"; } record_error(failure); - LOG_WARN("the model could not be loaded with profile %s: %s: %s", - sd_profile::level_name(level), + LOG_WARN("the model could not be loaded with %s: %s: %s", + rung_text(index, slot).c_str(), sd_error_code_name(failure.code), failure.message.c_str()); return false; @@ -344,7 +485,12 @@ bool ContextKeeper::try_build(size_t index, GenerationFailure& failure) { ctx_params_ = std::move(params); { std::lock_guard state(state_mutex_); - index_ = index; + const bool on_cpu = level == sd_profile::Level::LITE_CPU; + index_ = index; + slot_ = on_cpu ? 0 : slot; + if (!on_cpu) { + resume_index_ = SIZE_MAX; + } has_ctx_ = true; if (model_loaded_) { ++counters_.rebuilds; @@ -353,14 +499,29 @@ bool ContextKeeper::try_build(size_t index, GenerationFailure& failure) { backend_choice_.params_backend = ctx_params_->params_backend; backend_choice_.diffusion_conv_direct = ctx_params_->diffusion_conv_direct; backend_choice_.n_threads = ctx_params_->n_threads; + device_ = ctx_params_->backend.empty() ? "auto" : ctx_params_->backend; + cpu_modules_.clear(); + if (lowercase(ctx_params_->backend) == "cpu") { + cpu_modules_.push_back("all"); + } else { + if (ctx_params_->clip_on_cpu) { + cpu_modules_.push_back("text_encoder"); + } + if (ctx_params_->vae_on_cpu) { + cpu_modules_.push_back("vae"); + } + if (ctx_params_->control_net_cpu) { + cpu_modules_.push_back("controlnet"); + } + } } supports_image_ = image; supports_video_ = video; - LOG_INFO("the model is loaded (profile %s)", sd_profile::level_name(level)); + LOG_INFO("the model is loaded (%s)", rung_text(index, slot).c_str()); return true; } -bool ContextKeeper::build_from(size_t index, GenerationFailure& failure) { +bool ContextKeeper::build_from(size_t index, size_t slot, GenerationFailure& failure, bool& retry_used, bool only_this) { { std::lock_guard state(state_mutex_); rebuilding_ = true; @@ -374,27 +535,38 @@ bool ContextKeeper::build_from(size_t index, GenerationFailure& failure) { } done{*this}; while (index < ladder_.size()) { - if (try_build(index, failure)) { + if (try_build(index, slot, failure)) { return true; } - if (!settings_.degradation || !failure_is_recoverable(failure.code)) { + if (only_this || !settings_.degradation || !failure_is_recoverable(failure.code)) { return false; } - // A failing backend is not cured by trimming memory: go straight to the profile that avoids the devices. - size_t next = index + 1; - if (failure.code == SD_ERROR_BACKEND && ladder_.size() > next) { - next = ladder_.size() - 1; + const Rung next = next_rung(index, slot, failure, !retry_used); + if (!next.valid) { + return false; } - if (next < ladder_.size()) { - LOG_WARN("trying profile %s instead of %s", sd_profile::level_name(ladder_[next]), sd_profile::level_name(ladder_[index])); - } - index = next; + LOG_WARN("trying %s instead of %s", rung_text(next.index, next.slot).c_str(), rung_text(index, slot).c_str()); + retry_used = retry_used || next.retry; + note_move(index, next, failure); + index = next.index; + slot = next.slot; } return false; } +void ContextKeeper::note_move(size_t from_index, const Rung& to, const GenerationFailure& failure) { + // The climb back from the cpu profile returns to the profile that was running when the device failed. + if (failure.code != SD_ERROR_BACKEND || to.retry || ladder_[to.index] != sd_profile::Level::LITE_CPU || + ladder_[from_index] == sd_profile::Level::LITE_CPU) { + return; + } + std::lock_guard state(state_mutex_); + resume_index_ = from_index; +} + bool ContextKeeper::restore(GenerationFailure& failure) { size_t index = 0; + size_t slot = 0; { std::lock_guard state(state_mutex_); const auto now = hooks_.now(); @@ -407,13 +579,15 @@ bool ContextKeeper::restore(GenerationFailure& failure) { return false; } index = index_; + slot = slot_; } LOG_WARN("the model is not loaded; loading it again"); GenerationFailure rebuild_failure; - if (build_from(index, rebuild_failure)) { + bool retry_used = false; + if (build_from(index, slot, rebuild_failure, retry_used)) { std::lock_guard state(state_mutex_); - if (index_ > 0) { + if (index_ > 0 || slot_ > 0) { next_promotion_ = hooks_.now() + std::chrono::seconds(cooldown_seconds_); } return true; @@ -425,30 +599,39 @@ bool ContextKeeper::restore(GenerationFailure& failure) { return false; } -bool ContextKeeper::step_down(GenerationFailure& failure) { - size_t from = 0; +bool ContextKeeper::step_down(GenerationFailure& failure, bool& retry_used) { + size_t from = 0; + size_t from_slot = 0; { std::lock_guard state(state_mutex_); - from = index_; + from = index_; + from_slot = slot_; } - const size_t last = ladder_.size() - 1; - if (from >= last) { - LOG_ERROR("%s with profile %s and no lighter profile is left: %s", + const Rung to = next_rung(from, from_slot, failure, !retry_used); + if (!to.valid) { + LOG_ERROR("%s with %s and no other device or lighter profile is left: %s", sd_error_code_name(failure.code), - sd_profile::level_name(ladder_[from]), + rung_text(from, from_slot).c_str(), failure.message.c_str()); return false; } - const size_t to = failure.code == SD_ERROR_BACKEND ? last : from + 1; - LOG_WARN("%s with profile %s: %s; loading the model again with profile %s to run the request again", + LOG_WARN("%s with %s: %s; loading the model again with %s%s to run the request again", sd_error_code_name(failure.code), - sd_profile::level_name(ladder_[from]), + rung_text(from, from_slot).c_str(), failure.message.c_str(), - sd_profile::level_name(ladder_[to])); + rung_text(to.index, to.slot).c_str(), + to.retry ? " (the same configuration, in case the failure was a passing one)" : ""); { std::lock_guard state(state_mutex_); - ++counters_.step_downs; + if (to.retry) { + ++counters_.retries; + retry_used = true; + } else if (failure.code == SD_ERROR_BACKEND) { + ++counters_.device_switches; + } else { + ++counters_.step_downs; + } if (probation_) { probation_ = false; ++counters_.failed_promotions; @@ -459,12 +642,14 @@ bool ContextKeeper::step_down(GenerationFailure& failure) { // The old context goes first: both would not fit. release_context(); + note_move(from, to, failure); GenerationFailure rebuild_failure; - if (!build_from(to, rebuild_failure)) { + if (!build_from(to.index, to.slot, rebuild_failure, retry_used)) { { - // The next attempt to load the model starts from the profile that was just tried. + // The next attempt to load the model starts from the rung that was just tried. std::lock_guard state(state_mutex_); - index_ = to; + index_ = to.index; + slot_ = ladder_[to.index] == sd_profile::Level::LITE_CPU ? 0 : to.slot; } note_build_failure(rebuild_failure); failure = rebuild_failure; @@ -479,23 +664,38 @@ void ContextKeeper::promote_if_due() { if (!settings_.degradation || settings_.cooldown_seconds <= 0 || ctx_ == nullptr) { return; } - size_t index = 0; + size_t index = 0; + size_t slot = 0; + size_t resume = SIZE_MAX; { std::lock_guard state(state_mutex_); - if (index_ == 0 || hooks_.now() < next_promotion_) { + if ((index_ == 0 && slot_ == 0) || hooks_.now() < next_promotion_) { return; } - index = index_; + index = index_; + slot = slot_; + resume = resume_index_; } - const size_t target = index - 1; - LOG_INFO("trying profile %s again", sd_profile::level_name(ladder_[target])); + // From a GPU the climb makes one attempt: the preferred device first, then one profile up. From the cpu profile it + // goes back to the profile the server had when the device failed, and offers every device again, so that the + // best one that works is found even if the preferred one does not. + const bool from_cpu = ladder_[index] == sd_profile::Level::LITE_CPU; + size_t target = index; + if (from_cpu) { + target = resume < index ? resume : index - 1; + } else if (slot == 0) { + target = index - 1; + } + LOG_INFO("trying %s again", rung_text(target, 0).c_str()); release_context(); GenerationFailure failure; - bool built = build_from(target, failure); + bool retry_used = false; + bool built = build_from(target, 0, failure, retry_used, /*only_this=*/!from_cpu); if (!built) { - // The profile in use before the climb worked, so give it another go before giving up. - built = build_from(index, failure); + // The rung in use before the climb worked, so give it another go before giving up. + retry_used = false; + built = build_from(index, slot, failure, retry_used); } if (!built) { @@ -503,7 +703,7 @@ void ContextKeeper::promote_if_due() { return; } std::lock_guard state(state_mutex_); - if (index_ <= target) { + if (index_ < index || (index_ == index && slot_ < slot)) { ++counters_.promotions; probation_ = true; } else { @@ -592,6 +792,8 @@ bool ContextKeeper::run(const Attempt& attempt, GenerationFailure& failure, cons } bool stepped_down = false; + // One request loads the same configuration again once, however many times it fails afterwards. + bool retry_used = false; // The wait before the next climb counts from the end of a request that had to step down, not from its // start: reloading the model and generating on a lighter profile can take longer than the wait itself. struct Rearm { @@ -650,7 +852,7 @@ bool ContextKeeper::run(const Attempt& attempt, GenerationFailure& failure, cons if (!settings_.degradation || !failure_is_recoverable(failure.code)) { return fail(); } - if (!step_down(failure)) { + if (!step_down(failure, retry_used)) { return fail(); } stepped_down = true; @@ -672,7 +874,7 @@ ContextKeeper::Status ContextKeeper::status_locked() const { if (!has_ctx_) { return Status::UNAVAILABLE; } - return index_ > 0 ? Status::DEGRADED : Status::OK; + return index_ > 0 || slot_ > 0 ? Status::DEGRADED : Status::OK; } const char* ContextKeeper::status_text(Status status) { @@ -706,15 +908,22 @@ nlohmann::json ContextKeeper::health_json() const { out["model_loaded"] = model_loaded_.load(); out["profile"] = model_loaded_ ? nlohmann::json(sd_profile::level_name(ladder_[index_])) : nlohmann::json(nullptr); out["base_profile"] = sd_profile::level_name(base_level_); - out["degradation"] = settings_.degradation; - out["busy"] = active_runs_ > 0; - out["counters"] = { + // Where the compute runs: the backend the context was asked for ("auto" leaves the choice to the engine, "cpu" is + // the cpu profile) and the modules that were given to the cpu next to it ("all" for the cpu profile). + out["device"] = model_loaded_ ? nlohmann::json(device_) : nlohmann::json(nullptr); + out["cpu_modules"] = model_loaded_ ? nlohmann::json(cpu_modules_) : nlohmann::json(nullptr); + out["fallback_devices"] = devices_; + out["degradation"] = settings_.degradation; + out["busy"] = active_runs_ > 0; + out["counters"] = { {"requests", counters_.requests}, {"succeeded", counters_.succeeded}, {"failed", counters_.failed}, {"cancelled", counters_.cancelled}, {"recovered", counters_.recovered}, {"step_downs", counters_.step_downs}, + {"retries", counters_.retries}, + {"device_switches", counters_.device_switches}, {"promotions", counters_.promotions}, {"failed_promotions", counters_.failed_promotions}, {"rebuilds", counters_.rebuilds}, @@ -728,7 +937,7 @@ nlohmann::json ContextKeeper::health_json() const { {"at", last_error_.at}, }; } - if (model_loaded_ && has_ctx_ && index_ > 0 && settings_.degradation && settings_.cooldown_seconds > 0) { + if (model_loaded_ && has_ctx_ && (index_ > 0 || slot_ > 0) && settings_.degradation && settings_.cooldown_seconds > 0) { const auto remaining = std::chrono::duration_cast(next_promotion_ - now).count(); out["next_promotion_seconds"] = std::max(remaining, 0); } else { diff --git a/examples/server/recovery.h b/examples/server/recovery.h index b6ac1e44..8b3e57f0 100644 --- a/examples/server/recovery.h +++ b/examples/server/recovery.h @@ -54,8 +54,19 @@ std::string safe_json_dump(const nlohmann::json& value); // // A request that fails because the machine ran out of memory (or because a backend failed) makes the // keeper free the context, load the model again with the next lighter profile of the ladder -// max > balanced > lite > lite-disk > lite-cpu, and run the same request again. Once the machine has been -// quiet for a while, it climbs back one step at a time; a climb that fails doubles the wait. +// max > balanced > lite > lite-disk > lite-hybrid > lite-cpu, and run the same request again. The levels up to +// lite-disk keep all the compute on the GPUs; the CPU takes the text encoder at lite-hybrid and everything at +// lite-cpu, so it is the last resort. Once the machine has been quiet for a while, the keeper climbs back one +// step at a time; a climb that fails doubles the wait. +// +// A backend failure (a device that does not start, or fails while computing) is a different matter: a lighter +// profile does not cure it, so the keeper keeps the profile and changes where the model runs. It loads the model +// again with the same configuration once, in case the failure was passing; then it tries every other device in +// turn, the GPUs best first (the same card on another backend, other cards) and the integrated GPU last; the +// CPU takes over only when none of them works. While a GPU is left to try, the engine is told not to fall back to +// the CPU by itself, so that a device that fails to start is not turned into a slow server unnoticed. The +// climb back leads to the preferred device first, and from the CPU straight to the profile it was running when the +// device failed. // // The mutex returned by mutex() serializes everything that uses the compute devices: it is held for // the whole of a run() and by the upscale endpoint. Reading the health or the resources never takes it. @@ -77,6 +88,8 @@ public: std::function read_failure; // Whether a device other than the CPU is present. Default: asks the library. std::function has_accelerator; + // The devices of the machine, in the order the library lists them. Default: sd_get_device_info(). + std::function()> list_devices; std::function now; // Asks the library to stop the generation running on a context. Default: sd_cancel_generation(SD_CANCEL_ALL). std::function cancel_context; @@ -159,6 +172,9 @@ public: // The profiles the server can step down through, e.g. "max > lite > lite-cpu". std::string describe_ladder() const; bool can_step_down() const; + // The devices tried, in this order, after the engine's own choice failed, e.g. "CUDA0 > Vulkan0 > Vulkan1"; + // empty when none is offered (no accelerator, degradation disabled, or a placement written by the host). + std::string describe_devices() const; nlohmann::json health_json() const; // "ok", "degraded", "recovering", "unavailable" or "no_model" @@ -178,6 +194,8 @@ private: uint64_t cancelled = 0; // stopped on request; neither a success nor a failure uint64_t recovered = 0; // requests that succeeded after a step down uint64_t step_downs = 0; + uint64_t retries = 0; // a backend failure answered by loading the same configuration again + uint64_t device_switches = 0; // a backend failure answered by another device, the cpu included uint64_t promotions = 0; uint64_t failed_promotions = 0; uint64_t rebuilds = 0; @@ -189,16 +207,34 @@ private: int64_t at = 0; }; - std::unique_ptr params_for(sd_profile::Level level) const; + // Where the model runs: a profile of the ladder, on a device. Slot 0 leaves the choice of device to the engine; + // slot k > 0 names devices_[k - 1], which the keeper tries after the engine's own choice failed. + struct Rung { + size_t index = 0; + size_t slot = 0; + bool valid = false; + bool retry = false; // the rung that just failed, loaded again + }; + + std::unique_ptr params_for(sd_profile::Level level, size_t slot = 0) const; std::string fingerprint(sd_profile::Level level) const; bool force_tiling_at(sd_profile::Level level) const; std::vector make_ladder() const; + std::vector make_devices() const; + // Where to try next after failure at (index, slot); not valid when nothing is left. The same rung again is + // offered once (retry_available) for a backend failure, then the other devices, then the lightest profile. + Rung next_rung(size_t index, size_t slot, const GenerationFailure& failure, bool retry_available) const; + std::string rung_text(size_t index, size_t slot) const; bool load_locked(GenerationFailure& failure); - bool build_from(size_t index, GenerationFailure& failure); - bool try_build(size_t index, GenerationFailure& failure); + // Loads the model at (index, slot) and, unless only_this, keeps moving to the next rung while the failure is one + // a lighter profile or another device can get around. retry_used is shared with the caller, so that one request + // never loads the same rung again twice. + bool build_from(size_t index, size_t slot, GenerationFailure& failure, bool& retry_used, bool only_this = false); + bool try_build(size_t index, size_t slot, GenerationFailure& failure); bool restore(GenerationFailure& failure); - bool step_down(GenerationFailure& failure); + bool step_down(GenerationFailure& failure, bool& retry_used); + void note_move(size_t from_index, const Rung& to, const GenerationFailure& failure); void promote_if_due(); void release_context(); void note_build_failure(const GenerationFailure& failure); @@ -214,6 +250,8 @@ private: SDContextParams base_params_; const sd_profile::Level base_level_; std::vector ladder_; + bool accelerator_ = false; + std::vector devices_; // the devices of slots 1, 2, ...: best first // Held for the whole of a run(); guards ctx_ and the parameters it was created with. std::mutex mutex_; @@ -222,7 +260,14 @@ private: // Small lock for the figures health reads; always taken after mutex_ when both are needed. mutable std::mutex state_mutex_; - size_t index_ = 0; // position in ladder_ + size_t index_ = 0; // position in ladder_ + size_t slot_ = 0; // the device of the context in use: 0 = the engine's own choice, k = devices_[k - 1] + // The profile the server was running when a backend failure sent it to the cpu profile; the climb back from + // the cpu returns to it. SIZE_MAX when the cpu profile was reached by running out of memory. + size_t resume_index_ = SIZE_MAX; + // What the context in use was asked for, as health reports it. + std::string device_ = "auto"; + std::vector cpu_modules_; bool has_ctx_ = false; bool rebuilding_ = false; bool probation_ = false; // the context in use is a promotion nobody has tried yet diff --git a/test/profile_test.cpp b/test/profile_test.cpp index 947705ee..49962e18 100644 --- a/test/profile_test.cpp +++ b/test/profile_test.cpp @@ -79,6 +79,7 @@ int main() { strcmp(sd_profile::level_name(Level::BALANCED), "balanced") == 0 && strcmp(sd_profile::level_name(Level::LITE), "lite") == 0 && strcmp(sd_profile::level_name(Level::LITE_DISK), "lite-disk") == 0 && + strcmp(sd_profile::level_name(Level::LITE_HYBRID), "lite-hybrid") == 0 && strcmp(sd_profile::level_name(Level::LITE_CPU), "lite-cpu") == 0, "level names"); @@ -88,14 +89,15 @@ int main() { CHECK(sd_profile::parse("balanced", level, automatic) && level == Level::BALANCED && !automatic, "parse balanced"); CHECK(sd_profile::parse("max", level, automatic) && level == Level::MAX && !automatic, "parse max"); CHECK(sd_profile::parse("auto", level, automatic) && automatic, "parse auto"); - CHECK(!sd_profile::parse("lite-disk", level, automatic) && !sd_profile::parse("", level, automatic) && + CHECK(!sd_profile::parse("lite-disk", level, automatic) && !sd_profile::parse("lite-hybrid", level, automatic) && + !sd_profile::parse("lite-cpu", level, automatic) && !sd_profile::parse("", level, automatic) && !sd_profile::parse("LITE", level, automatic) && !sd_profile::parse("fast", level, automatic), "the steps below lite and unknown names are not accepted"); CHECK(sd_profile::lighter(Level::MAX) == Level::BALANCED && sd_profile::lighter(Level::BALANCED) == Level::LITE && - sd_profile::lighter(Level::LITE) == Level::LITE_DISK && sd_profile::lighter(Level::LITE_DISK) == Level::LITE_CPU && - sd_profile::lighter(Level::LITE_CPU) == Level::LITE_CPU, - "lighter walks down the steps and stops at the last one"); + sd_profile::lighter(Level::LITE) == Level::LITE_DISK && sd_profile::lighter(Level::LITE_DISK) == Level::LITE_HYBRID && + sd_profile::lighter(Level::LITE_HYBRID) == Level::LITE_CPU && sd_profile::lighter(Level::LITE_CPU) == Level::LITE_CPU, + "lighter walks down the steps, the CPU last, and stops at the last one"); check_choice("unknown model size", resources(0, 8, 0), Level::MAX); check_choice("unknown memory", resources(2, -1, 0), Level::MAX); @@ -170,12 +172,41 @@ int main() { { Parsed p({}); sd_profile::apply(Level::LITE, p.ctx, p.gen, true); - CHECK(p.ok && p.ctx.memory_guard == 85 && p.ctx.clip_on_cpu && !p.ctx.batched_cfg && p.gen.vae_tiling_params.enabled, - "lite sets the guard, the text encoder on the CPU, unbatched CFG and VAE tiling"); + CHECK(p.ok && p.ctx.memory_guard == 85 && !p.ctx.batched_cfg && p.gen.vae_tiling_params.enabled, + "lite sets the guard, unbatched CFG and VAE tiling"); + CHECK(!p.ctx.clip_on_cpu && !p.ctx.vae_on_cpu && !p.ctx.control_net_cpu && p.ctx.backend.empty(), + "lite keeps every module on the GPU: the text encoder stays where auto-fit puts it"); + CHECK(p.ctx.multi_gpu == "on", "lite spreads the modules over every GPU of the backend"); sd_profile::apply(Level::LITE, p.ctx, p.gen, true); - CHECK(p.ctx.memory_guard == 85 && p.ctx.params_backend.empty() && p.ctx.backend.empty(), + CHECK(p.ctx.memory_guard == 85 && p.ctx.params_backend.empty() && p.ctx.backend.empty() && p.ctx.multi_gpu == "on", "applying a level twice changes nothing more, and lite leaves the weights placement to auto-fit"); } + { + Parsed off({"--multi-gpu", "OFF"}); + sd_profile::apply(Level::LITE, off.ctx, off.gen, true); + CHECK(off.ctx.multi_gpu == "OFF", "lite does not undo --multi-gpu off at startup"); + sd_profile::apply(Level::LITE, off.ctx, off.gen, false); + CHECK(off.ctx.multi_gpu == "OFF", "nor does a recovery step"); + Parsed automatic({"--multi-gpu", "auto"}); + sd_profile::apply(Level::LITE, automatic.ctx, automatic.gen, true); + CHECK(automatic.ctx.multi_gpu == "auto", "an explicit --multi-gpu auto is kept at startup"); + sd_profile::apply(Level::LITE, automatic.ctx, automatic.gen, false); + CHECK(automatic.ctx.multi_gpu == "on", "and a recovery step turns it on"); + Parsed balanced({}); + sd_profile::apply(Level::BALANCED, balanced.ctx, balanced.gen, true); + CHECK(balanced.ctx.multi_gpu.empty(), "balanced leaves multi-gpu alone"); + } + { + bool stays_on_gpu = true; + for (Level step : {Level::MAX, Level::BALANCED, Level::LITE, Level::LITE_DISK}) { + for (bool respect_explicit : {true, false}) { + Parsed p({}); + sd_profile::apply(step, p.ctx, p.gen, respect_explicit); + stays_on_gpu = stays_on_gpu && !p.ctx.clip_on_cpu && !p.ctx.vae_on_cpu && !p.ctx.control_net_cpu && p.ctx.backend.empty(); + } + } + CHECK(stays_on_gpu, "no step down to lite-disk moves a module to the CPU"); + } { Parsed p({}); sd_profile::apply(Level::BALANCED, p.ctx, p.gen, true); @@ -210,6 +241,24 @@ int main() { Parsed p({"--backend", "te=cuda0"}); sd_profile::apply(Level::LITE, p.ctx, p.gen, true); CHECK(!p.ctx.clip_on_cpu, "an explicit text encoder placement is not overridden by lite"); + sd_profile::apply(Level::LITE_HYBRID, p.ctx, p.gen, false); + CHECK(!p.ctx.clip_on_cpu, "nor by lite-hybrid, even in a recovery"); + } + { + Parsed p({}); + sd_profile::apply(Level::LITE_HYBRID, p.ctx, p.gen, false); + CHECK(p.ctx.clip_on_cpu && !p.ctx.vae_on_cpu && !p.ctx.control_net_cpu && p.ctx.backend.empty(), + "lite-hybrid moves only the text encoder to the CPU"); + CHECK(p.ctx.params_backend == "disk" && !p.ctx.eager_load && p.ctx.memory_guard == 85 && !p.ctx.batched_cfg && + p.gen.vae_tiling_params.enabled && p.ctx.multi_gpu == "on", + "and keeps everything the steps before it set"); + Parsed manual({"--backend", "cuda0"}); + sd_profile::apply(Level::LITE_HYBRID, manual.ctx, manual.gen, true); + CHECK(!manual.ctx.clip_on_cpu && manual.ctx.backend == "cuda0", "an explicit --backend is kept at startup"); + Parsed clip({"--clip-on-cpu"}); + sd_profile::apply(Level::LITE, clip.ctx, clip.gen, true); + sd_profile::apply(Level::LITE_DISK, clip.ctx, clip.gen, false); + CHECK(clip.ctx.clip_on_cpu, "a --clip-on-cpu given on the command line is never undone before lite-cpu"); } { Parsed p({"--params-backend", "cpu", "--offload-to-cpu", "--eager-load"}); @@ -219,6 +268,7 @@ int main() { sd_profile::apply(Level::LITE_DISK, p.ctx, p.gen, false); CHECK(p.ctx.params_backend == "disk" && !p.ctx.offload_params_to_cpu, "lite-disk streams the weights from disk in a recovery"); CHECK(!p.ctx.eager_load, "and does not read all of them into memory first"); + CHECK(!p.ctx.clip_on_cpu && p.ctx.backend.empty(), "while the compute stays on the GPU, the text encoder included"); } { Parsed p({"--backend", "cuda0"}); @@ -237,8 +287,9 @@ int main() { CHECK(sd_profile::apply_from_options(p.ctx, p.gen, applied) && applied == Level::MAX && p.ctx.memory_guard == 0, "no --profile leaves the options alone"); p.ctx.profile = "lite"; - CHECK(sd_profile::apply_from_options(p.ctx, p.gen, applied) && applied == Level::LITE && p.ctx.memory_guard == 85, - "--profile lite is applied"); + CHECK(sd_profile::apply_from_options(p.ctx, p.gen, applied) && applied == Level::LITE && p.ctx.memory_guard == 85 && + !p.ctx.clip_on_cpu, + "--profile lite is applied, without moving anything to the CPU"); } printf("\n%s (%d failures)\n", failures ? "TEST FAILED" : "ALL TESTS PASSED", failures); diff --git a/test/server_recovery_test.cpp b/test/server_recovery_test.cpp index 3bb5ec89..4b58cf19 100644 --- a/test/server_recovery_test.cpp +++ b/test/server_recovery_test.cpp @@ -67,13 +67,19 @@ struct Load { std::string params_backend; bool eager_load; std::string model_path; + std::string multi_gpu; + bool no_fallback; + + bool text_encoder_on_cpu() const { + return backend.find("te=cpu") != std::string::npos; + } Level level() const { if (backend == "cpu") { return Level::LITE_CPU; } if (params_backend == "disk") { - return Level::LITE_DISK; + return text_encoder_on_cpu() ? Level::LITE_HYBRID : Level::LITE_DISK; } if (memory_guard == 85) { return Level::LITE; @@ -93,6 +99,8 @@ struct Env { GenerationFailure next_failure; // what the library reports for the attempt that failed Clock::time_point now = Clock::now(); bool accelerator = true; + // The devices the library lists besides the cpu; empty means that the engine's own choice is all there is. + std::vector devices; // The contexts the keeper asked the library to stop, in order. on_cancel runs on the thread that called cancel(). std::mutex cancel_mutex; @@ -107,7 +115,9 @@ struct Env { params.backend != nullptr ? params.backend : "", params.params_backend != nullptr ? params.params_backend : "", params.eager_load, - params.model_path != nullptr ? params.model_path : ""}; + params.model_path != nullptr ? params.model_path : "", + params.multi_gpu != nullptr ? params.multi_gpu : "", + params.disable_backend_fallback}; loads.push_back(load); if (on_create) { on_create(load); @@ -122,6 +132,7 @@ struct Env { }; hooks.read_failure = [this] { return next_failure; }; hooks.has_accelerator = [this] { return accelerator; }; + hooks.list_devices = [this] { return devices; }; hooks.now = [this] { return now; }; hooks.cancel_context = [this](sd_ctx_t* ctx) { // Touching the memory of a context the keeper no longer owns is what the address sanitizer reports. @@ -196,13 +207,14 @@ static void test_ladder() { Env env; { ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); - CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-cpu", "ladder with an accelerator"); + CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-hybrid > lite-cpu", "ladder with an accelerator"); CHECK(keeper.can_step_down(), "a full ladder can step down"); } env.accelerator = false; { ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); - CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk", "no cpu profile without an accelerator"); + CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk", + "without an accelerator the cpu has nothing to take over: no hybrid and no cpu profile"); } // The configuration of a host that already asks for most of it: steps that change nothing are left out. @@ -215,9 +227,22 @@ static void test_ladder() { ContextKeeper keeper(explicit_set, Level::MAX, settings(), env.hooks()); CHECK(keeper.describe_ladder() == "max > lite > lite-cpu", "profiles that would load the same configuration are skipped"); } + { + // Weights already streamed from disk, text encoder still on the GPU: the hybrid profile is the step this host lacks. + SDContextParams disk_only = base_params(); + disk_only.memory_guard = 90; + disk_only.params_backend = "disk"; + ContextKeeper keeper(disk_only, Level::MAX, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "max > lite > lite-hybrid > lite-cpu", + "lite-hybrid is kept when it is the only change of placement left"); + } { ContextKeeper keeper(base_params(), Level::LITE, settings(), env.hooks()); - CHECK(keeper.describe_ladder() == "lite > lite-disk > lite-cpu", "the ladder starts at the profile the server was started with"); + CHECK(keeper.describe_ladder() == "lite > lite-disk > lite-hybrid > lite-cpu", "the ladder starts at the profile the server was started with"); + } + { + ContextKeeper keeper(base_params(), Level::LITE_HYBRID, settings(), env.hooks()); + CHECK(keeper.describe_ladder() == "lite-hybrid > lite-cpu" && keeper.can_step_down(), "the cpu profile comes after the hybrid one"); } { // Reading every weight into memory at load time is what streaming them from disk avoids. @@ -278,6 +303,24 @@ static void test_start() { "a server started with --eager-load reaches the disk profile without the eager read"); CHECK(env.loads[0].eager_load && env.loads[2].eager_load, "the lighter profiles above it keep the option"); } + { + // The cpu takes work only when no level that keeps the compute on the GPUs is left. + Env env; + env.load_result = [](const Load& load) { return load.level() < Level::LITE_HYBRID ? oom() : ok_result; }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && env.loads.size() == 5 && env.loads[4].level() == Level::LITE_HYBRID, + "a model that does not fit is tried at every level that stays on the GPUs before the cpu is involved"); + bool cpu_early = false; + for (size_t i = 0; i < 4; ++i) { + cpu_early = cpu_early || !env.loads[i].backend.empty(); + } + CHECK(!cpu_early, "no level before lite-hybrid places a module on the cpu"); + CHECK(env.loads[4].backend == "te=cpu", "lite-hybrid gives the cpu the text encoder and nothing else"); + CHECK(env.loads[2].multi_gpu == "on" && env.loads[3].multi_gpu == "on" && env.loads[4].multi_gpu == "on", + "from lite on every GPU of the backend may take part"); + CHECK(env.loads[0].multi_gpu.empty() && env.loads[1].multi_gpu.empty(), "max and balanced leave the choice of GPUs to the engine"); + } { Env env; env.load_result = [](const Load&) { return model_file_failure(); }; @@ -298,8 +341,8 @@ static void test_start() { env.load_result = [](const Load& load) { return load.level() == Level::MAX ? backend_failure() : ok_result; }; ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); GenerationFailure failure; - CHECK(keeper.start(failure) && env.loads.size() == 2 && env.loads[1].level() == Level::LITE_CPU, - "a backend failure at start goes straight to the cpu profile"); + CHECK(keeper.start(failure) && env.loads.size() == 3 && env.loads[1].level() == Level::MAX && env.loads[2].level() == Level::LITE_CPU, + "a backend failure at start tries the same profile once more and, with no other device to use, goes to the cpu profile"); } { Env env; @@ -366,6 +409,11 @@ static void test_step_down() { CHECK(failure.code == SD_ERROR_OUT_OF_MEMORY && !failure.unavailable && failure.message == "unet ran out of memory", "with the out of memory reason, not as unavailable"); CHECK(seen.levels.size() == 4, "every profile was tried"); + bool moved_to_cpu = false; + for (const Load& load : env.loads) { + moved_to_cpu = moved_to_cpu || load.text_encoder_on_cpu() || load.backend == "cpu"; + } + CHECK(!moved_to_cpu, "without an accelerator no load moves a module to the cpu: it is the only device"); const json health = keeper.health_json(); CHECK(health["status"] == "degraded" && health["profile"] == "lite-disk", "the server keeps the lightest context"); CHECK(counter(health, "failed") == 1, "one failed request"); @@ -385,6 +433,25 @@ static void test_step_down() { CHECK(health["last_error"].is_null(), "a mistake of the client is not an error of the server"); CHECK(counter(health, "failed") == 1, "but it is a failed request"); } + { + // A request that keeps running out of memory is served by the GPUs for as long as a level exists that lets them. + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + const bool ok = run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE_HYBRID ? oom() : ok_result; }, failure); + CHECK(ok && seen.levels == std::vector({Level::MAX, Level::BALANCED, Level::LITE, Level::LITE_DISK, Level::LITE_HYBRID}), + "the request is run at each level in turn, the one that uses the cpu last"); + CHECK(seen.tiled == std::vector({false, false, true, true, true}), "tiling is forced from the lite profile on"); + bool cpu_early = false; + for (size_t i = 0; i + 1 < env.loads.size(); ++i) { + cpu_early = cpu_early || !env.loads[i].backend.empty(); + } + CHECK(!cpu_early, "no load before the last one places a module on the cpu"); + const json health = keeper.health_json(); + CHECK(health["status"] == "degraded" && health["profile"] == "lite-hybrid", "the server stays on the profile that worked"); + } { Env env; ContextKeeper keeper(base_params(), Level::MAX, settings(false), env.hooks()); @@ -405,8 +472,8 @@ static void test_step_down() { keeper.start(failure); Seen seen; const bool ok = run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level == Level::MAX ? backend_failure() : ok_result; }, failure); - CHECK(ok && seen.levels == std::vector({Level::MAX, Level::LITE_CPU}), - "a backend failure goes straight to the cpu profile"); + CHECK(ok && seen.levels == std::vector({Level::MAX, Level::MAX, Level::LITE_CPU}), + "a backend failure is tried once more on the same profile and, with no other device to use, then goes to the cpu profile"); CHECK(env.loads.back().backend == "cpu", "which loads the model on the cpu"); CHECK(keeper.backend_choice().backend == "cpu", "and the upscaler follows"); } @@ -773,7 +840,7 @@ static void test_load_unload() { ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); GenerationFailure failure; keeper.start(failure); - CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-cpu", "the ladder of the first model"); + CHECK(keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-hybrid > lite-cpu", "the ladder of the first model"); SDContextParams explicit_set = base_params(); explicit_set.memory_guard = 90; explicit_set.clip_on_cpu = true; @@ -880,7 +947,8 @@ static void test_load_unload() { reader.join(); } CHECK(readings.load() > 0, "the health, the ladder and the status were read while the model changed"); - CHECK(keeper.load(other, failure) && keeper.has_model() && keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-cpu", + CHECK(keeper.load(other, failure) && keeper.has_model() && + keeper.describe_ladder() == "max > balanced > lite > lite-disk > lite-hybrid > lite-cpu", "and the keeper still works after 150 changes"); } } @@ -1218,12 +1286,358 @@ static void test_cancel_threads() { CHECK(cancelled >= kThreads * kJobs / 5 && health["busy"] == false, "the jobs cancelled beforehand were stopped, and the keeper is idle at the end"); } +static sd_device_info_t device_info(const char* name, sd_device_type_t type, uint64_t free_gib) { + sd_device_info_t info{}; + snprintf(info.name, sizeof(info.name), "%s", name); + snprintf(info.description, sizeof(info.description), "%s", name); + info.type = type; + info.free_memory_bytes = free_gib << 30; + info.total_memory_bytes = free_gib << 30; + return info; +} + +// A card that the library lists once for each backend that supports it, and the integrated GPU of the processor. +static std::vector laptop_devices() { + return {device_info("CUDA0", SD_DEVICE_TYPE_GPU, 6), + device_info("Vulkan0", SD_DEVICE_TYPE_GPU, 6), + device_info("Vulkan1", SD_DEVICE_TYPE_IGPU, 8)}; +} + +using Names = std::vector; + +// The backend each load asked for, in order; "" is the engine's own choice of device. +static Names backends_of(const Env& env) { + Names names; + for (const Load& load : env.loads) { + names.push_back(load.backend); + } + return names; +} + +// A scripted library where nothing works but the cpu. +static GenerationFailure only_the_cpu_works(const Load& load) { + return load.backend == "cpu" ? ok_result : backend_failure(); +} + +// A request that only succeeds on the device named. +static Script runs_only_on(const std::string& device) { + return [device](const ContextKeeper::ContextView& view) { + return view.params != nullptr && view.params->backend == device ? ok_result : backend_failure(); + }; +} + +// A device that fails is not the end of the GPUs: the same configuration is tried once more, then every other device, +// and the cpu only when none of them works. The server goes back to the preferred device when it works again. +static void test_devices() { + { + Env env; + env.devices = laptop_devices(); + env.load_result = only_the_cpu_works; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure), "the model loads on the cpu when no device works"); + CHECK(backends_of(env) == Names({"", "", "CUDA0", "Vulkan0", "Vulkan1", "cpu"}), + "the same configuration again, then every other device best first, and the cpu last"); + const json health = keeper.health_json(); + CHECK(health["profile"] == "lite-cpu" && health["device"] == "cpu" && health["cpu_modules"] == json::array({"all"}), + "the health says that the cpu is doing all the work"); + CHECK(health["fallback_devices"] == json::array({"CUDA0", "Vulkan0", "Vulkan1"}), "and which devices the server can use"); + } + { + Env env; + env.devices = laptop_devices(); + env.load_result = [](const Load& load) { return load.backend == "Vulkan0" ? ok_result : backend_failure(); }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"", "", "CUDA0", "Vulkan0"}), + "a device that cannot start is replaced by the next GPU, not by the cpu"); + const json health = keeper.health_json(); + CHECK(env.loads.back().level() == Level::MAX, "on the profile the server was already on"); + CHECK(health["profile"] == "max" && health["status"] == "degraded" && health["device"] == "Vulkan0" && + health["cpu_modules"] == json::array(), + "the health says that it runs on another device, with nothing on the cpu"); + CHECK(health["next_promotion_seconds"] == 10, "the way back to the preferred device is scheduled"); + } + { + Env env; + env.devices = laptop_devices(); + int calls = 0; + env.load_result = [&](const Load&) { return ++calls == 1 ? backend_failure() : ok_result; }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"", ""}), + "a failure that does not repeat is cured by loading the same configuration again"); + const json health = keeper.health_json(); + CHECK(health["status"] == "ok" && health["device"] == "auto" && health["next_promotion_seconds"].is_null(), + "and the server is back to normal at once"); + } + { + Env env; + env.devices = laptop_devices(); + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(run_with(keeper, env, seen, runs_only_on("Vulkan0"), failure), "a request is served by another GPU when the first one fails"); + CHECK(seen.levels == std::vector({Level::MAX, Level::MAX, Level::MAX, Level::MAX}), "on the same profile every time"); + CHECK(backends_of(env) == Names({"", "", "CUDA0", "Vulkan0"}), "the same configuration again, then the next device, then the one after"); + CHECK(keeper.backend_choice().backend == "Vulkan0", "the upscaler follows to the device in use"); + const json health = keeper.health_json(); + CHECK(counter(health, "recovered") == 1 && counter(health, "retries") == 1 && counter(health, "device_switches") == 2 && + counter(health, "step_downs") == 0, + "counted as one retry and two device changes, not as a lighter profile"); + CHECK(health["status"] == "degraded" && health["profile"] == "max" && health["device"] == "Vulkan0" && + health["next_promotion_seconds"] == 10, + "the server stays on the device that worked and schedules the way back"); + CHECK(health["last_error"]["code"] == "backend", "the failure is the last error"); + } + { + Env env; + env.devices = laptop_devices(); + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + int attempts = 0; + CHECK(run_with(keeper, env, seen, [&](const ContextKeeper::ContextView&) { return ++attempts == 1 ? backend_failure() : ok_result; }, failure), "a request whose failure does not repeat is served"); + CHECK(seen.levels == std::vector({Level::MAX, Level::MAX}) && backends_of(env) == Names({"", ""}), + "by the same device, after loading the model again"); + const json health = keeper.health_json(); + CHECK(health["status"] == "ok" && health["device"] == "auto" && counter(health, "retries") == 1 && counter(health, "device_switches") == 0, + "without leaving it"); + } + { + Env env; + env.devices = laptop_devices(); + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(!run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return backend_failure(); }, failure), "a request that no device and not even the cpu can serve fails"); + CHECK(failure.code == SD_ERROR_BACKEND && !failure.unavailable && seen.levels.size() == 6 && backends_of(env).back() == "cpu", + "after trying them all, with the reason of the failure"); + const json health = keeper.health_json(); + CHECK(health["profile"] == "lite-cpu" && counter(health, "failed") == 1, "the server stays up on the cpu"); + } + { + // What the host wrote itself is not rewritten: the same configuration again, then the cpu. + Env env; + env.devices = laptop_devices(); + env.load_result = only_the_cpu_works; + SDContextParams pinned = base_params(); + pinned.backend = "diffusion=cuda0,vae=cpu"; + ContextKeeper keeper(pinned, Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"diffusion=cuda0,vae=cpu", "diffusion=cuda0,vae=cpu", "cpu"}), + "a placement of modules written by the host is kept"); + CHECK(keeper.health_json()["fallback_devices"] == json::array(), "and no other device is offered"); + } + { + // A device the host named is the one the engine tries first: the others come after it. + Env env; + env.devices = laptop_devices(); + env.load_result = only_the_cpu_works; + SDContextParams named = base_params(); + named.backend = "cuda0"; + ContextKeeper keeper(named, Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"cuda0", "cuda0", "Vulkan0", "Vulkan1", "cpu"}), + "the device the host named is not tried again as an alternative"); + } + { + // A machine on the network is not something to send the model to because a local device failed. + Env env; + env.devices = {device_info("CUDA0", SD_DEVICE_TYPE_GPU, 6), device_info("RPC0", SD_DEVICE_TYPE_GPU, 24)}; + env.load_result = only_the_cpu_works; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"", "", "CUDA0", "cpu"}), "devices of an rpc server are not used on their own"); + } + { + // Cards first (the one the vendor backend lists, then the one with the most memory), then accelerators, then the integrated GPU. + Env env; + env.devices = {device_info("Vulkan0", SD_DEVICE_TYPE_GPU, 6), + device_info("Vulkan2", SD_DEVICE_TYPE_IGPU, 8), + device_info("CUDA0", SD_DEVICE_TYPE_GPU, 6), + device_info("CUDA1", SD_DEVICE_TYPE_GPU, 12), + device_info("NPU0", SD_DEVICE_TYPE_ACCEL, 4), + device_info("CPU", SD_DEVICE_TYPE_CPU, 16)}; + env.load_result = only_the_cpu_works; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"", "", "CUDA1", "CUDA0", "Vulkan0", "NPU0", "Vulkan2", "cpu"}), + "the devices are tried best first, the cpu device is not one of them"); + } + { + // Running out of memory on the device that took over goes down the profiles on that device. + Env env; + env.devices = laptop_devices(); + env.load_result = [](const Load& load) -> GenerationFailure { + if (load.backend != "Vulkan0") { + return backend_failure(); + } + return load.level() < Level::LITE ? oom() : ok_result; + }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + CHECK(keeper.start(failure) && backends_of(env) == Names({"", "", "CUDA0", "Vulkan0", "Vulkan0", "Vulkan0"}) && + env.loads[3].level() == Level::MAX && env.loads[4].level() == Level::BALANCED && env.loads[5].level() == Level::LITE, + "the lighter profiles are tried on the device that is working"); + const json health = keeper.health_json(); + CHECK(health["profile"] == "lite" && health["device"] == "Vulkan0", "and the server stays there"); + } + { + // While a GPU is left to try, the engine must not turn a device that fails to start into a quiet cpu fallback. + Env env; + env.devices = laptop_devices(); + env.load_result = only_the_cpu_works; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + bool guarded = true; + for (size_t i = 0; i + 1 < env.loads.size(); ++i) { + guarded = guarded && env.loads[i].no_fallback; + } + CHECK(guarded && !env.loads.back().no_fallback, "every load that wants a GPU fails when the GPU does not start; the cpu profile asks for the cpu itself"); + } + { + Env env; + ContextKeeper keeper(base_params(), Level::MAX, settings(false), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + CHECK(!env.loads[0].no_fallback, "with degradation disabled the engine keeps its own fallback"); + } + { + Env env; + env.accelerator = false; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + CHECK(!env.loads[0].no_fallback, "and so does a machine without an accelerator, where the cpu is the only device"); + } + { + Env env; + env.devices = laptop_devices(); + ContextKeeper keeper(base_params(), Level::MAX, settings(false), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + CHECK(!run_with(keeper, env, seen, [](const ContextKeeper::ContextView&) { return backend_failure(); }, failure), "with degradation disabled a backend failure fails the request"); + CHECK(failure.code == SD_ERROR_BACKEND && seen.levels.size() == 1 && env.loads.size() == 1 && + keeper.health_json()["fallback_devices"] == json::array(), + "after one attempt, without loading the model again or offering a device"); + } + { + // The preferred device works again: the next climb returns to it. + Env env; + env.devices = laptop_devices(); + bool cuda_broken = true; + env.load_result = [&](const Load& load) { return cuda_broken && (load.backend.empty() || load.backend == "CUDA0") ? backend_failure() : ok_result; }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + CHECK(backends_of(env) == Names({"", "", "CUDA0", "Vulkan0"}), "the server started on the second GPU"); + const size_t loads = env.loads.size(); + cuda_broken = false; + env.advance(5); + Seen early; + run_with(keeper, env, early, succeed, failure); + CHECK(env.loads.size() == loads, "no climb before the wait is over"); + env.advance(6); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure) && climb.levels == std::vector({Level::MAX}) && env.loads.size() == loads + 1 && + env.loads.back().backend.empty(), + "the next request after the wait loads the engine's own choice again"); + const json health = keeper.health_json(); + CHECK(health["status"] == "ok" && health["device"] == "auto" && counter(health, "promotions") == 1 && health["next_promotion_seconds"].is_null(), + "and the server is back at the preferred device"); + CHECK(keeper.backend_choice().backend.empty(), "the upscaler follows"); + } + { + // The preferred device still fails: one attempt on it, then back to the one that worked, and a longer wait. + Env env; + env.devices = laptop_devices(); + env.load_result = [](const Load& load) { return load.backend.empty() || load.backend == "CUDA0" ? backend_failure() : ok_result; }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + const size_t loads = env.loads.size(); + env.advance(11); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure), "the request is served even if the climb fails"); + CHECK(env.loads.size() == loads + 2 && env.loads[loads].backend.empty() && env.loads[loads + 1].backend == "Vulkan0", + "one attempt on the preferred device, then the device that worked"); + const json health = keeper.health_json(); + CHECK(counter(health, "promotions") == 0 && counter(health, "failed_promotions") == 1 && health["next_promotion_seconds"] == 20 && + health["device"] == "Vulkan0", + "counted as a failed climb with a longer wait"); + } + { + // The cpu took over because every device failed: the climb goes back to the profile it left, on the best device that works. + Env env; + env.devices = laptop_devices(); + bool gpus_broken = true; + env.load_result = [&](const Load& load) { return gpus_broken && load.backend != "cpu" ? backend_failure() : ok_result; }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + CHECK(keeper.health_json()["profile"] == "lite-cpu", "the cpu took over"); + gpus_broken = false; + const size_t loads = env.loads.size(); + env.advance(11); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure) && climb.levels == std::vector({Level::MAX}) && + env.loads.size() == loads + 1 && env.loads.back().backend.empty(), + "the first climb returns to the profile the server had when the device failed, not one step up"); + CHECK(keeper.health_json()["status"] == "ok", "on the preferred device"); + } + { + // Only the second GPU works again. + Env env; + env.devices = laptop_devices(); + bool gpus_broken = true; + bool only_vulkan = false; + env.load_result = [&](const Load& load) { + if (load.backend == "cpu") { + return ok_result; + } + return gpus_broken || (only_vulkan && load.backend != "Vulkan0") ? backend_failure() : ok_result; + }; + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + gpus_broken = false; + only_vulkan = true; + env.advance(11); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure) && climb.levels == std::vector({Level::MAX}), "the climb is served"); + const json health = keeper.health_json(); + CHECK(health["status"] == "degraded" && health["profile"] == "max" && health["device"] == "Vulkan0" && counter(health, "promotions") == 1, + "by the GPU that works, not by the cpu"); + } + { + // The cpu took over because the memory ran out on every level: the climb goes up one step at a time. + Env env; + env.devices = laptop_devices(); + ContextKeeper keeper(base_params(), Level::MAX, settings(), env.hooks()); + GenerationFailure failure; + keeper.start(failure); + Seen seen; + run_with(keeper, env, seen, [](const ContextKeeper::ContextView& view) { return view.level < Level::LITE_CPU ? oom() : ok_result; }, failure); + env.advance(11); + Seen climb; + CHECK(run_with(keeper, env, climb, succeed, failure) && climb.levels == std::vector({Level::LITE_HYBRID}), + "after running out of memory everywhere the climb is one profile up"); + } +} + int main() { sd_set_log_callback([](enum sd_log_level_t, const char*, void*) {}, nullptr); test_ladder(); test_start(); test_step_down(); + test_devices(); test_promotion(); test_unavailable(); test_reporting();