mirror of
https://github.com/leejet/stable-diffusion.cpp.git
synced 2026-11-29 03:26:12 +00:00
Brings in the 73 upstream commits since b13a482 (2026-10-20 to 2026-11-05):
cancellation of running server jobs (#2190), recipe based model management
and idempotent model loading (#2176, #2188, #2217, #2221), ADetailer in the
server (#2164), generation metadata returned with the core results (#2206,
which changes generate_image and generate_video), integrated GPUs in the
automatic memory planning (#2228), discrete GPUs preferred in auto-fit
(#2259), Vulkan capacity checks retried after reclaiming memory (#2256),
the layer split fix across CUDA devices (#2262), RPC devices in
--list-devices (#2182), new models and many speed-ups (FLUX.3, Fibo 2.0,
MiniMax-H3, P-H3-Image, MOSS, Z-Image control-net, INT8 CUDA fusions),
Node 24 and ccache in the workflows, a CUTLASS submodule for the CUDA build,
and the ggml sync to 135ce1e.
Conflicts resolved by hand in 25 files, keeping both sides:
- include/stable-diffusion.h, src/stable-diffusion.cpp,
src/core/ggml_runner.cpp, src/pipeline/diffusion_engine.cpp,
src/pipeline/image.cpp: upstream's result API stays (generate_image and
generate_video fill a result out-parameter, free_sd_image_generation_result
releases it); the fork's classified errors, exception barrier and busy
check wrap it, so a failed call still records its reason and clears the
result. memory_guard, disable_backend_fallback and multi_gpu follow
upstream's last sd_ctx_params_t field. A stop on request is logged as
information, not as an error.
- src/core/backend_fit.cpp: integrated GPUs are enumerated as upstream now
does; which device becomes the main one is still decided by the fork's
rules (discrete before integrated, a card seen by both CUDA and Vulkan
counts once), which cover the case of #2259 as well.
- src/core/ggml_extend_backend.cpp, CMakeLists.txt: the NVIDIA driver is
still loaded at run time (sd::cuda_driver; the toolkit provides headers
only), so upstream's cuda_compiled_arch asks the compute capability
through it and not through <cuda.h>; the CUTLASS include of upstream
stays.
- src/model_manager.cpp: the CPU memory guard and upstream's capacity
rechecks (#2183, #2256) both apply.
- examples/server (runtime, main, async_jobs, routes_*): the context keeper
is still the only owner of the context, and ServerRuntime has no context
or mutex of its own. Upstream's model catalog (--model-dir, the
/sdcpp/v1/models routes, recipes) asks the keeper to load and unload
(ContextKeeper::load, unload, has_model), so a model loaded from the
catalog gets the same recovery ladder as the one given with -m, built from
the options of the new model. ADetailer runs with the context and the
options of the profile in use. The server still starts without a model.
- Cancellation: every job has a CancelToken that the keeper registers only
while the job generates. POST /sdcpp/v1/jobs/{id}/cancel answers at once
when called without ?wait=, as upstream does (the job can still be
generating, with cancel_requested true); with ?wait=N it waits for the end
of the job and answers 200, or 202 if it is still ending, which is what
the fork's guardian expects. cancel_requested is always in the job JSON.
- examples/common/common.{h,cpp}: upstream's --list-devices with RPC devices
and --taesd-preview-only next to the fork's --profile, --memory-guard,
--multi-gpu and --disable-backend-fallback.
- .github/workflows/build.yml: upstream's Node 24, ccache and CUDA header
triggers next to the fork's CPU Docker variant, lowercase image names,
combined CUDA and Vulkan Windows zip and Italian release notes.
examples/cli and examples/server CMakeLists: profile.cpp and recovery.cpp
are added to upstream's source lists.
- docs/backend.md, docs/build.md, examples/server/api.md: the sections of
both sides are kept. The paragraph on how a layer split assigns blocks is
the fork's, which is what layer_split_partition.cpp does (the first device
takes blocks until its free memory is used up), not upstream's
"proportional" wording.
The ggml submodule moves from dc99877 to 135ce1e, the frontend submodule to
fa93429 and the new thirdparty/cutlass submodule is added, all at upstream's
pins. A checkout needs git submodule update --init --recursive.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
414 lines
16 KiB
C++
414 lines
16 KiB
C++
#include "routes.h"
|
|
|
|
#include <algorithm>
|
|
#include <ctime>
|
|
#include <new>
|
|
#include <regex>
|
|
|
|
#include "common/common.h"
|
|
#include "common/media_io.h"
|
|
#include "common/resource_owners.hpp"
|
|
#include "recovery.h"
|
|
|
|
static std::string extract_and_remove_sd_cpp_extra_args(std::string& text) {
|
|
std::regex re("<sd_cpp_extra_args>(.*?)</sd_cpp_extra_args>");
|
|
std::smatch match;
|
|
|
|
std::string extracted;
|
|
if (std::regex_search(text, match, re)) {
|
|
extracted = match[1].str();
|
|
text = std::regex_replace(text, re, "");
|
|
}
|
|
return extracted;
|
|
}
|
|
|
|
static bool build_openai_generation_request(const httplib::Request& req,
|
|
ServerRuntime& runtime,
|
|
ImgGenJobRequest& request,
|
|
std::string& error_message) {
|
|
if (req.body.empty()) {
|
|
error_message = "empty body";
|
|
return false;
|
|
}
|
|
|
|
json j = json::parse(req.body);
|
|
std::string prompt = j.value("prompt", "");
|
|
int n = std::max(1, j.value("n", 1));
|
|
std::string size = j.value("size", "");
|
|
std::string output_format = j.value("output_format", "png");
|
|
int output_compression = j.value("output_compression", 100);
|
|
int width = runtime.default_gen_params->width > 0 ? runtime.default_gen_params->width : 512;
|
|
int height = runtime.default_gen_params->height > 0 ? runtime.default_gen_params->height : 512;
|
|
if (!size.empty()) {
|
|
auto pos = size.find('x');
|
|
if (pos != std::string::npos) {
|
|
try {
|
|
width = std::stoi(size.substr(0, pos));
|
|
height = std::stoi(size.substr(pos + 1));
|
|
} catch (...) {
|
|
}
|
|
}
|
|
}
|
|
|
|
if (prompt.empty()) {
|
|
error_message = "prompt required";
|
|
return false;
|
|
}
|
|
|
|
request.gen_params = *runtime.default_gen_params;
|
|
if (!assign_output_options(request, output_format, output_compression, true, error_message)) {
|
|
return false;
|
|
}
|
|
|
|
request.gen_params.prompt = prompt;
|
|
request.gen_params.width = width;
|
|
request.gen_params.height = height;
|
|
request.gen_params.batch_count = n;
|
|
|
|
std::string sd_cpp_extra_args_str = extract_and_remove_sd_cpp_extra_args(request.gen_params.prompt);
|
|
if (!sd_cpp_extra_args_str.empty() && !request.gen_params.from_json_str(sd_cpp_extra_args_str)) {
|
|
error_message = "invalid sd_cpp_extra_args";
|
|
return false;
|
|
}
|
|
|
|
// Intentionally disable prompt-embedded LoRA tag parsing for server APIs.
|
|
if (!request.gen_params.resolve_and_validate(IMG_GEN, "", runtime.ctx_params->hires_upscalers_dir, true)) {
|
|
error_message = "invalid params";
|
|
return false;
|
|
}
|
|
return validate_server_img_gen_request(runtime, request, error_message);
|
|
}
|
|
|
|
static bool build_openai_edit_request(const httplib::Request& req,
|
|
ServerRuntime& runtime,
|
|
ImgGenJobRequest& request,
|
|
std::string& error_message) {
|
|
if (!req.is_multipart_form_data()) {
|
|
error_message = "Content-Type must be multipart/form-data";
|
|
return false;
|
|
}
|
|
|
|
std::string prompt = req.form.get_field("prompt");
|
|
if (prompt.empty()) {
|
|
error_message = "prompt required";
|
|
return false;
|
|
}
|
|
|
|
size_t image_count = req.form.get_file_count("image[]");
|
|
bool has_legacy_image = req.form.has_file("image");
|
|
if (image_count == 0 && !has_legacy_image) {
|
|
error_message = "at least one image[] required";
|
|
return false;
|
|
}
|
|
|
|
std::vector<std::vector<uint8_t>> images_bytes;
|
|
for (size_t i = 0; i < image_count; ++i) {
|
|
auto file = req.form.get_file("image[]", i);
|
|
images_bytes.emplace_back(file.content.begin(), file.content.end());
|
|
}
|
|
if (image_count == 0 && has_legacy_image) {
|
|
auto file = req.form.get_file("image");
|
|
images_bytes.emplace_back(file.content.begin(), file.content.end());
|
|
}
|
|
|
|
std::vector<uint8_t> mask_bytes;
|
|
if (req.form.has_file("mask")) {
|
|
auto file = req.form.get_file("mask");
|
|
mask_bytes.assign(file.content.begin(), file.content.end());
|
|
}
|
|
|
|
int n = 1;
|
|
if (req.form.has_field("n")) {
|
|
try {
|
|
n = std::stoi(req.form.get_field("n"));
|
|
} catch (...) {
|
|
}
|
|
}
|
|
|
|
std::string size = req.form.get_field("size");
|
|
int width = -1;
|
|
int height = -1;
|
|
if (!size.empty()) {
|
|
auto pos = size.find('x');
|
|
if (pos != std::string::npos) {
|
|
try {
|
|
width = std::stoi(size.substr(0, pos));
|
|
height = std::stoi(size.substr(pos + 1));
|
|
} catch (...) {
|
|
}
|
|
}
|
|
}
|
|
|
|
std::string output_format = req.form.has_field("output_format")
|
|
? req.form.get_field("output_format")
|
|
: "png";
|
|
|
|
int output_compression = 100;
|
|
try {
|
|
output_compression = std::stoi(req.form.get_field("output_compression"));
|
|
} catch (...) {
|
|
}
|
|
|
|
request.gen_params = *runtime.default_gen_params;
|
|
if (!assign_output_options(request, output_format, output_compression, false, error_message)) {
|
|
return false;
|
|
}
|
|
|
|
request.gen_params.prompt = prompt;
|
|
request.gen_params.width = width;
|
|
request.gen_params.height = height;
|
|
request.gen_params.batch_count = n;
|
|
|
|
std::string sd_cpp_extra_args_str = extract_and_remove_sd_cpp_extra_args(request.gen_params.prompt);
|
|
for (auto& bytes : images_bytes) {
|
|
int img_w = 0;
|
|
int img_h = 0;
|
|
int resolved_channel = 0;
|
|
uint8_t* raw_pixels = load_image_from_memory(
|
|
reinterpret_cast<const char*>(bytes.data()),
|
|
static_cast<int>(bytes.size()),
|
|
img_w, img_h, resolved_channel,
|
|
0, 0,
|
|
0);
|
|
if (raw_pixels == nullptr) {
|
|
continue;
|
|
}
|
|
|
|
SDImageOwner image_owner({(uint32_t)img_w, (uint32_t)img_h, (uint32_t)resolved_channel, raw_pixels});
|
|
request.gen_params.set_width_and_height_if_unset(image_owner.get().width, image_owner.get().height);
|
|
|
|
request.gen_params.ref_images.push_back(std::move(image_owner));
|
|
}
|
|
|
|
if (!mask_bytes.empty()) {
|
|
int mask_w = 0;
|
|
int mask_h = 0;
|
|
int mask_channel = 0;
|
|
|
|
uint8_t* mask_raw = load_image_from_memory(
|
|
reinterpret_cast<const char*>(mask_bytes.data()),
|
|
static_cast<int>(mask_bytes.size()),
|
|
mask_w, mask_h, mask_channel,
|
|
0, 0, 1);
|
|
request.gen_params.mask_image.reset({(uint32_t)mask_w, (uint32_t)mask_h, 1, mask_raw});
|
|
const sd_image_t& mask_image = request.gen_params.mask_image.get();
|
|
request.gen_params.set_width_and_height_if_unset(mask_image.width, mask_image.height);
|
|
} else {
|
|
request.gen_params.mask_image.reset({
|
|
(uint32_t)request.gen_params.get_resolved_width(),
|
|
(uint32_t)request.gen_params.get_resolved_height(),
|
|
1,
|
|
nullptr,
|
|
});
|
|
}
|
|
|
|
if (!sd_cpp_extra_args_str.empty() && !request.gen_params.from_json_str(sd_cpp_extra_args_str)) {
|
|
error_message = "invalid sd_cpp_extra_args";
|
|
return false;
|
|
}
|
|
|
|
// Intentionally disable prompt-embedded LoRA tag parsing for server APIs.
|
|
if (!request.gen_params.resolve_and_validate(IMG_GEN, "", runtime.ctx_params->hires_upscalers_dir, true)) {
|
|
error_message = "invalid params";
|
|
return false;
|
|
}
|
|
|
|
return validate_server_img_gen_request(runtime, request, error_message);
|
|
}
|
|
|
|
static bool execute_sync_img_gen_request(ServerRuntime& runtime,
|
|
ImgGenJobRequest& request,
|
|
SDImageVec& results,
|
|
GenerationFailure& failure) {
|
|
const sd_img_gen_params_t img_gen_params = request.to_sd_img_gen_params_t();
|
|
|
|
bool adetailer_failed = false;
|
|
const bool generated = runtime.keeper->run(
|
|
[&](const ContextKeeper::ContextView& view) {
|
|
sd_img_gen_params_t params = img_gen_params;
|
|
if (view.force_vae_tiling) {
|
|
params.vae_tiling_params.enabled = true;
|
|
}
|
|
adetailer_failed = false;
|
|
sd_image_generation_result_t* produced = nullptr;
|
|
if (!generate_image(view.ctx, ¶ms, &produced)) {
|
|
return false;
|
|
}
|
|
results.adopt(produced, view.params->lora_model_dir);
|
|
if (!results.empty() && !apply_server_adetailer(runtime, view.ctx, *view.params, request, params, results)) {
|
|
adetailer_failed = true;
|
|
return false;
|
|
}
|
|
return true;
|
|
},
|
|
failure);
|
|
if (!generated) {
|
|
if (adetailer_failed) {
|
|
failure.message = failure.message.empty() ? "ADetailer failed" : "ADetailer failed: " + failure.message;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
if (results.empty()) {
|
|
failure = GenerationFailure();
|
|
failure.code = SD_ERROR_UNKNOWN;
|
|
failure.message = "generate_image returned no results";
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) {
|
|
ServerRuntime* runtime = &rt;
|
|
RuntimeRoutes routes(svr, rt);
|
|
|
|
routes.get("/v1/models", [runtime](const httplib::Request&, httplib::Response& res) {
|
|
json r;
|
|
r["data"] = json::array();
|
|
if (runtime->keeper->has_model()) {
|
|
r["data"].push_back({{"id", "sd-cpp-local"}, {"object", "model"}, {"owned_by", "local"}});
|
|
}
|
|
res.set_content(r.dump(), "application/json");
|
|
});
|
|
|
|
routes.post("/v1/images/generations", [runtime](const httplib::Request& req, httplib::Response& res) {
|
|
try {
|
|
if (!runtime_supports_generation_mode(*runtime, IMG_GEN)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", unsupported_generation_mode_error(*runtime, IMG_GEN)}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
ImgGenJobRequest request;
|
|
std::string error_message;
|
|
if (!build_openai_generation_request(req, *runtime, request, error_message)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", error_message}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
LOG_DEBUG("%s\n", request.gen_params.to_string().c_str());
|
|
|
|
SDImageVec results;
|
|
GenerationFailure failure;
|
|
if (!execute_sync_img_gen_request(*runtime, request, results, failure)) {
|
|
send_generation_failure(res, failure);
|
|
return;
|
|
}
|
|
|
|
json out;
|
|
out["created"] = static_cast<long long>(std::time(nullptr));
|
|
out["data"] = json::array();
|
|
out["output_format"] = request.output_format;
|
|
|
|
int result_count = results.count();
|
|
|
|
for (int i = 0; i < result_count; ++i) {
|
|
if (results[i].data == nullptr) {
|
|
continue;
|
|
}
|
|
std::string params = request.gen_params.embed_image_metadata
|
|
? results.generation_info(i)
|
|
: "";
|
|
auto image_bytes = encode_image_to_vector(request.output_format == "jpeg"
|
|
? EncodedImageFormat::JPEG
|
|
: request.output_format == "webp"
|
|
? EncodedImageFormat::WEBP
|
|
: EncodedImageFormat::PNG,
|
|
results[i].data,
|
|
results[i].width,
|
|
results[i].height,
|
|
results[i].channel,
|
|
params,
|
|
request.output_compression);
|
|
if (image_bytes.empty()) {
|
|
LOG_ERROR("write image to mem failed");
|
|
continue;
|
|
}
|
|
|
|
json item;
|
|
item["b64_json"] = base64_encode(image_bytes);
|
|
item["generation_info"] = json::parse(results.generation_info(i));
|
|
out["data"].push_back(item);
|
|
}
|
|
|
|
res.set_content(out.dump(), "application/json");
|
|
res.status = 200;
|
|
|
|
} catch (const std::bad_alloc&) {
|
|
send_generation_failure(res, out_of_memory_failure());
|
|
} catch (const std::exception& e) {
|
|
res.status = 500;
|
|
json err;
|
|
err["error"] = "server_error";
|
|
err["message"] = e.what();
|
|
res.set_content(safe_json_dump(err), "application/json");
|
|
}
|
|
});
|
|
|
|
routes.post("/v1/images/edits", [runtime](const httplib::Request& req, httplib::Response& res) {
|
|
try {
|
|
if (!runtime_supports_generation_mode(*runtime, IMG_GEN)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", unsupported_generation_mode_error(*runtime, IMG_GEN)}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
ImgGenJobRequest request;
|
|
std::string error_message;
|
|
if (!build_openai_edit_request(req, *runtime, request, error_message)) {
|
|
res.status = 400;
|
|
res.set_content(json({{"error", error_message}}).dump(), "application/json");
|
|
return;
|
|
}
|
|
|
|
LOG_DEBUG("%s\n", request.gen_params.to_string().c_str());
|
|
|
|
SDImageVec results;
|
|
GenerationFailure failure;
|
|
if (!execute_sync_img_gen_request(*runtime, request, results, failure)) {
|
|
send_generation_failure(res, failure);
|
|
return;
|
|
}
|
|
|
|
json out;
|
|
out["created"] = static_cast<long long>(std::time(nullptr));
|
|
out["data"] = json::array();
|
|
out["output_format"] = request.output_format;
|
|
|
|
int result_count = results.count();
|
|
|
|
for (int i = 0; i < result_count; ++i) {
|
|
if (results[i].data == nullptr) {
|
|
continue;
|
|
}
|
|
std::string params = request.gen_params.embed_image_metadata
|
|
? results.generation_info(i)
|
|
: "";
|
|
auto image_bytes = encode_image_to_vector(request.output_format == "jpeg" ? EncodedImageFormat::JPEG : EncodedImageFormat::PNG,
|
|
results[i].data,
|
|
results[i].width,
|
|
results[i].height,
|
|
results[i].channel,
|
|
params,
|
|
request.output_compression);
|
|
json item;
|
|
item["b64_json"] = base64_encode(image_bytes);
|
|
item["generation_info"] = json::parse(results.generation_info(i));
|
|
out["data"].push_back(item);
|
|
}
|
|
|
|
res.set_content(out.dump(), "application/json");
|
|
res.status = 200;
|
|
|
|
} catch (const std::bad_alloc&) {
|
|
send_generation_failure(res, out_of_memory_failure());
|
|
} catch (const std::exception& e) {
|
|
res.status = 500;
|
|
json err;
|
|
err["error"] = "server_error";
|
|
err["message"] = e.what();
|
|
res.set_content(safe_json_dump(err), "application/json");
|
|
}
|
|
});
|
|
}
|