From 801642fa990f474c255d4f5849da185ff3edd9d2 Mon Sep 17 00:00:00 2001 From: leejet Date: Mon, 23 Nov 2026 23:37:53 +0800 Subject: [PATCH 1/2] refactor(server): use one context with on-demand model loading --- docs/development/c_api.md | 9 +- docs/guides/c_api.md | 21 +- examples/server/README.md | 41 +-- examples/server/api.md | 171 +++-------- examples/server/async_jobs.cpp | 82 ++--- examples/server/async_jobs.h | 6 +- examples/server/frontend | 2 +- examples/server/main.cpp | 23 +- examples/server/model_catalog.cpp | 130 ++++---- examples/server/model_catalog.h | 33 +- examples/server/routes_dgl.cpp | 50 ++- examples/server/routes_models.cpp | 140 ++------- examples/server/routes_openai.cpp | 20 +- examples/server/routes_sdapi.cpp | 11 +- examples/server/routes_sdcpp.cpp | 427 ++++++-------------------- examples/server/runtime.cpp | 55 +++- examples/server/runtime.h | 5 +- include/stable-diffusion.h | 10 +- src/api/api.cpp | 31 +- src/api/generation.cpp | 36 ++- src/api/generation.h | 32 +- src/api/generation_hires.cpp | 2 +- src/api/generation_image.cpp | 10 +- src/api/generation_program.cpp | 38 +-- src/api/generation_prompt.cpp | 2 +- src/api/generation_video.cpp | 16 +- src/api/templates/README.md | 1 - src/api/templates/load_components.dgl | 33 -- src/api/upscaler.cpp | 12 +- src/dgl/bindings/predictor.cpp | 8 +- src/dgl/context.cpp | 3 + src/dgl/context.h | 5 + src/dgl/dgl.cpp | 6 +- src/dgl/models/diffusion_prediction.h | 16 +- src/dgl/models/lora.cpp | 3 +- src/dgl/models/lora.h | 3 +- src/dgl/models/model_runtime.cpp | 2 +- src/dgl/ops/tensor.cpp | 2 +- src/model/diffusion/moss_image.hpp | 2 +- 39 files changed, 541 insertions(+), 958 deletions(-) delete mode 100644 src/api/templates/load_components.dgl diff --git a/docs/development/c_api.md b/docs/development/c_api.md index b3f4da682b..bfa6fd1e52 100644 --- a/docs/development/c_api.md +++ b/docs/development/c_api.md @@ -74,12 +74,9 @@ Context creation snapshots options without loading weights. Family probing is lazy and tracks actual file dependencies. The complete request stays busy during probing, compilation, batch gaps and execution. File permissions are checked before probing and on every DGL resource access, including cache hits. -`sd_ctx_prepare()` runs a component-only template using the same loading -parameters as generation. Server startup and model selection call it after -installing file permissions, before publishing `ready`. Capability queries read -an atomic snapshot of the last detected type and do not acquire a generation -run or reset its cancellation state. Only an initial probe takes the context -lock. +Generation templates load their required components as part of execution. +Capability queries read the detected family under the context lock and probe it +on demand. They leave the generation cancellation state untouched. C++ validates inputs, resolves model defaults, prepares geometry and binds host tensors. Templates describe complete execution flows and optional stages; diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index 7e66c40dcf..c359b695da 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -62,13 +62,20 @@ cleanup: } ``` -`sd_ctx_create()` retains configuration and leaves component loading lazy. To -validate a model before accepting generation requests, install any file-access -callback and call `sd_ctx_prepare(ctx)`. It probes the model, builds and validates -the configured components, and retains them for later generation without -sampling. Weight residency still follows `eager_load` and the memory budgets. -Preparation failures return a non-OK status; callers can discard or retry the -context. Capability queries reuse the detected model type during generation. +`sd_ctx_create()` retains the model configuration. The first generation call +loads the components it needs and reports any loading errors through its return +status. Weight residency follows `eager_load` and the memory budgets. Capability +queries can probe the model family and reuse the detected type. + +Use `sd_ctx_set_model_options()` on an idle context to replace its model +configuration. It copies the options and resets model detection. Later +`sd_generate_image()` and `sd_generate_video()` calls use the new configuration. +The execution settings and component cache continue to serve generation and the +DGL context borrowed through `sd_ctx_get_dgl_ctx()`. The borrowed pointer stays +valid until `sd_ctx_free()`. Run scripts and generation calls one at a time. Set +file-access callbacks for generated programs and scripts through +`sd_ctx_set_file_access_callback()` and `sd_dgl_ctx_set_file_access_callback()` +respectively. Use `sd_generate_video()` with options from `sd_vid_gen_opt_create()` to generate video. Its result exposes frames through the same image accessors, optional audio through diff --git a/examples/server/README.md b/examples/server/README.md index f360694e7c..a657acfc7d 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -4,7 +4,7 @@ and HTTP APIs. Download or build the server before starting; see the [build guide](../../docs/build.md) and [frontend build instructions](#build-with-frontend). -- [Web UI](#web-ui): start the server, load a model, and generate. +- [Web UI](#web-ui): start the server, select a model, and generate. - [Model management](#model-management): model directories, recipes, and startup models. - [Server configuration](#server-configuration): launcher settings, network, logging, and help. - [API](#api): native and compatibility endpoints. @@ -61,7 +61,7 @@ for another build configuration or an extracted release archive. Open after the server starts, and keep the server running while using the browser. -### Load a model +### Select a model 1. Download the weights and required components listed in the matching [model guide](../../docs/models/README.md). Put them in the category folders @@ -76,8 +76,6 @@ while using the browser. to the chosen checkpoint and variant, as described in its model guide. 5. If a file is missing from a dropdown, check its category folder and click **Refresh files & recipes**. Selectors support searching by name or path. -6. Click **Load models** and wait for loading to finish. Selecting a recipe or - file alone does not reload the model. Recipe and component selectors support searching by name or relative file ID. Use the arrow keys and Enter to select, or Escape to cancel a search. With @@ -85,13 +83,10 @@ Use the arrow keys and Enter to select, or Escape to cancel a search. With declared generation defaults while preserving prompts, input images and fields not specified by the recipe. Disable it to keep your current parameters when switching recipes. This preference defaults to enabled and is saved locally. -Model loading and server-info refreshes do not reapply defaults or reset the form. Recipes declaring `video_frames` also switch the form to Video Generation; -other recipes switch to Image Generation. Generation is enabled after the -selected recipe is loaded. - -The model button shows elapsed loading time and keeps the final time after -success or failure, including after a page refresh. +other recipes switch to Image Generation. Select the required components to +enable **Generate**. The job loads any needed components and reports the +loading progress alongside sampling and output encoding. ### Generate an image or video @@ -316,12 +311,10 @@ For example, run this Z-Image Turbo configuration from the build directory: `--offload-to-cpu` keeps weights in RAM when possible to reduce VRAM pressure, `-v` enables verbose logging, and `--cfg-scale 1.0` sets the default CFG scale. -API clients can use the model loaded at startup without selecting a recipe. -The UI automatically selects **Command-line model (all features)** and uses the -startup generation defaults. This runtime-only recipe exposes all controls for the supported -image/video mode. Selecting another recipe previews a model switch; selecting -the command-line entry again restores its generation defaults. The entry is -removed when the command-line context is unloaded or replaced. +The model specified on the command line is the initial model for API clients. +Its components load when needed. The UI offers **Current server model** with +generation defaults and controls for the active configuration. Generating with +a catalog recipe makes that selection the current model. #### Identity inputs @@ -336,18 +329,16 @@ their own inputs under the server's file-access rules. For a checkpoint loaded from a complete repository directory, pass its model loading arguments when starting `sd-server`, as in the model's CLI example. Keep the index, tokenizer, and all shards together. The browser then uses -**Command-line model (all features)** for the model loaded at startup; selecting -an individual shard in a recipe dropdown does not load the whole repository. +**Current server model** for that repository. Select the repository +using the startup option so the model loader can resolve all its shards. ### Switching models -The server keeps one model context loaded. Loading or unloading is rejected -while generation requests or queued jobs are pending. A switch validates the -selection before unloading the old context, then loads the replacement. -If loading fails, the service stays online with no active model and reports -the error. Backend and memory options supplied at startup apply to subsequent -loads. Recipe defaults apply to new loads; explicitly supplied generation -request parameters take precedence. +Choose a recipe and component files for the next generation. A queued job that +specifies a recipe makes it the current model when it starts. Later requests +without a recipe use the current model. The server shares one execution context +with the DGL editor and reuses matching model components within its startup +memory budgets. A load failure is reported on the job that requested the model. See [the API reference](api.md#model-management) for recipe fields, supported slots, management endpoints, and compatibility behavior. diff --git a/examples/server/api.md b/examples/server/api.md index 25aa587533..d23a98687e 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -65,47 +65,46 @@ Current endpoints include: - `GET /sdcpp/v1/jobs/{id}` - `POST /sdcpp/v1/jobs/{id}/cancel` - `POST /sdcpp/v1/vid_gen` -- `POST /sdcpp/v1/upscale` ## Model management -Model management is additive: existing generation request bodies, successful -responses, job polling and cancellation remain unchanged. All three API families -use the current loaded context. Starting with the existing model arguments -preserves command-line preloading and its generation defaults; it does not -require a recipe. +All three API families share the server's execution context and its component +cache. The command-line model supplies the initial configuration. Native image +and video jobs can select a recipe and component files in the request. The worker +applies that selection to the shared context before generation. It remains the +current model for later requests that omit `model`, including A1111 and OpenAI +requests. Each native job reports loading and generation progress through the job API. Recipe defaults apply when a generation request omits the corresponding parameters. Image editing endpoints retain their existing input-image size inference when dimensions are omitted. -Without a loaded model, generation endpoints return HTTP 503 with -`{"error":"No model is loaded","code":"model_not_loaded"}`. -While loading/unloading, endpoints that access the context return HTTP 503 -with `code: "model_loading"`. These errors retain the existing string-valued -`error` field. Job polling/cancellation, catalog queries and model status remain -available during loading. Model lists are empty when no model is loaded; -`/v1/models` retains the `sd-cpp-local` ID when ready. +Requests that use the current model return HTTP 503 with +`{"error":"No current model is configured","code":"model_not_loaded"}` until +the server has a model configuration. `/v1/models` lists `sd-cpp-local` when a +model is configured. An accepted native job that omits `model` uses the current +model and its defaults when the job starts. | Method | Endpoint | Response / behavior | | --- | --- | --- | | GET | `/sdcpp/v1/recipes` | `{recipes: [...], errors: [...]}` | | GET | `/sdcpp/v1/model-files` | `{files: [{id, name, category, root, relative_path}], errors: [...]}` | | POST | `/sdcpp/v1/models/refresh` | Rescan recipes and files; return `{errors: [...]}` | -| GET | `/sdcpp/v1/models/status` | Current state, recipe, selection, error, loading time and optional revision | -| POST | `/sdcpp/v1/models/load` | Prepare and validate the submitted components before reporting `ready`; failures report `model_load_failed` and leave no active context. A load is a no-op returning the current status with `already_loaded: true` only when the state is ready and the fully resolved selection, the complete recipe object, and the resolved component paths all match the active model; a catalog refresh with modified recipe metadata or a retargeted model path therefore reloads even with an unchanged recipe ID and selection | -| POST | `/sdcpp/v1/models/unload` | Release the active context; return empty status | +| GET | `/sdcpp/v1/models/status` | Current model configuration (`configured` or `empty`), recipe, components and revision | -Load request: +Example `POST /sdcpp/v1/img_gen` request with a model selection. ```json { - "recipe": "flux1-dev", - "models": { - "diffusion_model": "diffusion_models/flux1-dev.gguf", - "clip_l": "text_encoders/clip_l.safetensors", - "t5xxl": "text_encoders/t5xxl.safetensors", - "vae": "vae/ae.safetensors" + "prompt": "a photograph of a cat", + "model": { + "recipe": "flux1-dev", + "models": { + "diffusion_model": "diffusion_models/flux1-dev.gguf", + "clip_l": "text_encoders/clip_l.safetensors", + "t5xxl": "text_encoders/t5xxl.safetensors", + "vae": "vae/ae.safetensors" + } } } ``` @@ -115,7 +114,7 @@ retains the existing relative IDs, such as `checkpoints/nested/model.gguf`. Additional roots use `@/` so identical paths in different roots remain selectable. Root qualifiers derive from the canonical root path; adding unrelated roots or refreshing the catalog does not change them. Moving -a root changes its qualifier. Do not construct IDs or use display names in load +a root changes its qualifier. Use the returned IDs to select files in generation requests. The display `name` omits the physical category directory (including aliases such @@ -137,31 +136,17 @@ relative path, or the full absolute file path when needed to distinguish duplica Continue sending `path` in structured LoRA requests. `--lora-model-dir` overrides automatic discovery across all model roots. Absolute paths, unknown files, wrong categories and -paths escaping the configured root are rejected. Optional slots can be omitted -or set to an empty string. Load/unload returns HTTP 409 (`model_busy`) while -requests or queued jobs are pending. Invalid configurations return HTTP 400 -(`invalid_model_config`) before unloading the current context. An initialization -failure returns HTTP 422 (`model_load_failed`) and leaves no active context. -The load HTTP request waits for completion; a separate client can poll status -while it runs. Refreshing the catalog never modifies an already loaded context. - -Status uses `state: empty | loading | ready | error`, `recipe` (ID or null), -`models` (slot-to-file-ID mapping), and `error` (string or null). A monotonically -increasing `revision` identifies runtime transitions within this server process. -Command-line preloading keeps `origin: command_line` and `recipe: null` for -compatibility, and adds `runtime_recipe`: a read-only `@command-line` recipe -with all feature declarations enabled. It is only available while that context -is loaded and cannot be submitted to `models/load`. The UI selects it by default -and uses command-line generation defaults, not defaults from a catalog recipe. -Capabilities also include this status as an additive `runtime` field. - -`load_elapsed_seconds` is the server-measured duration in seconds (a number or -null). It updates while a model is loading and freezes on success or failure. -Timing starts after selection validation and includes releasing the previous -model. It resets for each load and is null before any load and during/after -unloading. Command-line preloading reports its completed initialization time. -Poll `/sdcpp/v1/models/status` to display elapsed time, including while loading; -timer updates alone do not change `revision`. +paths escaping the configured root are rejected. An invalid selection returns +HTTP 400 with `code: "invalid_model_config"`. A component that fails to load +after submission reports its error in the job result. Catalog refreshes apply +to later submissions. + +The initial command-line selection has `origin: command_line`. Once a catalog +recipe is selected, status reports its ID and component files. The read-only +`runtime_recipe` with ID `@current` represents whichever model is configured at +the time of the query. Omit `model` from the request to use the current model. +Capabilities include the same model information in `runtime` and advertise +`generation_model_selection: true`. ### Recipe feature declarations @@ -206,9 +191,8 @@ Default-enabled features are `img2img`, `mask_image`, `lora`, `vae_tiling`, A `control_net` slot enables `controlnet`, `ip_adapter` enables `ip_adapter`, `high_noise_diffusion_model` enables `high_noise`, and `tae`/`taesd` enables `preview_tae`, unless explicitly disabled. -ControlNet controls are shown when previewing a supporting recipe, even before -a model file is selected. High-noise and TAE controls additionally require their -component to be selected. Runtime capabilities require the component to be loaded. +ControlNet, IP-Adapter, high-noise, TAE preview and audio reference controls +also depend on the selected component files. PuLID disables SLG while selected. Image-only and video-only inputs are filtered by the active generation mode. Eta depends on the selected sampler; SCM fields only apply to DBCache, @@ -219,16 +203,11 @@ each recipe. This is response-only metadata, like `source` and slot `categories` omit it when writing a user recipe file. The defaults are maintained by the server, not duplicated by the frontend. -`GET /sdcpp/v1/capabilities` adds `generation_features` for the loaded context, -derived from the active recipe and component availability without inferring -features from model-family names. When no model is loaded, every feature is -present and false. The UI can still preview a selected recipe using its -`effective_features` before loading. -Existing `features` / `features_by_mode` keys are retained and their model-specific -values reflect these declarations. A loaded recipe is snapshotted: refreshing -recipe files does not change the active context's capabilities until reloading. -Command-line preloading uses the runtime-only all-features recipe instead of model-family inference -and component paths; variant-specific recipe declarations are more precise. +`GET /sdcpp/v1/capabilities` reports `generation_features` for the current model, +along with its generation mode and defaults. With no configured model, those +features are false. +The UI uses the selected catalog recipe's `effective_features` and component +selection for requests that specify `model`. Known high-noise sampling settings and `moe_boundary` are ignored when no high-noise stage is loaded, and `vace_strength` is ignored by non-VACE models. Actual control-frame inputs still require VACE. @@ -281,12 +260,9 @@ supported directories; they cannot redefine or restrict its search directories. At least one required `model` or `diffusion_model` slot is necessary. An optional top-level `models` object maps slot IDs to file IDs, providing -recipe-local defaults for component selection. A load request may omit -`models` entirely and load with the recipe's defaults. Selections sent in the -request always override recipe defaults, slot by slot. An empty string -disables a slot's recipe default (omitting the slot selects it); the empty -key is then normalized out of the reported selection, so for slots without a -recipe default an empty selection loads identically to an omitted one. +recipe-local defaults for component selection. Omitting `model.models` uses +the recipe's defaults. Explicit selections override recipe defaults slot by +slot. An empty string disables the default for an optional slot. `size_multiple` is a positive integer from 1 to 4096 that declares the width and height increment used by the web UI. It defaults to `8` when omitted; the UI also @@ -396,7 +372,7 @@ Supported defaults: Other generation parameters continue to use startup defaults unless explicitly supplied by the generation request. Built-in Wan recipes provide video defaults; -use `/sdcpp/v1/vid_gen` after loading a video model. +use `/sdcpp/v1/vid_gen` with a video model. LoRAs are merged from `loras/` and `Lora/` in every model root unless `--lora-model-dir` is supplied. @@ -877,7 +853,6 @@ Top-level fields: | `schedulers` | `array` | Available schedulers | | `loras` | `array` | Available LoRA entries | | `upscalers` | `array` | Available highres upscalers, built-in and model-backed | -| `upscale` | `boolean` | Whether a compatible RGB ESRGAN model is available for `POST /sdcpp/v1/upscale` | | `preview_modes` | `array` | Available preview modes, e.g. `["none", "proj", "tae", "vae"]` | | `limits` | `object` | Shared queue and size limits | @@ -922,7 +897,6 @@ Shared nested fields: | --- | --- | --- | | `upscalers[].name` | `string` | Built-in name or model stem; use this value in `hires.upscaler` | | `upscalers[].model` | `boolean` | True for a model-backed upscaler, false for a built-in scaling filter | -| `upscalers[].image_upscale` | `boolean` | Whether this model can be selected by `POST /sdcpp/v1/upscale`; false for latent upscalers and built-in filters | Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, and `Latent (bicubic antialiased)`. Model-backed entries are scanned from the top level of `--hires-upscalers-dir`; subdirectories are not scanned. @@ -936,8 +910,6 @@ Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (neares | `limits.max_height` | `integer` | | `limits.max_batch_count` | `integer` | | `limits.max_queue_size` | `integer` | -| `limits.max_upscale_width` | `integer` | -| `limits.max_upscale_height` | `integer` | Shared default fields used by both `img_gen` and `vid_gen`: @@ -1093,52 +1065,6 @@ Typical status codes: - `404 Not Found` - `410 Gone` -#### `POST /sdcpp/v1/upscale` - -Runs one RGB ESRGAN upscaler over an image, with no generation involved. Latent upscaler models remain available for hires generation but cannot be used here. - -This is the HTTP equivalent of `sd-cli -M upscale`: no diffusion model, text -encoder or sampling is used, so it is fast enough to answer synchronously and -does not create a job. - -Request fields: - -| Field | Type | Notes | -| --- | --- | --- | -| `image` | `string` | Required. Base64 or data URL image | -| `upscaler` | `string` | A name from `upscalers` with `image_upscale: true`; the first compatible entry when omitted | -| `repeats` | `integer` | Run the upscaler this many times, 1 to 4 (default `1`) | -| `tile_size` | `integer` | Tile size, defaulting to the server's `--upscale-tile-size` | -| `output_format` | `string` | `png`, `jpeg`, or `webp` when built with WebP support (default `png`); unsupported formats return 400 | -| `output_compression` | `integer` | Range is clamped to `0..100` | - -Response fields: - -| Field | Type | Notes | -| --- | --- | --- | -| `images` | `array` | One image | -| `images[].index` | `integer` | | -| `images[].b64_json` | `string` | Base64-encoded image bytes | -| `upscaler` | `string` | The upscaler actually used | -| `scale` | `integer` | The model's scale factor | -| `repeats` | `integer` | How many times it was run | -| `width` | `integer` | Result width | -| `height` | `integer` | Result height | -| `output_format` | `string` | Final encoded image format | - -Typical status codes: - -- `200 OK` -- `400 Bad Request` (invalid request, unsupported output format, unreadable image, incompatible upscaler, or output dimensions exceeding the limit) -- `500 Internal Server Error` - -Notes: - -- Final output dimensions, including all repeats, must not exceed 8192 pixels on either axis (`limits.max_upscale_width` and `limits.max_upscale_height`). Requests exceeding this bound are rejected before upscaling. -- The upscaler models are three-channel; alpha is not preserved. -- The request holds the generation context lock, so an upscale and a - generation never run on the device at the same time. - #### `POST /sdcpp/v1/jobs/{id}/cancel` Cancels a queued job immediately, or requests interruption of a generating image or @@ -1458,7 +1384,8 @@ Example cancelled job: `POST /sdcpp/v1/img_gen` may return: - `202 Accepted` when the job is created -- `400 Bad Request` for an empty body, unsupported model mode, invalid JSON, or invalid generation parameters +- `400 Bad Request` for an invalid model selection, an unsupported current model mode, or invalid request parameters +- `503 Service Unavailable` when the request uses the current model and the server has none configured - `429 Too Many Requests` when the job queue is full - `500 Internal Server Error` for unexpected server exceptions during submission @@ -1891,7 +1818,8 @@ Example cancelled job: `POST /sdcpp/v1/vid_gen` may return: - `202 Accepted` when the job is created -- `400 Bad Request` for an empty body, unsupported model mode, invalid JSON, invalid generation parameters, or an unsupported output format +- `400 Bad Request` for an invalid model selection, an unsupported current model mode, invalid request parameters, or an unsupported output format +- `503 Service Unavailable` when the request uses the current model and the server has none configured - `429 Too Many Requests` when the job queue is full - `500 Internal Server Error` for unexpected server exceptions during submission @@ -1909,6 +1837,7 @@ the working directory's ./dgl directory unless --dgl-dir is set. | GET /sdcpp/v1/dgl/jobs/{id} | Returns the job status, error or result with tensor descriptions and inline encoded media | | GET /sdcpp/v1/dgl/jobs/{id}/outputs/{index}?frame=0 | Returns a PNG of an image output or a video frame. Output and frame indexes start at zero. | +Scripts share the component cache and execution settings used for generation. Model reads are restricted to the configured model directories. Script writes are restricted to output/ in the server's working directory. diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index ad1bef097a..5f15d6a6a8 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -231,6 +231,8 @@ bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job) { } manager.queue.erase(new_end, manager.queue.end()); + job.model.reset(); + job.request_body = nullptr; job.cancel_requested.store(true); job.status = AsyncJobStatus::Cancelled; job.completed_at = unix_timestamp_now_ms(); @@ -339,28 +341,46 @@ json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJo return result; } +static bool prepare_native_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message) { + if (job.cancel_requested.load()) + return false; + if (job.model) { + auto model = std::move(job.model); + return set_current_model(runtime, std::move(*model), error_message); + } + auto body = std::move(job.request_body); + if (job.model_revision == runtime.models->revision) + return true; + // An earlier queued job can change the model and its defaults before this job starts. + const SDMode mode = job.kind == AsyncJobKind::VidGen ? VID_GEN : IMG_GEN; + if (!runtime_supports_generation_mode(runtime, mode)) { + error_message = unsupported_generation_mode_error(mode); + return false; + } + try { + return parse_native_job_request(body, runtime, job, error_message); + } catch (const std::exception& error) { + error_message = error.what(); + return false; + } +} + bool execute_img_gen_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::vector& output_images, json& output_info, std::string& error_message) { - output_info = json::array(); - SDOptPtr params = job.img_gen.to_image_opt(); - + output_info = json::array(); SDImageVec results; { std::lock_guard lock(*runtime.sd_ctx_mutex); - if (job.cancel_requested.load()) { + if (!prepare_native_job(runtime, job, error_message)) { return false; } JobCancellationMonitor cancellation(runtime.sd_ctx, job); JobCallbacksGuard callbacks(runtime.sd_ctx, job); - PromptImageCallbackGuard prompt_images(runtime.sd_ctx, job.img_gen.gen_params); - sd_result_t* generated = nullptr; - generate_sd_image(runtime.sd_ctx, params, &generated); - results.adopt(generated); - if (job.cancel_requested.load()) { + if (!generate_server_images(runtime.sd_ctx, job.img_gen, results, error_message) || job.cancel_requested.load()) { return false; } } @@ -418,7 +438,6 @@ bool execute_vid_gen_job(ServerRuntime& runtime, int& output_fps, json& output_info, std::string& error_message) { - SDOptPtr params = job.vid_gen.to_video_opt(); std::string str_params; SDImageVec results; @@ -427,9 +446,10 @@ bool execute_vid_gen_job(ServerRuntime& runtime, { std::lock_guard lock(*runtime.sd_ctx_mutex); - if (job.cancel_requested.load()) { + if (!prepare_native_job(runtime, job, error_message)) { return false; } + auto params = job.vid_gen.to_video_opt(); JobCancellationMonitor cancellation(runtime.sd_ctx, job); JobCallbacksGuard callbacks(runtime.sd_ctx, job); PromptImageCallbackGuard prompt_images(runtime.sd_ctx, job.vid_gen.gen_params); @@ -442,13 +462,16 @@ bool execute_vid_gen_job(ServerRuntime& runtime, output_info = results.generation_info(0); if (job.vid_gen.gen_params.embed_image_metadata) str_params = results.generation_info(0); + } else { + error_message = sd_get_last_error(); } } num_results = results.count(); if (job.cancel_requested.load() || num_results <= 0) { free_sd_audio(generated_audio); - error_message = "generate_video returned no results"; + if (error_message.empty()) + error_message = "generate_video returned no results"; return false; } @@ -571,11 +594,6 @@ static json describe_dgl_result(const sd_dgl_result_t* result) { namespace { namespace fs = std::filesystem; - struct DglExecution { - ServerFileAccess file_access; - std::unique_ptr context{nullptr, sd_dgl_ctx_free}; - }; - bool allowed_dgl_path(const char* path, sd_dgl_file_access_t access, void* userdata) try { const auto& policy = *static_cast(userdata); std::error_code error; @@ -644,46 +662,35 @@ namespace { } } -void prepare_native_context(ServerModels& models, const SDSvrParams& params, const SDContextParams& config, bool startup) { - auto& policy = models.file_access; - policy = {get_model_roots(params), fs::weakly_canonical(fs::current_path()) / "output", {}, {}}; +void configure_server_file_access(ServerModels& models, const SDSvrParams& params, const SDContextParams& config) { + auto& policy = models.file_access; + policy = {get_model_roots(params), fs::weakly_canonical(fs::current_path()) / "output", {}, {}}; + models.workspace_file_access = policy; for (const auto* directory : {&config.lora_model_dir, &config.hires_upscalers_dir}) if (!directory->empty()) policy.models.push_back(make_model_root(fs::u8path(*directory), false)); for (const auto& entry : config.embedding_map) policy.configured_files.insert(model_path_key(fs::weakly_canonical(fs::absolute(fs::u8path(entry.second))))); - if (startup) - add_startup_model_sources(policy, config); + add_startup_model_sources(policy, config); if (sd_ctx_set_file_access_callback(models.context.get(), allowed_dgl_path, &policy) != SD_STATUS_OK) throw std::runtime_error(sd_get_last_error()); - if (sd_ctx_prepare(models.context.get()) != SD_STATUS_OK) + if (!sd_dgl_ctx_set_file_access_callback(sd_ctx_get_dgl_ctx(models.context.get()), allowed_dgl_path, &models.workspace_file_access)) throw std::runtime_error(sd_get_last_error()); } static bool execute_dgl_job(ServerRuntime& runtime, - DglExecution& execution, AsyncGenerationJob& job, std::shared_ptr& result, json& result_info, std::string& error_message) { try { - auto source = std::move(job.dgl_source); - execution.file_access = {get_model_roots(*runtime.svr_params), fs::canonical(fs::current_path()) / "output", {}, {}}; - if (!execution.context) { - std::unique_ptr context(sd_dgl_ctx_create(), sd_dgl_ctx_free); - if (!context || !runtime.ctx_params->configure_dgl(context.get()) || - !sd_dgl_ctx_set_file_access_callback(context.get(), allowed_dgl_path, &execution.file_access)) { - error_message = sd_dgl_error(); - return false; - } - execution.context = std::move(context); - } + auto source = std::move(job.dgl_source); sd_dgl_result_t* raw_result = nullptr; { std::lock_guard lock(*runtime.sd_ctx_mutex); update_job_progress(job, "executing", "dgl"); - if (sd_dgl_run(execution.context.get(), source.c_str(), nullptr, 0, &raw_result) != SD_STATUS_OK) { + if (sd_dgl_run(sd_ctx_get_dgl_ctx(runtime.sd_ctx), source.c_str(), nullptr, 0, &raw_result) != SD_STATUS_OK) { error_message = sd_dgl_error(); return false; } @@ -699,7 +706,6 @@ static bool execute_dgl_job(ServerRuntime& runtime, void async_job_worker(ServerRuntime& runtime) { AsyncJobManager& manager = *runtime.async_job_manager; - DglExecution dgl; while (true) { std::shared_ptr job; @@ -753,7 +759,7 @@ void async_job_worker(ServerRuntime& runtime) { output_info, error_message); } else if (job->kind == AsyncJobKind::Dgl) { - ok = execute_dgl_job(runtime, dgl, *job, dgl_result, dgl_result_info, error_message); + ok = execute_dgl_job(runtime, *job, dgl_result, dgl_result_info, error_message); } else { error_message = "unsupported job kind"; } diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h index 7cade97295..3c940fe637 100644 --- a/examples/server/async_jobs.h +++ b/examples/server/async_jobs.h @@ -12,7 +12,7 @@ #include -#include "runtime.h" +#include "model_catalog.h" enum class AsyncJobKind { ImgGen, @@ -50,6 +50,9 @@ struct AsyncGenerationJob { int64_t created_at = unix_timestamp_now_ms(); int64_t started_at = 0; int64_t completed_at = 0; + std::unique_ptr model; + json request_body; + uint64_t model_revision = 0; ImgGenJobRequest img_gen; VidGenJobRequest vid_gen; std::string dgl_source; @@ -91,6 +94,7 @@ std::string make_async_job_id(AsyncJobManager& manager); bool cancel_queued_job(AsyncJobManager& manager, AsyncGenerationJob& job); json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJob& job); int64_t dgl_image_frame_count(const sd_tensor_t* tensor); +bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message); bool execute_img_gen_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::vector& output_images, diff --git a/examples/server/frontend b/examples/server/frontend index 0166e07b64..d9fd4e6a93 160000 --- a/examples/server/frontend +++ b/examples/server/frontend @@ -1 +1 @@ -Subproject commit 0166e07b6468f7cb8e1fe81b2de997869ec56b16 +Subproject commit d9fd4e6a938b74ad97c7e464a8e689474b70c533 diff --git a/examples/server/main.cpp b/examples/server/main.cpp index af554ae580..b0b44cce3f 100644 --- a/examples/server/main.cpp +++ b/examples/server/main.cpp @@ -94,22 +94,15 @@ int main(int argc, const char** argv) { SDOptPtr sd_ctx_params = ctx_params.to_context_opt(); ServerModels models; - if (!ctx_params.model_path.empty() || !ctx_params.diffusion_model_path.empty()) { - const auto started = std::chrono::steady_clock::now(); - models.context.reset(create_sd_context(sd_ctx_params)); - if (models.context) { - try { - prepare_native_context(models, svr_params, ctx_params, true); - } catch (const std::exception& error) { - LOG_ERROR("Model preparation failed: %s", error.what()); - models.context.reset(); - } - } - models.status["load_elapsed_seconds"] = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); + models.context.reset(create_sd_context(sd_ctx_params)); + if (!models.context) { + LOG_ERROR("sd_ctx_create failed: %s", sd_get_last_error()); + return 1; } - - if ((!ctx_params.model_path.empty() || !ctx_params.diffusion_model_path.empty()) && !models.context) { - LOG_ERROR("sd_ctx_create failed"); + try { + configure_server_file_access(models, svr_params, ctx_params); + } catch (const std::exception& error) { + LOG_ERROR("Context setup failed: %s", error.what()); return 1; } diff --git a/examples/server/model_catalog.cpp b/examples/server/model_catalog.cpp index cbfc79d442..acf02b04e4 100644 --- a/examples/server/model_catalog.cpp +++ b/examples/server/model_catalog.cpp @@ -66,14 +66,6 @@ static void clear_model_paths(SDContextParams& params) { } } -bool component_paths_match(const SDContextParams& a, const SDContextParams& b) { - for (const auto& slot : k_model_slots) { - if ((a.*slot.field) != (b.*slot.field)) - return false; - } - return true; -} - std::string model_path_key(const fs::path& path) { #ifdef _WIN32 const auto value = path.generic_wstring(); @@ -426,25 +418,22 @@ json resolve_recipe_features(const json& recipe) { } json model_generation_features(const ServerRuntime& runtime) { - if (!runtime.sd_ctx || runtime.models->active_recipe.is_null()) { - json features = k_recipe_features; - for (auto& feature : features) - feature = false; + const auto& recipe = runtime.models->current_recipe; + if (!recipe.is_null()) { + auto features = recipe.at("effective_features"); + if (recipe.value("source", "") != "command_line") { + const auto& context = *runtime.ctx_params; + features["controlnet"] = features.at("controlnet").get() && !context.control_net_path.empty(); + features["high_noise"] = features.at("high_noise").get() && !context.high_noise_diffusion_model_path.empty(); + features["preview_tae"] = features.at("preview_tae").get() && !context.taesd_path.empty(); + features["ref_audios"] = features.at("ref_audios").get() && (!context.audio_vae_path.empty() || !context.audio_encoder_path.empty()); + features["ref_video_audios"] = features.at("ref_video_audios").get() && !context.audio_vae_path.empty(); + } return features; } - json features = resolve_recipe_features(runtime.models->active_recipe); - if (runtime.models->active_recipe.value("source", "") == "command_line") - return features; - // Optional components only become usable once selected and loaded. - features["ip_adapter"] = features.value("ip_adapter", false) && !runtime.ctx_params->ip_adapter_path.empty(); - features["controlnet"] = features.value("controlnet", false) && !runtime.ctx_params->control_net_path.empty(); - features["high_noise"] = features.value("high_noise", false) && !runtime.ctx_params->high_noise_diffusion_model_path.empty(); - features["preview_tae"] = features.value("preview_tae", false) && !runtime.ctx_params->taesd_path.empty(); - features["ref_audios"] = features.value("ref_audios", false) && - (!runtime.ctx_params->audio_vae_path.empty() || !runtime.ctx_params->audio_encoder_path.empty()); - features["ref_video_audios"] = features.value("ref_video_audios", false) && !runtime.ctx_params->audio_vae_path.empty(); - if (!runtime.ctx_params->pulid_weights_path.empty()) - features["slg"] = false; + json features = k_recipe_features; + for (auto& feature : features) + feature = false; return features; } @@ -689,12 +678,21 @@ void refresh_model_catalog(ServerRuntime& runtime) { models.catalog_errors = std::move(errors); } -json model_status(ServerRuntime& runtime) { - std::lock_guard lock(runtime.models->status_mutex); - auto& models = *runtime.models; - json status = models.status; - if (status["state"] == "loading" && !status["load_elapsed_seconds"].is_null()) { - status["load_elapsed_seconds"] = std::chrono::duration(std::chrono::steady_clock::now() - models.load_started_at).count(); +json model_status(const ServerRuntime& runtime) { + const auto& models = *runtime.models; + const auto& recipe = models.current_recipe; + const bool startup = !recipe.is_null() && recipe.value("source", "") == "command_line"; + json status = {{"state", recipe.is_null() ? "empty" : "configured"}, + {"recipe", recipe.is_null() || startup ? json(nullptr) : recipe.at("id")}, + {"models", models.current_files}, + {"error", nullptr}, + {"revision", models.revision}}; + if (startup) + status["origin"] = "command_line"; + if (!recipe.is_null()) { + status["runtime_recipe"] = {{"id", "@current"}, {"name", "Current server model"}, {"source", "current"}, {"size_multiple", recipe.value("size_multiple", 8)}, {"slots", json::array()}}; + if (recipe.contains("video_constraints")) + status["runtime_recipe"]["video_constraints"] = recipe.at("video_constraints"); } return status; } @@ -704,29 +702,26 @@ void initialize_server_models(ServerRuntime& runtime) { models.base_context = *runtime.ctx_params; clear_model_paths(models.base_context); models.base_defaults = *runtime.default_gen_params; - if (runtime.sd_ctx) { - models.status["state"] = "ready"; - models.status["origin"] = "command_line"; - json features = json::array(); + if (has_current_model(runtime)) { + json features = json::array(); for (const auto& feature : k_recipe_features) features.push_back(feature.first); - models.active_recipe = { + models.current_recipe = { {"id", "@command-line"}, {"name", "Command-line model (all features)"}, {"source", "command_line"}, - {"description", "Uses the loaded command-line model and its generation defaults."}, + {"description", "Uses the model and generation defaults specified on the command line."}, {"slots", json::array()}, {"defaults", json::object()}, {"size_multiple", 8}, {"features", features}, }; - models.active_recipe["effective_features"] = resolve_recipe_features(models.active_recipe); - models.status["runtime_recipe"] = models.active_recipe; + models.current_recipe["effective_features"] = resolve_recipe_features(models.current_recipe); } refresh_model_catalog(runtime); } -void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& context, SDGenerationParams& defaults, json* loaded_recipe) { +ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body) { check_keys(body, {"recipe", "models"}); const auto recipe_id = body.at("recipe").get(); // `models` is optional; unselected slots may fall back to recipe defaults below. @@ -739,10 +734,8 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con if (found == models.recipes.end()) throw std::runtime_error("unknown recipe"); const auto& recipe = found->second; - if (loaded_recipe) - *loaded_recipe = recipe; - context = models.base_context; - defaults = models.base_defaults; + auto context = models.base_context; + auto defaults = models.base_defaults; apply_recipe_context(recipe.value("context", json::object()), context); apply_recipe_defaults(recipe.value("defaults", json::object()), defaults); // Recipe-provided default models fill any slot the request did not select. @@ -770,8 +763,7 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con if (selection.contains(id)) throw std::runtime_error("specify only one of tae and taesd"); selection[id] = selection.at(alias); - // Keep only the declared spelling: equivalent loads must resolve - // to an identical selection for the idempotent-load comparison. + // Normalize the alias so the same selection reuses the current configuration. selection.erase(alias); } } @@ -796,20 +788,6 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con if (!allowed.count(it.key())) throw std::runtime_error("unknown model slot: " + it.key()); } - // Omitting an optional slot and sending it as an empty string resolve to - // the same context; drop the empty key so equivalent loads compare - // identically instead of rebuilding the context. The explicit empty - // string already overrode any recipe default during the merge, so its - // intent is preserved. - for (auto it = selection.begin(); it != selection.end();) { - if (!it->is_string() || !it->get().empty()) { - ++it; - continue; - } - it = selection.erase(it); - } - // Echo the fully resolved selection (recipe defaults merged in) for status reporting. - body["models"] = selection; for (const auto& group : recipe.value("required_any", json::array())) { if (std::none_of(group.begin(), group.end(), [&](const json& value) { return !selection.value(value.get(), std::string()).empty(); @@ -817,6 +795,36 @@ void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& con throw std::runtime_error("select at least one model from: " + group.dump()); } } - if (!context.resolve_and_validate(IMG_GEN)) + if (!context.resolve(IMG_GEN)) throw std::runtime_error("invalid model context parameters"); + auto options = context.to_context_opt(); + if (!options) + throw std::runtime_error(sd_get_last_error()); + for (auto it = selection.begin(); it != selection.end();) { + if (it.value() == "") + it = selection.erase(it); + else + ++it; + } + return {std::move(context), std::move(defaults), recipe, std::move(selection), std::move(options)}; +} + +bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, std::string& error_message) { + auto& models = *runtime.models; + std::unique_lock lock(models.model_mutex); + if (models.current_recipe == selection.recipe && models.current_files == selection.files && + std::all_of(std::begin(k_model_slots), std::end(k_model_slots), [&](const ModelSlot& slot) { + return runtime.ctx_params->*slot.field == selection.context.*slot.field; + })) + return true; + if (sd_ctx_set_model_options(runtime.sd_ctx, selection.options.get()) != SD_STATUS_OK) { + error_message = sd_get_last_error(); + return false; + } + *runtime.ctx_params = std::move(selection.context); + *runtime.default_gen_params = std::move(selection.defaults); + models.current_recipe = std::move(selection.recipe); + models.current_files = std::move(selection.files); + ++models.revision; + return true; } diff --git a/examples/server/model_catalog.h b/examples/server/model_catalog.h index d3488e510c..488cc14a52 100644 --- a/examples/server/model_catalog.h +++ b/examples/server/model_catalog.h @@ -1,7 +1,6 @@ #ifndef __SD_EXAMPLES_SERVER_MODEL_CATALOG_H__ #define __SD_EXAMPLES_SERVER_MODEL_CATALOG_H__ -#include #include #include #include @@ -38,37 +37,39 @@ struct ServerFileAccess { }; struct ServerModels { - std::shared_mutex runtime_mutex; + std::shared_mutex model_mutex; std::mutex catalog_mutex; - std::mutex status_mutex; ServerFileAccess file_access; + ServerFileAccess workspace_file_access; SDCtxPtr context; SDContextParams base_context; SDGenerationParams base_defaults; std::map recipes; std::map files; - std::chrono::steady_clock::time_point load_started_at; - json active_recipe = nullptr; + json current_recipe = nullptr; + json current_files = json::object(); + uint64_t revision = 0; json catalog_errors = json::array(); - json status = {{"state", "empty"}, {"recipe", nullptr}, {"models", json::object()}, {"error", nullptr}, {"load_elapsed_seconds", nullptr}}; +}; + +struct ServerModelSelection { + SDContextParams context; + SDGenerationParams defaults; + json recipe; + json files; + SDOptPtr options; }; void refresh_model_catalog(ServerRuntime& runtime); -json model_status(ServerRuntime& runtime); +json model_status(const ServerRuntime& runtime); void initialize_server_models(ServerRuntime& runtime); json resolve_recipe_features(const json& recipe); json model_generation_features(const ServerRuntime& runtime); -// Resolves the load request into context/generation params. `body` is updated -// so `models` reflects the fully resolved selection (recipe defaults merged in), -// letting the caller report exactly which components got loaded. -void prepare_model_load(ServerRuntime& runtime, json& body, SDContextParams& context, SDGenerationParams& defaults, json* loaded_recipe = nullptr); - -// True when both parameter sets resolve to the same component files. File IDs -// stay stable if a model directory symlink is retargeted inside the configured -// root, so the idempotent-load check compares the resolved paths too. -bool component_paths_match(const SDContextParams& a, const SDContextParams& b); +ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body); +// The caller holds the generation mutex across the switch and generation. +bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, std::string& error_message); void add_startup_model_sources(ServerFileAccess& policy, const SDContextParams& config); #endif diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp index 8fd0a3a4b9..7290512922 100644 --- a/examples/server/routes_dgl.cpp +++ b/examples/server/routes_dgl.cpp @@ -227,32 +227,30 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { send_json(res, updating ? 200 : 201, {{"name", name}}); })); - RuntimeRoutes routes(svr, runtime); - // Use the model transition lock during admission, as with image and video jobs. - routes.post("/sdcpp/v1/dgl/jobs", local_dgl_route([&runtime](const Request& req, Response& res) { - auto source = json::parse(req.body).at("source").get(); - if (source.empty() || !valid_source(source)) { - send_error(res, 400, "Expected non-empty UTF-8 source"); - return; - } - auto job = std::make_shared(); - job->kind = AsyncJobKind::Dgl; - job->dgl_source = std::move(source); - auto& manager = *runtime.async_job_manager; - { - std::lock_guard lock(manager.mutex); - purge_expired_jobs(manager); - if (count_pending_jobs(manager) >= manager.max_pending_jobs) { - send_error(res, 429, "Job queue is full"); - return; - } - job->id = make_async_job_id(manager); - manager.jobs.emplace(job->id, job); - manager.queue.push_back(job->id); - send_json(res, 202, make_async_job_json(manager, *job)); - } - manager.cv.notify_one(); - })); + svr.Post("/sdcpp/v1/dgl/jobs", local_dgl_route([&runtime](const Request& req, Response& res) { + auto source = json::parse(req.body).at("source").get(); + if (source.empty() || !valid_source(source)) { + send_error(res, 400, "Expected non-empty UTF-8 source"); + return; + } + auto job = std::make_shared(); + job->kind = AsyncJobKind::Dgl; + job->dgl_source = std::move(source); + auto& manager = *runtime.async_job_manager; + { + std::lock_guard lock(manager.mutex); + purge_expired_jobs(manager); + if (count_pending_jobs(manager) >= manager.max_pending_jobs) { + send_error(res, 429, "Job queue is full"); + return; + } + job->id = make_async_job_id(manager); + manager.jobs.emplace(job->id, job); + manager.queue.push_back(job->id); + send_json(res, 202, make_async_job_json(manager, *job)); + } + manager.cv.notify_one(); + })); svr.Get(R"(/sdcpp/v1/dgl/jobs/([A-Za-z0-9_-]+))", local_dgl_route([&runtime](const Request& req, Response& res) { auto& manager = *runtime.async_job_manager; diff --git a/examples/server/routes_models.cpp b/examples/server/routes_models.cpp index d7db0d6fe2..7072aa19ca 100644 --- a/examples/server/routes_models.cpp +++ b/examples/server/routes_models.cpp @@ -1,6 +1,5 @@ #include "routes.h" -#include "async_jobs.h" #include "model_catalog.h" static void model_error(httplib::Response& res, int status, const std::string& code, const std::string& message) { @@ -11,127 +10,35 @@ static void model_error(httplib::Response& res, int status, const std::string& c httplib::Server::Handler RuntimeRoutes::protect(httplib::Server::Handler handler) { ServerRuntime* runtime = &runtime_; return [runtime, handler](const httplib::Request& req, httplib::Response& res) { - std::shared_lock lock(runtime->models->runtime_mutex, std::try_to_lock); - if (!lock.owns_lock()) { - model_error(res, 503, "model_loading", "Model is loading or unloading"); - return; - } - const bool generation = req.path == "/sdcpp/v1/img_gen" || req.path == "/sdcpp/v1/vid_gen" || - req.path == "/sdapi/v1/txt2img" || req.path == "/sdapi/v1/img2img" || + const bool generation = req.path == "/sdapi/v1/txt2img" || req.path == "/sdapi/v1/img2img" || req.path == "/v1/images/generations" || req.path == "/v1/images/edits"; - if (generation && !runtime->sd_ctx) { - model_error(res, 503, "model_not_loaded", "No model is loaded"); - return; + if (generation) { + std::lock_guard lock(*runtime->sd_ctx_mutex); + if (!has_current_model(*runtime)) { + model_error(res, 503, "model_not_loaded", "No current model is configured"); + return; + } + handler(req, res); + } else { + handler(req, res); } - handler(req, res); }; } void RuntimeRoutes::get(const std::string& pattern, httplib::Server::Handler handler) { - // Job polling and cancellation only access the job manager, even during a model transition. - server_.Get(pattern, pattern.find("/sdcpp/v1/jobs/") != std::string::npos ? handler : protect(handler)); -} - -void RuntimeRoutes::post(const std::string& pattern, httplib::Server::Handler handler) { - server_.Post(pattern, pattern.find("/sdcpp/v1/jobs/") != std::string::npos ? handler : protect(handler)); -} - -static void set_model_status(ServerRuntime& runtime, const char* state, const json& recipe, const json& selection, const json& error = nullptr) { - std::lock_guard lock(runtime.models->status_mutex); - auto& models = *runtime.models; - const uint64_t revision = models.status.value("revision", uint64_t(0)) + 1; - json elapsed = nullptr; - if (!recipe.is_null()) { - const auto now = std::chrono::steady_clock::now(); - if (std::string(state) == "loading") { - models.load_started_at = now; - elapsed = 0.0; - } else { - elapsed = std::chrono::duration(now - models.load_started_at).count(); - } - } - models.status = {{"state", state}, {"recipe", recipe}, {"models", selection}, {"error", error}, {"revision", revision}, {"load_elapsed_seconds", elapsed}}; -} - -static void change_model(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, bool unload) { - auto& models = *runtime.models; - std::unique_lock lock(models.runtime_mutex, std::try_to_lock); - if (!lock.owns_lock()) { - model_error(res, 409, "model_busy", "Model is in use or another model operation is running"); + if (pattern.find("/sdcpp/v1/jobs/") != std::string::npos) { + server_.Get(pattern, handler); return; } - { - // Admission holds runtime_mutex through enqueue. Jobs stay pending until - // generation and metadata encoding finish, so no worker can retain this context here. - std::lock_guard jobs_lock(runtime.async_job_manager->mutex); - if (count_pending_jobs(*runtime.async_job_manager) != 0) { - model_error(res, 409, "model_busy", "Finish or cancel pending generation jobs before switching models"); - return; - } - } - - json body; - json loaded_recipe; - SDContextParams context; - SDGenerationParams defaults; - if (!unload) { - try { - body = json::parse(req.body); - prepare_model_load(runtime, body, context, defaults, &loaded_recipe); - } catch (const std::exception& e) { - model_error(res, 400, "invalid_model_config", e.what()); - return; - } - } - - // Idempotent load: if this exact recipe and resolved selection are already - // active, report the current status instead of tearing down the context. - // Comparing full recipe objects (not just the id) also reloads when the - // catalog was refreshed with modified recipe metadata for the same id. - // Comparing resolved component paths catches the same file IDs resolving - // to different files (e.g. a model directory symlink retargeted inside - // the configured root since the catalog was last scanned). - if (!unload) { - json current = model_status(runtime); - if (current.value("state", "") == "ready" && current.value("recipe", json(nullptr)) == body.at("recipe") && - current.value("models", json::object()) == body.at("models") && models.active_recipe == loaded_recipe && - component_paths_match(*runtime.ctx_params, context)) { - current["already_loaded"] = true; - res.set_content(current.dump(), "application/json"); - return; - } - } + ServerModels* models = runtime_.models; + server_.Get(pattern, [models, handler](const httplib::Request& req, httplib::Response& res) { + std::shared_lock lock(models->model_mutex); + handler(req, res); + }); +} - const json recipe = unload ? json(nullptr) : body.at("recipe"); - const json selection = unload ? json::object() : body.value("models", json::object()); - set_model_status(runtime, "loading", recipe, selection); - try { - runtime.sd_ctx = nullptr; - models.context.reset(); - models.active_recipe = nullptr; - *runtime.ctx_params = unload ? models.base_context : std::move(context); - *runtime.default_gen_params = unload ? models.base_defaults : std::move(defaults); - if (!unload) { - auto params = runtime.ctx_params->to_context_opt(); - models.context.reset(create_sd_context(params)); - if (!models.context) { - throw std::runtime_error("Model initialization failed; check the server log for component compatibility and memory errors"); - } - prepare_native_context(models, *runtime.svr_params, *runtime.ctx_params); - runtime.sd_ctx = models.context.get(); - models.active_recipe = std::move(loaded_recipe); - } - set_model_status(runtime, unload ? "empty" : "ready", recipe, selection); - res.set_content(model_status(runtime).dump(), "application/json"); - } catch (const std::exception& e) { - runtime.sd_ctx = nullptr; - models.context.reset(); - models.active_recipe = nullptr; - *runtime.ctx_params = models.base_context; - *runtime.default_gen_params = models.base_defaults; - set_model_status(runtime, "error", recipe, selection, e.what()); - model_error(res, 422, "model_load_failed", e.what()); - } +void RuntimeRoutes::post(const std::string& pattern, httplib::Server::Handler handler) { + server_.Post(pattern, protect(handler)); } void register_model_endpoints(httplib::Server& svr, ServerRuntime& runtime) { @@ -158,12 +65,7 @@ void register_model_endpoints(httplib::Server& svr, ServerRuntime& runtime) { res.set_content(json({{"errors", runtime.models->catalog_errors}}).dump(), "application/json"); }); svr.Get("/sdcpp/v1/models/status", [&runtime](const httplib::Request&, httplib::Response& res) { + std::shared_lock lock(runtime.models->model_mutex); res.set_content(model_status(runtime).dump(), "application/json"); }); - svr.Post("/sdcpp/v1/models/load", [&runtime](const httplib::Request& req, httplib::Response& res) { - change_model(runtime, req, res, false); - }); - svr.Post("/sdcpp/v1/models/unload", [&runtime](const httplib::Request& req, httplib::Response& res) { - change_model(runtime, req, res, true); - }); } diff --git a/examples/server/routes_openai.cpp b/examples/server/routes_openai.cpp index b92d075465..0fe6537524 100644 --- a/examples/server/routes_openai.cpp +++ b/examples/server/routes_openai.cpp @@ -218,23 +218,7 @@ static bool execute_sync_img_gen_request(ServerRuntime& runtime, ImgGenJobRequest& request, SDImageVec& results, std::string& error_message) { - SDOptPtr img_gen_params = request.to_image_opt(); - int num_results = 0; - - { - std::lock_guard lock(*runtime.sd_ctx_mutex); - PromptImageCallbackGuard prompt_images(runtime.sd_ctx, request.gen_params); - sd_result_t* generated = nullptr; - generate_sd_image(runtime.sd_ctx, img_gen_params, &generated); - results.adopt(generated); - num_results = results.count(); - } - - if (results.empty()) { - error_message = "generate_image returned no results"; - return false; - } - return true; + return generate_server_images(runtime.sd_ctx, request, results, error_message); } void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { @@ -244,7 +228,7 @@ void register_openai_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { routes.get("/v1/models", [runtime](const httplib::Request&, httplib::Response& res) { json r; r["data"] = json::array(); - if (runtime->sd_ctx) { + if (has_current_model(*runtime)) { r["data"].push_back({{"id", "sd-cpp-local"}, {"object", "model"}, {"owned_by", "local"}}); } res.set_content(r.dump(), "application/json"); diff --git a/examples/server/routes_sdapi.cpp b/examples/server/routes_sdapi.cpp index 8539e53afb..780a1e598c 100644 --- a/examples/server/routes_sdapi.cpp +++ b/examples/server/routes_sdapi.cpp @@ -582,18 +582,13 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { LOG_DEBUG("%s\n", request.gen_params.to_string().c_str()); - SDOptPtr img_gen_params = request.to_image_opt(); SDImageVec results; int num_results = 0; { - std::lock_guard lock(*runtime->sd_ctx_mutex); - PromptImageCallbackGuard prompt_images(runtime->sd_ctx, request.gen_params); const bool detailing = request.adetailer_enabled && !runtime->default_gen_params->ad_model_path.empty(); SDAPIPreviewGuard preview_guard(id_task, request.gen_params, img2img ? "img2img" : "txt2img", detailing); - sd_result_t* generated = nullptr; - generate_sd_image(runtime->sd_ctx, img_gen_params, &generated); - results.adopt(generated); + generate_server_images(runtime->sd_ctx, request, results, error_message); num_results = results.count(); if (detailing && !results.empty()) preview_guard.begin_detailing(); @@ -601,7 +596,7 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { if (results.empty()) { res.status = 500; - res.set_content(R"({"error":"generate_image returned no results"})", "application/json"); + res.set_content(json({{"error", error_message}}).dump(), "application/json"); return; } @@ -777,7 +772,7 @@ void register_sdapi_endpoints(httplib::Server& svr, ServerRuntime& rt) { entry["sha256"] = "8888888888888888888888888888888888888888888888888888888888888888"; entry["config"] = nullptr; json r = json::array(); - if (runtime->sd_ctx) { + if (has_current_model(*runtime)) { r.push_back(entry); } res.set_content(r.dump(), "application/json"); diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index 8fe235af2b..587407aa9d 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -1,36 +1,16 @@ #include "routes.h" -#include #include #include -#include +#include #include "async_jobs.h" #include "common/common.h" -#include "common/media_io.h" #include "common/resource_owners.hpp" #include "model_catalog.h" namespace fs = std::filesystem; -static constexpr uint32_t k_max_upscale_dimension = 8192; - -static bool valid_upscale_dimensions(const SDImage& image, int factor, int repeats) { - if (image.width == 0 || image.height == 0 || factor < 1 || repeats < 1 || repeats > 4) { - return false; - } - uint32_t width = image.width; - uint32_t height = image.height; - for (int i = 0; i < repeats; ++i) { - if (width > k_max_upscale_dimension / factor || height > k_max_upscale_dimension / factor) { - return false; - } - width *= factor; - height *= factor; - } - return true; -} - static bool parse_cache_mode(const std::string& value, std::string& mode) { const std::string canonical = value == "cache-dit" ? "cache_dit" : value; SDOptPtr opt(sd_img_gen_opt_create()); @@ -247,58 +227,46 @@ static json make_capabilities_json(ServerRuntime& runtime) { available_upscalers.push_back({ {"name", "None"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Lanczos"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Nearest"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (nearest)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (nearest-exact)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (antialiased)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (bicubic)"}, {"model", false}, - {"image_upscale", false}, }); available_upscalers.push_back({ {"name", "Latent (bicubic antialiased)"}, {"model", false}, - {"image_upscale", false}, }); - bool have_upscaler_models = false; { std::lock_guard lock(*runtime.upscaler_mutex); for (const auto& entry : *runtime.upscaler_cache) { available_upscalers.push_back({ {"name", entry.name}, {"model", true}, - {"image_upscale", entry.image_upscale_factor > 0}, }); - have_upscaler_models = have_upscaler_models || entry.image_upscale_factor > 0; } } @@ -335,17 +303,15 @@ static json make_capabilities_json(ServerRuntime& runtime) { return features; }; json defaults_by_mode = json::object(); - json output_formats_by_mode = json::object(); + json output_formats_by_mode = {{"img_gen", image_output_formats}, {"vid_gen", video_output_formats}}; json features_by_mode = json::object(); if (supports_img) { - defaults_by_mode["img_gen"] = make_img_gen_defaults_json(defaults, default_img_output_format); - output_formats_by_mode["img_gen"] = image_output_formats; - features_by_mode["img_gen"] = recipe_features(make_img_gen_features_json(), false); + defaults_by_mode["img_gen"] = make_img_gen_defaults_json(defaults, default_img_output_format); + features_by_mode["img_gen"] = recipe_features(make_img_gen_features_json(), false); } if (supports_vid) { - defaults_by_mode["vid_gen"] = make_vid_gen_defaults_json(defaults, default_vid_output_format); - output_formats_by_mode["vid_gen"] = video_output_formats; - features_by_mode["vid_gen"] = recipe_features(make_vid_gen_features_json(), true); + defaults_by_mode["vid_gen"] = make_vid_gen_defaults_json(defaults, default_vid_output_format); + features_by_mode["vid_gen"] = recipe_features(make_vid_gen_features_json(), true); } json top_level_defaults = json::object(); @@ -373,21 +339,20 @@ static json make_capabilities_json(ServerRuntime& runtime) { {"stem", model_path.stem().u8string()}, {"path", model_path.u8string()}, }; - result["generation_features"] = generation_features; - result["runtime"] = model_status(runtime); - result["current_mode"] = current_mode; - result["supported_modes"] = supported_modes; - result["defaults"] = top_level_defaults; - result["defaults_by_mode"] = defaults_by_mode; - result["limits"] = { + result["generation_features"] = generation_features; + result["generation_model_selection"] = true; + result["runtime"] = model_status(runtime); + result["current_mode"] = current_mode; + result["supported_modes"] = supported_modes; + result["defaults"] = top_level_defaults; + result["defaults_by_mode"] = defaults_by_mode; + result["limits"] = { {"min_width", 64}, {"max_width", k_max_generation_dimension}, {"min_height", 64}, {"max_height", k_max_generation_dimension}, {"max_batch_count", 8}, {"max_queue_size", manager.max_pending_jobs}, - {"max_upscale_width", k_max_upscale_dimension}, - {"max_upscale_height", k_max_upscale_dimension}, }; result["samplers"] = samplers; result["schedulers"] = schedulers; @@ -397,7 +362,6 @@ static json make_capabilities_json(ServerRuntime& runtime) { result["features_by_mode"] = features_by_mode; result["loras"] = available_loras; result["upscalers"] = available_upscalers; - result["upscale"] = have_upscaler_models; result["preview_modes"] = make_preview_modes_json(); return result; } @@ -460,7 +424,7 @@ static bool parse_vid_gen_request(const json& body, merge_shared_sample_input("flow_shift", &SDSampleParams::flow_shift); merge_shared_sample_input("shifted_timestep", &SDSampleParams::shifted_timestep); - std::string output_format = body.value("output_format", "webm"); + std::string output_format = body.value("output_format", supported_vid_output_formats().front()); int output_compression = body.value("output_compression", 100); if (!assign_output_options(request, output_format, output_compression, error_message)) { return false; @@ -475,304 +439,113 @@ static bool parse_vid_gen_request(const json& body, return true; } -void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { - ServerRuntime* runtime = &rt; - RuntimeRoutes routes(svr, rt); - - routes.get("/sdcpp/v1/capabilities", [runtime](const httplib::Request&, httplib::Response& res) { - res.status = 200; - res.set_content(make_capabilities_json(*runtime).dump(), "application/json"); - }); - - routes.post("/sdcpp/v1/upscale", [runtime](const httplib::Request& req, httplib::Response& res) { - try { - if (req.body.empty()) { - res.status = 400; - res.set_content(R"({"error":"empty body"})", "application/json"); - return; - } - json body = json::parse(req.body); - if (!body.is_object()) { - res.status = 400; - res.set_content(R"({"error":"body must be an object"})", "application/json"); - return; - } - for (const char* key : {"repeats", "tile_size", "output_compression"}) { - if (!body.contains(key)) { - continue; - } - const auto& value = body[key]; - const bool valid = value.is_number_unsigned() - ? value.get() <= static_cast(std::numeric_limits::max()) - : value.is_number_integer() && value.get() >= std::numeric_limits::min() && - value.get() <= std::numeric_limits::max(); - if (!valid) { - res.status = 400; - res.set_content(json({{"error", std::string(key) + " must be a 32-bit integer"}}).dump(), "application/json"); - return; - } - } - ImgGenJobRequest output_options; - std::string error_message; - if (!assign_output_options(output_options, - body.value("output_format", std::string("png")), - body.value("output_compression", 100), - true, - error_message)) { - res.status = 400; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); - return; - } - const auto tile_size = body.value("tile_size", runtime->default_gen_params->upscale_tile_size); - if (tile_size && *tile_size < 32) { - res.status = 400; - res.set_content(json({{"error", "tile_size must be at least 32"}}).dump(), "application/json"); - return; - } - const int repeats = std::clamp(body.value("repeats", 1), 1, 4); - const std::string wanted = body.value("upscaler", std::string()); - - const std::string encoded = body.value("image", std::string()); - if (encoded.empty()) { - res.status = 400; - res.set_content(R"({"error":"image is required"})", "application/json"); - return; - } - SDImageOwner input; - if (!decode_base64_image(encoded, 3, 0, 0, input) || input.get().data == nullptr) { - res.status = 400; - res.set_content(R"({"error":"image could not be read"})", "application/json"); - return; - } - - refresh_upscaler_cache(*runtime); - int model_scale = 0; - std::string model_path; - std::string used_name; - { - std::lock_guard lock(*runtime->upscaler_mutex); - for (const auto& entry : *runtime->upscaler_cache) { - if (entry.image_upscale_factor > 0 && (wanted.empty() || entry.name == wanted)) { - model_path = entry.fullpath; - used_name = entry.name; - model_scale = entry.image_upscale_factor; - break; - } - } - } - if (model_path.empty()) { - res.status = 400; - res.set_content(json({{"error", wanted.empty() - ? std::string("no RGB ESRGAN upscaler models are available; " - "start the server with --hires-upscalers-dir") - : "no compatible image upscaler called " + wanted}}) - .dump(), - "application/json"); - return; - } - - if (!valid_upscale_dimensions(input.get(), model_scale, repeats)) { - res.status = 400; - res.set_content(R"({"error":"upscaled dimensions must not exceed 8192 x 8192"})", "application/json"); - return; - } - - // One GPU: an upscale must not run while a generation is using it. - std::lock_guard ctx_lock(*runtime->sd_ctx_mutex); - UpscalerCtxPtr upscaler_ctx(create_sd_upscaler(model_path.c_str(), - runtime->ctx_params->diffusion_conv_direct, - runtime->ctx_params->n_threads, - tile_size, - runtime->ctx_params->backend ? runtime->ctx_params->backend->c_str() : nullptr, - runtime->ctx_params->params_backend ? runtime->ctx_params->params_backend->c_str() : nullptr)); - if (upscaler_ctx == nullptr) { - res.status = 500; - res.set_content(R"({"error":"the upscaler model could not be loaded"})", "application/json"); - return; - } - const int factor = sd_upscaler_get_scale(upscaler_ctx.get()); - // The model file may have changed since its metadata was cached. - if (!valid_upscale_dimensions(input.get(), factor, repeats)) { - res.status = 400; - res.set_content(R"({"error":"upscaled dimensions must not exceed 8192 x 8192"})", "application/json"); - return; - } - - SDImageOwner current(input.release()); - std::string generation_info; - sd_result_t* generated = nullptr; - if (!upscale_sd_image(upscaler_ctx.get(), current.get(), &generated, repeats) || !generated) { - sd_result_free(generated); - res.status = 500; - res.set_content(R"({"error":"upscale failed"})", "application/json"); - return; - } - generation_info = sd_result_get_generation_info(generated, 0); - current.reset(take_result_image(generated, 0)); - sd_result_free(generated); - - const std::string& format = output_options.output_format; - const int compression = output_options.output_compression; - const SDImage result = current.get(); - auto image_bytes = encode_image_to_vector(format == "jpeg" ? EncodedImageFormat::JPEG - : format == "webp" ? EncodedImageFormat::WEBP - : EncodedImageFormat::PNG, - result.data, - result.width, - result.height, - result.channel, - generation_info, - compression); - if (image_bytes.empty()) { - res.status = 500; - res.set_content(R"({"error":"the result could not be encoded"})", "application/json"); - return; - } +bool parse_native_job_request(const json& body, ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message) { + return job.kind == AsyncJobKind::VidGen ? parse_vid_gen_request(body, runtime, job.vid_gen, error_message) + : parse_img_gen_request(body, runtime, job.img_gen, error_message); +} - json out; - out["generation_info"] = generation_info; - out["upscaler"] = used_name; - out["scale"] = factor; - out["repeats"] = repeats; - out["width"] = result.width; - out["height"] = result.height; - out["output_format"] = format; - json images = json::array(); - images.push_back({{"index", 0}, {"b64_json", base64_encode(image_bytes)}}); - out["images"] = std::move(images); - res.set_content(out.dump(), "application/json"); - res.status = 200; - } catch (const json::exception& e) { +static void submit_generation_job(ServerRuntime& runtime, const httplib::Request& req, httplib::Response& res, SDMode mode) { + try { + if (req.body.empty()) { res.status = 400; - res.set_content(json({{"error", "invalid request"}, {"message", e.what()}}).dump(), "application/json"); - } catch (const std::exception& e) { - res.status = 500; - res.set_content(json({{"error", std::string("server_error: ") + e.what()}}).dump(), "application/json"); + res.set_content(R"({"error":"empty body"})", "application/json"); + return; + } + auto body = json::parse(req.body); + if (!body.is_object()) { + res.status = 400; + res.set_content(R"({"error":"generation request must be an object"})", "application/json"); + return; } - }); - routes.post("/sdcpp/v1/img_gen", [runtime](const httplib::Request& req, httplib::Response& res) { - try { - if (req.body.empty()) { + auto job = std::make_shared(); + job->kind = mode == VID_GEN ? AsyncJobKind::VidGen : AsyncJobKind::ImgGen; + ServerRuntime request_runtime = runtime; + std::shared_lock model_lock(runtime.models->model_mutex, std::defer_lock); + if (auto model = body.find("model"); model != body.end()) { + try { + job->model = std::make_unique(resolve_model_selection(runtime, *model)); + } catch (const std::exception& error) { res.status = 400; - res.set_content(R"({"error":"empty body"})", "application/json"); + res.set_content(json({{"error", error.what()}, {"code", "invalid_model_config"}}).dump(), "application/json"); return; } - if (!runtime_supports_generation_mode(*runtime, IMG_GEN)) { - res.status = 400; - res.set_content(json({{"error", unsupported_generation_mode_error(IMG_GEN)}}).dump(), "application/json"); + body.erase(model); + request_runtime.ctx_params = &job->model->context; + request_runtime.default_gen_params = &job->model->defaults; + } else { + model_lock.lock(); + if (!has_current_model(runtime)) { + res.status = 503; + res.set_content(R"({"error":"No current model is configured","code":"model_not_loaded"})", "application/json"); return; } - - json body = json::parse(req.body); - ImgGenJobRequest request; - std::string error_message; - if (!parse_img_gen_request(body, *runtime, request, error_message)) { + if (!runtime_supports_generation_mode(runtime, mode)) { res.status = 400; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); + res.set_content(json({{"error", unsupported_generation_mode_error(mode)}}).dump(), "application/json"); return; } + } - AsyncJobManager& manager = *runtime->async_job_manager; - std::shared_ptr job = std::make_shared(); - job->kind = AsyncJobKind::ImgGen; - job->status = AsyncJobStatus::Queued; - job->created_at = unix_timestamp_now_ms(); - job->img_gen = std::move(request); - - { - std::lock_guard lock(manager.mutex); - purge_expired_jobs(manager); - if (count_pending_jobs(manager) >= manager.max_pending_jobs) { - res.status = 429; - res.set_content(R"({"error":"job queue is full"})", "application/json"); - return; - } - job->id = make_async_job_id(manager); - manager.jobs[job->id] = job; - manager.queue.push_back(job->id); - } - - manager.cv.notify_one(); - - json out; - out["id"] = job->id; - out["kind"] = async_job_kind_name(job->kind); - out["status"] = async_job_status_name(job->status); - out["created"] = job->created_at; - out["poll_url"] = "/sdcpp/v1/jobs/" + job->id; - - res.status = 202; - res.set_content(out.dump(), "application/json"); - } catch (const json::parse_error& e) { + std::string error_message; + if (!parse_native_job_request(body, request_runtime, *job, error_message)) { res.status = 400; - res.set_content(json({{"error", "invalid json"}, {"message", e.what()}}).dump(), "application/json"); - } catch (const std::exception& e) { - res.status = 500; - res.set_content(json({{"error", "server_error"}, {"message", e.what()}}).dump(), "application/json"); + res.set_content(json({{"error", error_message}}).dump(), "application/json"); + return; + } + if (model_lock.owns_lock()) { + job->model_revision = runtime.models->revision; + job->request_body = std::move(body); + model_lock.unlock(); } - }); - - routes.post("/sdcpp/v1/vid_gen", [runtime](const httplib::Request& req, httplib::Response& res) { - try { - if (req.body.empty()) { - res.status = 400; - res.set_content(R"({"error":"empty body"})", "application/json"); - return; - } - if (!runtime_supports_generation_mode(*runtime, VID_GEN)) { - res.status = 400; - res.set_content(json({{"error", unsupported_generation_mode_error(VID_GEN)}}).dump(), "application/json"); - return; - } - json body = json::parse(req.body); - VidGenJobRequest request; - std::string error_message; - if (!parse_vid_gen_request(body, *runtime, request, error_message)) { - res.status = 400; - res.set_content(json({{"error", error_message}}).dump(), "application/json"); + auto& manager = *runtime.async_job_manager; + { + std::lock_guard lock(manager.mutex); + purge_expired_jobs(manager); + if (count_pending_jobs(manager) >= manager.max_pending_jobs) { + res.status = 429; + res.set_content(R"({"error":"job queue is full"})", "application/json"); return; } + job->id = make_async_job_id(manager); + manager.jobs[job->id] = job; + manager.queue.push_back(job->id); + } + manager.cv.notify_one(); + + json out; + out["id"] = job->id; + out["kind"] = async_job_kind_name(job->kind); + out["status"] = async_job_status_name(AsyncJobStatus::Queued); + out["created"] = job->created_at; + out["poll_url"] = "/sdcpp/v1/jobs/" + job->id; + res.status = 202; + res.set_content(out.dump(), "application/json"); + } catch (const json::parse_error& error) { + res.status = 400; + res.set_content(json({{"error", "invalid json"}, {"message", error.what()}}).dump(), "application/json"); + } catch (const std::exception& error) { + res.status = 500; + res.set_content(json({{"error", "server_error"}, {"message", error.what()}}).dump(), "application/json"); + } +} - AsyncJobManager& manager = *runtime->async_job_manager; - std::shared_ptr job = std::make_shared(); - job->kind = AsyncJobKind::VidGen; - job->status = AsyncJobStatus::Queued; - job->created_at = unix_timestamp_now_ms(); - job->vid_gen = std::move(request); - - { - std::lock_guard lock(manager.mutex); - purge_expired_jobs(manager); - if (count_pending_jobs(manager) >= manager.max_pending_jobs) { - res.status = 429; - res.set_content(R"({"error":"job queue is full"})", "application/json"); - return; - } - job->id = make_async_job_id(manager); - manager.jobs[job->id] = job; - manager.queue.push_back(job->id); - } +void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { + ServerRuntime* runtime = &rt; + RuntimeRoutes routes(svr, rt); - manager.cv.notify_one(); + routes.get("/sdcpp/v1/capabilities", [runtime](const httplib::Request&, httplib::Response& res) { + res.status = 200; + res.set_content(make_capabilities_json(*runtime).dump(), "application/json"); + }); - json out; - out["id"] = job->id; - out["kind"] = async_job_kind_name(job->kind); - out["status"] = async_job_status_name(job->status); - out["created"] = job->created_at; - out["poll_url"] = "/sdcpp/v1/jobs/" + job->id; + routes.post("/sdcpp/v1/img_gen", [runtime](const httplib::Request& req, httplib::Response& res) { + submit_generation_job(*runtime, req, res, IMG_GEN); + }); - res.status = 202; - res.set_content(out.dump(), "application/json"); - } catch (const json::parse_error& e) { - res.status = 400; - res.set_content(json({{"error", "invalid json"}, {"message", e.what()}}).dump(), "application/json"); - } catch (const std::exception& e) { - res.status = 500; - res.set_content(json({{"error", "server_error"}, {"message", e.what()}}).dump(), "application/json"); - } + routes.post("/sdcpp/v1/vid_gen", [runtime](const httplib::Request& req, httplib::Response& res) { + submit_generation_job(*runtime, req, res, VID_GEN); }); routes.get(R"(/sdcpp/v1/jobs/([A-Za-z0-9_\-]+))", [runtime](const httplib::Request& req, httplib::Response& res) { diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index c473c06821..7b9c4aca1d 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -233,6 +233,9 @@ std::string video_mime_type(const std::string& output_format) { } bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) { + if (!has_current_model(runtime)) { + return false; + } if (mode == VID_GEN) { return sd_ctx_supports_video_generation(runtime.sd_ctx); } @@ -242,14 +245,39 @@ bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode) return true; } +bool has_current_model(const ServerRuntime& runtime) { + return !runtime.ctx_params->model_path.empty() || !runtime.ctx_params->diffusion_model_path.empty(); +} + +bool generate_server_images(sd_ctx_t* ctx, ImgGenJobRequest& request, SDImageVec& results, std::string& error_message) { + auto params = request.to_image_opt(); + PromptImageCallbackGuard prompt_images(ctx, request.gen_params); + sd_result_t* generated = nullptr; + if (!generate_sd_image(ctx, params, &generated)) { + error_message = sd_get_last_error(); + if (error_message.empty()) + error_message = "generate_image returned no results"; + return false; + } + results.adopt(generated); + if (results.empty()) { + error_message = "generate_image returned no results"; + return false; + } + return true; +} + std::string unsupported_generation_mode_error(SDMode mode) { + if (const auto* error = sd_get_last_error(); *error) { + return error; + } if (mode == VID_GEN) { - return "loaded model does not support vid_gen"; + return "current model does not support vid_gen"; } if (mode == IMG_GEN) { - return "loaded model does not support img_gen"; + return "current model does not support img_gen"; } - return "loaded model does not support requested mode"; + return "current model does not support requested mode"; } ArgOptions SDSvrParams::get_options() { @@ -458,10 +486,9 @@ void refresh_upscaler_cache(ServerRuntime& rt) { UpscalerEntry upscaler_entry; upscaler_entry.name = p.stem().u8string(); std::error_code abs_ec; - fs::path abs_path = fs::absolute(p, abs_ec); - upscaler_entry.fullpath = (abs_ec ? p : abs_path.lexically_normal()).u8string(); - upscaler_entry.model_name = "ESRGAN_4x"; - upscaler_entry.path = p.filename().u8string(); + fs::path abs_path = fs::absolute(p, abs_ec); + upscaler_entry.fullpath = (abs_ec ? p : abs_path.lexically_normal()).u8string(); + upscaler_entry.path = p.filename().u8string(); std::error_code size_ec; upscaler_entry.file_size = it->file_size(size_ec); @@ -471,19 +498,15 @@ void refresh_upscaler_cache(ServerRuntime& rt) { } std::error_code time_ec; - upscaler_entry.last_modified = it->last_write_time(time_ec); - auto previous = std::find_if(previous_cache.begin(), previous_cache.end(), [&](const UpscalerEntry& cached) { + upscaler_entry.last_modified = it->last_write_time(time_ec); + auto previous = std::find_if(previous_cache.begin(), previous_cache.end(), [&](const UpscalerEntry& cached) { return cached.fullpath == upscaler_entry.fullpath && cached.file_size == upscaler_entry.file_size && (!time_ec && cached.last_modified == upscaler_entry.last_modified); }); - upscaler_entry.image_upscale_factor = previous != previous_cache.end() - ? previous->image_upscale_factor - : sd_upscaler_probe_scale(upscaler_entry.fullpath.c_str()); - if (upscaler_entry.image_upscale_factor > 0) { - upscaler_entry.scale = upscaler_entry.image_upscale_factor; - upscaler_entry.model_name = "ESRGAN_" + std::to_string(upscaler_entry.scale) + "x"; - } + const int scale = previous != previous_cache.end() ? previous->scale : sd_upscaler_probe_scale(upscaler_entry.fullpath.c_str()); + upscaler_entry.scale = scale > 0 ? scale : 4; + upscaler_entry.model_name = "ESRGAN_" + std::to_string(upscaler_entry.scale) + "x"; new_cache.push_back(std::move(upscaler_entry)); it.increment(ec); diff --git a/examples/server/runtime.h b/examples/server/runtime.h index 51d6e8856f..40d6d4fb54 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -51,7 +51,6 @@ struct UpscalerEntry { std::string fullpath; std::string model_name; int scale = 4; - int image_upscale_factor = 0; uintmax_t file_size = 0; std::filesystem::file_time_type last_modified; }; @@ -140,7 +139,9 @@ bool assign_output_options(VidGenJobRequest& request, std::string& error_message); std::string video_mime_type(const std::string& output_format); bool runtime_supports_generation_mode(const ServerRuntime& runtime, SDMode mode); -void prepare_native_context(ServerModels& models, const SDSvrParams& params, const SDContextParams& config, bool startup = false); +bool has_current_model(const ServerRuntime& runtime); +void configure_server_file_access(ServerModels& models, const SDSvrParams& params, const SDContextParams& config); +bool generate_server_images(sd_ctx_t* ctx, ImgGenJobRequest& request, SDImageVec& results, std::string& error_message); std::string unsupported_generation_mode_error(SDMode mode); void refresh_lora_cache(ServerRuntime& rt); std::string get_lora_full_path(ServerRuntime& rt, const std::string& path); diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 64ae419bd4..5bb5aeca1b 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -210,11 +210,15 @@ SD_API sd_status_t sd_opt_unset(sd_opt_t* params, const char* key); // its own configuration; params may be freed immediately after the call returns. SD_API sd_status_t sd_ctx_create(const sd_ctx_opt_t* params, sd_ctx_t** ctx_out); SD_API void sd_ctx_free(sd_ctx_t* ctx); +// Borrows the context used for generation, or returns NULL if ctx is NULL. +// It shares component caches and can run scripts between generation calls. +// Its lifetime is tied to ctx. Do not pass it to sd_dgl_ctx_free(). +SD_API sd_dgl_ctx_t* sd_ctx_get_dgl_ctx(sd_ctx_t* ctx); +// Copies the new model configuration into an idle context. The execution +// settings, callbacks, and DGL component cache belong to the existing context. +SD_API sd_status_t sd_ctx_set_model_options(sd_ctx_t* ctx, const sd_ctx_opt_t* params); // Applies to generated programs and model probing. Register or clear while idle. SD_API sd_status_t sd_ctx_set_file_access_callback(sd_ctx_t* ctx, sd_dgl_file_access_cb_t callback, void* userdata); -// Probe the model and prepare its configured components without generating. -// Optional for lazy C API use; call after setting file permissions to validate loading. -SD_API sd_status_t sd_ctx_prepare(sd_ctx_t* ctx); SD_API sd_status_t sd_generate_image(sd_ctx_t* ctx, const sd_img_gen_opt_t* params, sd_result_t** result_out); SD_API sd_status_t sd_generate_video(sd_ctx_t* ctx, const sd_vid_gen_opt_t* params, sd_result_t** result_out); diff --git a/src/api/api.cpp b/src/api/api.cpp index 7eba378ff0..b6bb214737 100644 --- a/src/api/api.cpp +++ b/src/api/api.cpp @@ -112,17 +112,24 @@ void sd_ctx_free(sd_ctx_t* context) { delete context; } -sd_status_t sd_ctx_prepare(sd_ctx_t* context) { +sd_dgl_ctx_t* sd_ctx_get_dgl_ctx(sd_ctx_t* context) { + return context && context->engine ? &context->engine->execution : nullptr; +} + +sd_status_t sd_ctx_set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* options) { return sd::api::call([&] { if (!context || !context->engine) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context is required"); auto& engine = *context->engine; - sd::api::GenerationRun preparation(engine); - sd::FileAccessScope access(engine.execution.file_access); - sd::api::execute_program(engine, sd::api::component_program(engine)); + std::unique_lock lock(engine.mutex, std::try_to_lock); + if (!lock.owns_lock() || engine.executing) + return sd::api::error(SD_STATUS_BUSY, nullptr, "context is busy"); + std::unique_lock execution_lock(engine.execution.mutex, std::try_to_lock); + if (!execution_lock.owns_lock() || engine.execution.active_run) + return sd::api::error(SD_STATUS_BUSY, nullptr, "DGL context is busy"); + engine.model = sd::api::GenerationModel(sd::api::copy_options(options), sd::api::Context); return SD_STATUS_OK; - }, - SD_STATUS_LOAD_FAILED); + }); } void sd_cancel_generation(sd_ctx_t* context, enum sd_cancel_mode_t mode) { @@ -144,14 +151,14 @@ static const ModelDefinition* context_definition(const sd_ctx_t* context) { sd::api::call([&] { if (!context || !context->engine) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context is required"); - auto& engine = *context->engine; - const auto family = engine.family.load(); + auto& engine = *context->engine; + std::lock_guard lock(engine.mutex); + const auto family = engine.model.family; if (family != VERSION_COUNT) { definition = find_model_definition(family); } else { - std::lock_guard lock(engine.mutex); - sd::FileAccessScope access(engine.execution.file_access); - definition = &engine.model_definition(); + sd::FileAccessScope access(engine.file_access); + definition = &engine.model.definition(engine); } return SD_STATUS_OK; }, @@ -182,7 +189,7 @@ sd_status_t sd_ctx_set_file_access_callback(sd_ctx_t* context, sd_dgl_file_acces std::unique_lock lock(engine.mutex, std::try_to_lock); if (!lock.owns_lock() || engine.executing) return sd::api::error(SD_STATUS_BUSY, nullptr, "context is busy"); - engine.execution.file_access = {callback, data}; + engine.file_access = {callback, data}; return SD_STATUS_OK; }); } diff --git a/src/api/generation.cpp b/src/api/generation.cpp index 51a3630849..629b678e71 100644 --- a/src/api/generation.cpp +++ b/src/api/generation.cpp @@ -18,12 +18,16 @@ #include "name_conversion.h" namespace sd::api { - GenerationContext::GenerationContext(const sd_opt_t* source, Operation purpose) - : options(copy_options(source)), execution(true) { + GenerationModel::GenerationModel(std::shared_ptr source, Operation purpose) + : options(std::move(source)) { const auto status = resolve(options.get(), purpose, config); if (status != SD_STATUS_OK) throw dgl::Error(status, sd_get_last_error()); - const auto& settings = config.context; + } + + GenerationContext::GenerationContext(const sd_opt_t* source, Operation purpose) + : model(copy_options(source), purpose) { + const auto& settings = model.config.context; execution.set("n_threads", std::to_string(settings.n_threads)); execution.set("conditioning_cache_size", std::to_string(settings.conditioning_cache_size)); for (const auto& [key, enabled] : std::map{ @@ -46,9 +50,9 @@ namespace sd::api { return false; } - const ModelDefinition& GenerationContext::model_definition() { - std::lock_guard lock(mutex); - check_cancelled(); + const ModelDefinition& GenerationModel::definition(GenerationContext& context) { + std::lock_guard lock(context.mutex); + context.check_cancelled(); const auto& settings = config.context; const auto* path = settings.diffusion_model_path && *settings.diffusion_model_path ? settings.diffusion_model_path : settings.model_path; if (!path || !*path) @@ -107,7 +111,7 @@ namespace sd::api { embedded_audio_vae = settings.vae_path; } } - check_cancelled(); + context.check_cancelled(); family = detected; probe_dependencies = std::move(dependencies); LOG_INFO("Detected model family: %s (%s)", sd_version_name(family), std::filesystem::u8path(path).filename().u8string().c_str()); @@ -135,13 +139,17 @@ namespace sd::api { std::unique_lock lock(context_.mutex, std::try_to_lock); if (!lock.owns_lock() || context_.executing) throw dgl::Error(SD_STATUS_BUSY, "context is busy"); - context_.executing = true; + std::unique_lock execution_lock(context_.execution.mutex, std::try_to_lock); + if (!execution_lock.owns_lock() || context_.execution.active_run) + throw dgl::Error(SD_STATUS_BUSY, "DGL context is busy"); + context_.execution.generating = true; + context_.executing = true; } GenerationRun::~GenerationRun() { std::lock_guard lock(context_.mutex); - context_.active_run = nullptr; - context_.execution.active_run = nullptr; + std::lock_guard execution_lock(context_.execution.mutex); + context_.execution.generating = false; context_.cancellation.store(SD_CANCEL_RESET); context_.executing = false; } @@ -156,7 +164,7 @@ namespace sd::api { dgl::Value execute_program(GenerationContext& context, const GenerationProgram& program, const dgl::Graph* compiled) { context.check_cancelled(); - FileAccessScope access(context.execution.file_access); + FileAccessScope access(context.file_access); dgl::Graph graph; if (!compiled) { graph = dgl::compile(program.source, dgl::operations(), !program.inputs.empty()); @@ -172,6 +180,7 @@ namespace sd::api { dgl::RunEvents& events; ~ActiveRun() { std::lock_guard lock(context.mutex); + std::lock_guard execution_lock(context.execution.mutex); context.sample_pass += events.preview_info().sample_pass; context.active_run = nullptr; context.execution.active_run = nullptr; @@ -179,6 +188,7 @@ namespace sd::api { } active{context, events}; { std::lock_guard lock(context.mutex); + std::lock_guard execution_lock(context.execution.mutex); context.active_run = &events; context.execution.active_run = &events; if (context.cancellation.load() == SD_CANCEL_ALL) @@ -199,7 +209,7 @@ namespace sd::api { sd_status_t generate_images(GenerationContext& context, const sd_img_gen_opt_t* options, sd_result_t** out) { GenerationRun request(context); - FileAccessScope access(context.execution.file_access); + FileAccessScope access(context.file_access); auto snapshot = copy_options(options); OptConfig config; const auto status = resolve(snapshot.get(), Image, config); @@ -223,7 +233,7 @@ namespace sd::api { } sd_status_t generate_video(GenerationContext& context, const sd_vid_gen_opt_t* options, sd_result_t** out) { GenerationRun request(context); - FileAccessScope access(context.execution.file_access); + FileAccessScope access(context.file_access); auto snapshot = copy_options(options); OptConfig config; const auto status = resolve(snapshot.get(), Video, config); diff --git a/src/api/generation.h b/src/api/generation.h index cb1cc8f057..287dad3801 100644 --- a/src/api/generation.h +++ b/src/api/generation.h @@ -13,10 +13,28 @@ #include "model_definition.h" namespace sd::api { - struct GenerationContext { + struct GenerationContext; + + struct GenerationModel { std::shared_ptr options; OptConfig config; - dgl::Context execution; + SDVersion family = VERSION_COUNT; + prediction_t default_prediction = PREDICTION_COUNT; + bool wan_image_condition = false; + bool wan_vision_condition = false; + bool wan_end_vision = false; + bool wan_vace = false; + std::string embedded_audio_vae; + ModelLoader::Dependencies probe_dependencies; + + GenerationModel(std::shared_ptr source, Operation purpose); + const ModelDefinition& definition(GenerationContext& context); + }; + + struct GenerationContext { + GenerationModel model; + sd_dgl_ctx_t execution; + FileAccessPolicy file_access; std::recursive_mutex mutex; bool executing = false; std::atomic cancellation{SD_CANCEL_RESET}; @@ -26,17 +44,8 @@ namespace sd::api { sd_prompt_image_cb_t prompt_image = nullptr; void* prompt_image_data = nullptr; int sample_pass = 0; - std::atomic family{VERSION_COUNT}; - prediction_t default_prediction = PREDICTION_COUNT; - bool wan_image_condition = false; - bool wan_vision_condition = false; - bool wan_end_vision = false; - bool wan_vace = false; - std::string embedded_audio_vae; - ModelLoader::Dependencies probe_dependencies; GenerationContext(const sd_opt_t* source, Operation purpose); - const ModelDefinition& model_definition(); void check_cancelled() const; }; @@ -56,7 +65,6 @@ namespace sd::api { }; dgl::Value execute_program(GenerationContext& context, const GenerationProgram& program, const dgl::Graph* compiled = nullptr); - GenerationProgram component_program(GenerationContext& context); GenerationProgram image_program(GenerationContext& context, const ImageConfig& image, const sd_opt_t* explicit_options, int64_t seed); GenerationProgram video_program(GenerationContext& context, const VideoConfig& video, const sd_opt_t* explicit_options, int64_t seed); sd_status_t generate_images(GenerationContext& context, const sd_img_gen_opt_t* options, sd_result_t** result); diff --git a/src/api/generation_hires.cpp b/src/api/generation_hires.cpp index 7d43f759f8..0e73478d40 100644 --- a/src/api/generation_hires.cpp +++ b/src/api/generation_hires.cpp @@ -29,7 +29,7 @@ namespace sd::api { throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "video hires requires a latent interpolation mode or a latent upscaler model"); if (model && text(hires.model_path).empty()) throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "hires model upscaling requires hires.model_path"); - const auto& settings = request.context.config.context; + const auto& settings = request.context.model.config.context; const auto vae_version = request.definition.traits.vae_format_override && request.fields.at("vae_loader") != "load_tae" ? sd::vae::version_for_format(settings.vae_format, version) : version; diff --git a/src/api/generation_image.cpp b/src/api/generation_image.cpp index a5168ba8b4..8d2fa414a8 100644 --- a/src/api/generation_image.cpp +++ b/src/api/generation_image.cpp @@ -55,7 +55,7 @@ namespace sd::api { } static bool prompt_has_vision(const GenerationTemplate& request) { - const auto* vision_path = request.context.config.context.llm_vision_path; + const auto* vision_path = request.context.model.config.context.llm_vision_path; if (vision_path && *vision_path) return true; const auto path = request.values.at("text_path").get(); @@ -105,7 +105,7 @@ namespace sd::api { request.fields["negative_prompt_options"] += ", media = [" + pixels + "]"; } if (encode && !sd_version_is_unet_edit(version)) { - const bool increase = sd_version_is_flux2(version) || sd_version_is_flux3(version) || + const bool increase = sd_version_is_flux2(version) || sd_version_is_flux3(version) || sd_version_is_qwen_image(version) || sd_version_is_minimax_h3_image(version) || version == VERSION_FIBO2 || sd_version_is_krea2(version) || version == VERSION_ANIMA || sd_version_is_mage_flow(version) || moss_edit; @@ -159,7 +159,7 @@ namespace sd::api { } return; } - const auto& settings = request.context.config.context; + const auto& settings = request.context.model.config.context; if (!settings.control_net_path || !*settings.control_net_path) throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "control_image requires control_net_path"); request.values["control_path"] = settings.control_net_path; @@ -173,8 +173,8 @@ namespace sd::api { void prepare_image_program(GenerationTemplate& request) { const auto version = request.definition.version; - const auto& settings = request.context.config.context; - const auto prediction = settings.prediction == PREDICTION_COUNT ? request.context.default_prediction : settings.prediction; + const auto& settings = request.context.model.config.context; + const auto prediction = settings.prediction == PREDICTION_COUNT ? request.context.model.default_prediction : settings.prediction; const bool inpaint = sd_version_is_inpaint(version); const bool mask = bound_tensor(request.options, "mask_image"); const bool refs = request.image.ref_images_count > 0; diff --git a/src/api/generation_program.cpp b/src/api/generation_program.cpp index 92b69a4215..9a1056d064 100644 --- a/src/api/generation_program.cpp +++ b/src/api/generation_program.cpp @@ -200,45 +200,19 @@ namespace sd::api { {"vae_options", arguments(vae_options)}}}; } - GenerationProgram component_program(GenerationContext& context) { - const auto& definition = context.model_definition(); - const auto& settings = context.config.context; - if (definition.version == VERSION_ESRGAN || definition.version == VERSION_SEEDVR2 || definition.version == VERSION_RELAY_VSR) - throw dgl::Error(SD_STATUS_UNSUPPORTED, "this model requires a dedicated DGL workflow"); - auto components = component_bindings(settings, definition); - nlohmann::json flags; - const auto optional_component = [&](const char* name, const std::string& path, SDBackendModule module) { - flags[name] = !path.empty(); - if (!path.empty()) { - components.values[std::string(name) + "_path"] = path; - components.fields[std::string(name) + "_options"] = arguments(loader_options(settings, module, definition)); - } - }; - optional_component("high_model", text(settings.high_noise_diffusion_model_path), SDBackendModule::DIFFUSION); - optional_component("negative_model", sd_version_is_ideogram4(definition.version) ? text(settings.uncond_diffusion_model_path) : "", SDBackendModule::DIFFUSION); - optional_component("control", text(settings.control_net_path), SDBackendModule::CONTROL_NET); - optional_component("vision", text(settings.clip_vision_path), SDBackendModule::TE); - optional_component("audio_encoder", text(settings.audio_encoder_path), SDBackendModule::TE); - optional_component("audio_vae", text(settings.audio_vae_path).empty() ? context.embedded_audio_vae : text(settings.audio_vae_path), SDBackendModule::VAE); - optional_component("preview", !components.tae && settings.tae_preview_only ? text(settings.taesd_path) : "", SDBackendModule::VAE); - nlohmann::json parameters = components.fields; - parameters["variables"] = variables(components.values); - parameters["flags"] = std::move(flags); - return {render_template("load_components", parameters), {}}; - } - static GenerationProgram generation_program(GenerationContext& context, const ImageConfig& image, const sd_opt_t* explicit_options, int64_t seed, const VideoConfig* video) { - const auto& definition = context.model_definition(); - const auto& settings = context.config.context; + auto& model = context.model; + const auto& definition = model.definition(context); + const auto& settings = model.config.context; if (definition.traits.supports_video_generation != bool(video) || definition.version == VERSION_ESRGAN || definition.version == VERSION_SEEDVR2 || definition.version == VERSION_RELAY_VSR) throw dgl::Error(SD_STATUS_UNSUPPORTED, "this model requires a video or dedicated DGL workflow"); const auto components = component_bindings(settings, definition); const auto method = image.sample_params.sample_method == SAMPLE_METHOD_COUNT ? definition.sampling.default_sample_method : image.sample_params.sample_method; auto scheduler = image.sample_params.scheduler; if (scheduler == SCHEDULER_COUNT) { - scheduler = (settings.prediction == EDM_V_PRED || (settings.prediction == PREDICTION_COUNT && context.default_prediction == EDM_V_PRED)) ? EXPONENTIAL_SCHEDULER : method == LCM_SAMPLE_METHOD || method == TCD_SAMPLE_METHOD ? LCM_SCHEDULER - : method == DDIM_TRAILING_SAMPLE_METHOD ? SIMPLE_SCHEDULER - : definition.sampling.default_scheduler; + scheduler = (settings.prediction == EDM_V_PRED || (settings.prediction == PREDICTION_COUNT && model.default_prediction == EDM_V_PRED)) ? EXPONENTIAL_SCHEDULER : method == LCM_SAMPLE_METHOD || method == TCD_SAMPLE_METHOD ? LCM_SCHEDULER + : method == DDIM_TRAILING_SAMPLE_METHOD ? SIMPLE_SCHEDULER + : definition.sampling.default_scheduler; } const auto predictor_options = arguments({{"prediction", settings.prediction == PREDICTION_COUNT ? "auto" : sd_prediction_name(settings.prediction)}, {"guidance", image.sample_params.guidance.distilled_guidance}, diff --git a/src/api/generation_prompt.cpp b/src/api/generation_prompt.cpp index 5481751e36..991e0a60ed 100644 --- a/src/api/generation_prompt.cpp +++ b/src/api/generation_prompt.cpp @@ -12,7 +12,7 @@ namespace sd::api { } static void prepare_textual_inversion(GenerationTemplate& request) { - const auto& config = request.context.config.context; + const auto& config = request.context.model.config.context; if (!config.embedding_count) return; std::vector> embeddings; diff --git a/src/api/generation_video.cpp b/src/api/generation_video.cpp index ef9c894ce3..8e4a963d55 100644 --- a/src/api/generation_video.cpp +++ b/src/api/generation_video.cpp @@ -26,7 +26,7 @@ namespace sd::api { request.flags["driving_audio"] = !tracks.empty(); if (tracks.empty()) return; - const auto& config = request.context.config.context; + const auto& config = request.context.model.config.context; if (!config.audio_encoder_path || !*config.audio_encoder_path) throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "Wan S2V audio requires audio_encoder_path"); bind_tensor(request.program, "driving_audio", tracks[0].data); @@ -39,10 +39,10 @@ namespace sd::api { static void audiovisual(GenerationTemplate& request) { const bool h3 = sd_version_is_minimax_h3(request.definition.version); - const auto& settings = request.context.config.context; + const auto& settings = request.context.model.config.context; auto path = text(settings.audio_vae_path); if (path.empty()) - path = request.context.embedded_audio_vae; + path = request.context.model.embedded_audio_vae; request.flags["decode_audio"] = !path.empty(); if (!path.empty()) request.values["audio_vae_path"] = path; @@ -59,7 +59,7 @@ namespace sd::api { } static void dual_expert(GenerationTemplate& request) { - const auto& settings = request.context.config.context; + const auto& settings = request.context.model.config.context; request.flags["dual"] = !text(settings.high_noise_diffusion_model_path).empty(); if (!request.flags.at("dual").get()) return; @@ -95,10 +95,10 @@ namespace sd::api { void prepare_video_program(GenerationTemplate& request) { const auto version = request.definition.version; - const auto& settings = request.context.config.context; + const auto& settings = request.context.model.config.context; const bool first = keyframe(request, "init_image", "first_frame"); const bool last = keyframe(request, "end_image", "last_frame"); - const bool vace = request.context.wan_vace; + const bool vace = request.context.model.wan_vace; const bool s2v = version == VERSION_WAN2_2_S2V; const bool frozen = (version == VERSION_WAN2_2_TI2V || sd_version_is_lingbot_video(version)) && (first || last); const bool ltx = sd_version_is_ltxav(version); @@ -109,8 +109,8 @@ namespace sd::api { throw dgl::Error(SD_STATUS_UNSUPPORTED, "reference audio requires MiniMax-H3 or Wan2.2 S2V"); if (s2v && last) throw dgl::Error(SD_STATUS_UNSUPPORTED, "Wan2.2 S2V does not support an end image"); - const bool image_condition = !vace && !s2v && request.context.wan_image_condition; - request.flags = {{"first", first}, {"last", last}, {"conditioned", first || last}, {"vace", vace}, {"vace_reference", vace && first}, {"s2v_reference", s2v && first}, {"driving_audio", false}, {"image_condition", image_condition}, {"vision", image_condition && request.context.wan_vision_condition}, {"end_vision", request.context.wan_end_vision}, {"frozen", frozen}, {"hunyuan", sd_version_is_hunyuan_video(version) && (first || last)}, {"controls", false}, {"dual", false}, {"custom_sigmas", request.image.sample_params.custom_sigmas_count > 0}}; + const bool image_condition = !vace && !s2v && request.context.model.wan_image_condition; + request.flags = {{"first", first}, {"last", last}, {"conditioned", first || last}, {"vace", vace}, {"vace_reference", vace && first}, {"s2v_reference", s2v && first}, {"driving_audio", false}, {"image_condition", image_condition}, {"vision", image_condition && request.context.model.wan_vision_condition}, {"end_vision", request.context.model.wan_end_vision}, {"frozen", frozen}, {"hunyuan", sd_version_is_hunyuan_video(version) && (first || last)}, {"controls", false}, {"dual", false}, {"custom_sigmas", request.image.sample_params.custom_sigmas_count > 0}}; request.fields["entry"] = ltx ? "video_ltx" : h3 ? "video_h3" : "video_wan"; if (image_condition || request.flags.at("hunyuan").get()) diff --git a/src/api/templates/README.md b/src/api/templates/README.md index 82f7b4ffaf..3b8e0d5ae2 100644 --- a/src/api/templates/README.md +++ b/src/api/templates/README.md @@ -7,7 +7,6 @@ during configuration. | Template | Flow | | --- | --- | -| [load_components.dgl](load_components.dgl) | Prepare and validate configured model components without generation | | [image.dgl](image.dgl) | Text-to-image and ordinary image-to-image | | [image_inpaint.dgl](image_inpaint.dgl) | Masked sampling and native inpaint conditioning | | [image_edit.dgl](image_edit.dgl) | Native reference-image editing | diff --git a/src/api/templates/load_components.dgl b/src/api/templates/load_components.dgl deleted file mode 100644 index 8c41c7f16e..0000000000 --- a/src/api/templates/load_components.dgl +++ /dev/null @@ -1,33 +0,0 @@ -# version: 0.0.0 - -var { -{{variables}} -} - -fn main() { - model = {{model_loader}}(model_path{{model_options}}) - text = load_text_encoder(text_path{{text_options}}) - vae = {{vae_loader}}(vae_path{{vae_options}}) -{% if flags.high_model %} - load_dit(high_model_path{{high_model_options}}) -{% endif %} -{% if flags.negative_model %} - load_dit(negative_model_path{{negative_model_options}}) -{% endif %} -{% if flags.control %} - controlnet::load(control_path{{control_options}}) -{% endif %} -{% if flags.vision %} - load_vision_encoder(vision_path{{vision_options}}) -{% endif %} -{% if flags.audio_encoder %} - load_audio_encoder(audio_encoder_path{{audio_encoder_options}}) -{% endif %} -{% if flags.audio_vae %} - load_audio_vae(audio_vae_path{{audio_vae_options}}) -{% endif %} -{% if flags.preview %} - load_tae(preview_path, decode_only = true{{preview_options}}) -{% endif %} - return {model = model, text = text, vae = vae} -} diff --git a/src/api/upscaler.cpp b/src/api/upscaler.cpp index d2c5478bc2..2e2aa051e0 100644 --- a/src/api/upscaler.cpp +++ b/src/api/upscaler.cpp @@ -17,8 +17,8 @@ struct sd_upscaler { }; namespace sd::api { - static std::string upscale_source(const GenerationContext& context, int repeats) { - const auto& settings = context.config.context; + static std::string upscale_source(const OptConfig& config, int repeats) { + const auto& settings = config.context; std::string options; for (const auto& [name, spec] : std::map{{"backend", settings.backend}, {"params_backend", settings.params_backend}}) { if (!spec || !*spec) @@ -29,10 +29,10 @@ namespace sd::api { throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, error); options += ", " + name + " = " + nlohmann::json(assignment.get(SDBackendModule::UPSCALER)).dump(); } - if (context.config.post.conv_direct) + if (config.post.conv_direct) options += ", direct = true"; return render_template("upscale", {{"model_path", nlohmann::json(settings.model_path).dump()}, - {"tile_size", std::to_string(context.config.post.tile_size)}, + {"tile_size", std::to_string(config.post.tile_size)}, {"repeats", std::to_string(repeats)}, {"loader_options", options}}); } @@ -45,7 +45,7 @@ sd_status_t sd_upscaler_create(const sd_upscaler_opt_t* options, sd_upscaler_t** if (!out) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "out is required"); auto result = std::make_unique(options); - result->source = sd::api::upscale_source(result->context, 1); + result->source = sd::api::upscale_source(result->context.model.config, 1); result->program = sd::dgl::compile(result->source, sd::dgl::operations(), true); const auto& resource = result->program.resources.at(0); auto arguments = resource.arguments; @@ -109,7 +109,7 @@ sd_status_t sd_upscale(sd_upscaler_t* upscaler, const sd_upscale_opt_t* options, } const auto* input = sd::api::bound_tensor(snapshot.get(), "image"); sd::api::GenerationProgram program; - program.source = config.post.repeats == 1 ? upscaler->source : sd::api::upscale_source(upscaler->context, config.post.repeats); + program.source = config.post.repeats == 1 ? upscaler->source : sd::api::upscale_source(upscaler->context.model.config, config.post.repeats); program.inputs.emplace("input_image", sd::dgl::Value::object(std::shared_ptr(sd_tensor_retain(input), sd_tensor_free))); auto value = sd::api::execute_program(upscaler->context, program, config.post.repeats == 1 ? &upscaler->program : nullptr); auto result = std::make_unique(); diff --git a/src/dgl/bindings/predictor.cpp b/src/dgl/bindings/predictor.cpp index 5e20df0852..49cf20e2f7 100644 --- a/src/dgl/bindings/predictor.cpp +++ b/src/dgl/bindings/predictor.cpp @@ -139,10 +139,10 @@ namespace sd::dgl { const auto ref_rope_anchor = get_string(args, "ref_rope_anchor"); if (ref_rope_anchor != "default" && engine.version() != VERSION_MOSS_IMAGE) throw std::runtime_error("reference RoPE anchoring is not configurable for this model"); - output.options.ref_rope_anchor = ref_rope_anchor == "image_start" ? Rope::RefRoPEAnchor::IMAGE_START - : ref_rope_anchor == "text_start" ? Rope::RefRoPEAnchor::TEXT_START - : Rope::RefRoPEAnchor::MODEL_DEFAULT; - output.options.guidance = float(get_number(args, "guidance")); + output.options.ref_rope_anchor = ref_rope_anchor == "image_start" ? Rope::RefRoPEAnchor::IMAGE_START + : ref_rope_anchor == "text_start" ? Rope::RefRoPEAnchor::TEXT_START + : Rope::RefRoPEAnchor::MODEL_DEFAULT; + output.options.guidance = float(get_number(args, "guidance")); bind_predictor_options(output, args); const auto& condition = args.at("condition").fields; if (const auto controls = condition.find("controls"); controls != condition.end()) { diff --git a/src/dgl/context.cpp b/src/dgl/context.cpp index 33da3c2fa5..6e5843bab9 100644 --- a/src/dgl/context.cpp +++ b/src/dgl/context.cpp @@ -13,6 +13,7 @@ #include "dgl/model_value.h" #include "dgl/models/component_sources.h" #include "dgl/models/lora.h" +#include "dgl/run_events.h" namespace sd::dgl { @@ -203,6 +204,8 @@ namespace sd::dgl { return std::move(*value); } const bool model = is_model_kind(kind); + if (model) + report_run_progress("loading"); ResourceLoadRequest request{*this, model ? identity.first : ""}; auto value = prepared.load(request); auto dependencies = model ? model_from_value(value).dependencies() : ModelLoader::Dependencies{}; diff --git a/src/dgl/context.h b/src/dgl/context.h index 30ea1ee7e6..90fbfc76b8 100644 --- a/src/dgl/context.h +++ b/src/dgl/context.h @@ -33,6 +33,7 @@ namespace sd::dgl { std::mutex mutex; RunEvents* active_run = nullptr; + bool generating = false; RunCallbacks callbacks; FileAccessPolicy file_access; std::shared_ptr backends = std::make_shared(); @@ -73,4 +74,8 @@ namespace sd::dgl { } // namespace sd::dgl +struct sd_dgl_ctx_t : sd::dgl::Context { + using Context::Context; +}; + #endif // __SD_DGL_CONTEXT_H__ diff --git a/src/dgl/dgl.cpp b/src/dgl/dgl.cpp index ee8aef7d23..5f5b0a30d1 100644 --- a/src/dgl/dgl.cpp +++ b/src/dgl/dgl.cpp @@ -10,10 +10,6 @@ #include "graph.h" #include "result.h" -struct sd_dgl_ctx_t : sd::dgl::Context { - using Context::Context; -}; - namespace { using namespace sd::dgl; @@ -35,7 +31,7 @@ namespace { if (!ctx) throw Error(SD_STATUS_INVALID_ARGUMENT, "context is required"); std::unique_lock lock(ctx->mutex, std::try_to_lock); - if (!lock.owns_lock() || ctx->active_run) + if (!lock.owns_lock() || ctx->active_run || ctx->generating) throw Error(SD_STATUS_BUSY, "DGL context is busy"); return lock; } diff --git a/src/dgl/models/diffusion_prediction.h b/src/dgl/models/diffusion_prediction.h index 94bc6d1e64..8535c9dd7d 100644 --- a/src/dgl/models/diffusion_prediction.h +++ b/src/dgl/models/diffusion_prediction.h @@ -34,15 +34,15 @@ namespace sd::dgl::models { struct DiffusionPredictionOptions { sd::Tensor vace_context, audio_embedding, video_positions; std::vector skip_layers; - float guidance = 3.5f; - float vace_strength = 1.f; - float fps = 24.f; - float video_sigma_shift = 12.f; - float audio_sigma_shift = 3.f; - int audio_length = 0; - Rope::RefIndexMode ref_index_mode = Rope::RefIndexMode::FIXED; + float guidance = 3.5f; + float vace_strength = 1.f; + float fps = 24.f; + float video_sigma_shift = 12.f; + float audio_sigma_shift = 3.f; + int audio_length = 0; + Rope::RefIndexMode ref_index_mode = Rope::RefIndexMode::FIXED; Rope::RefRoPEAnchor ref_rope_anchor = Rope::RefRoPEAnchor::MODEL_DEFAULT; - bool force_ref_timestep_zero = false; + bool force_ref_timestep_zero = false; std::function transform; }; diff --git a/src/dgl/models/lora.cpp b/src/dgl/models/lora.cpp index 5355095ce9..5eeddb96ae 100644 --- a/src/dgl/models/lora.cpp +++ b/src/dgl/models/lora.cpp @@ -8,8 +8,7 @@ namespace sd::dgl::models { - lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, - SDBackendManager& backends, SDBackendModule module, bool row_split) { + lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, SDBackendManager& backends, SDBackendModule module, bool row_split) { if (mode != LORA_APPLY_AUTO) return mode; // Offloading can signal limited compute memory, so avoid merged copies in auto mode. diff --git a/src/dgl/models/lora.h b/src/dgl/models/lora.h index 40b5a86f4c..b4709c2132 100644 --- a/src/dgl/models/lora.h +++ b/src/dgl/models/lora.h @@ -29,8 +29,7 @@ namespace sd::dgl::models { lora_apply_mode_t mode = LORA_APPLY_AUTO; }; - lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, - SDBackendManager& backends, SDBackendModule module, bool row_split = false); + lora_apply_mode_t resolve_lora_mode(lora_apply_mode_t mode, const ModelLoader& loader, SDBackendManager& backends, SDBackendModule module, bool row_split = false); class LoraExecution { std::vector> models_; diff --git a/src/dgl/models/model_runtime.cpp b/src/dgl/models/model_runtime.cpp index 177308546f..d468ee0815 100644 --- a/src/dgl/models/model_runtime.cpp +++ b/src/dgl/models/model_runtime.cpp @@ -413,7 +413,7 @@ namespace sd::dgl::models { const auto& loader = model_.model_weights->loader(); const bool row_split = mode != LORA_APPLY_AT_RUNTIME && split_active(SDSplitMode::ROW); if (mode == LORA_APPLY_IMMEDIATELY) { - const auto& tensors = loader.get_tensor_storage_map(); + const auto& tensors = loader.get_tensor_storage_map(); apply_lora_immediately_ = !row_split && std::none_of(tensors.begin(), tensors.end(), [](const auto& entry) { return entry.second.is_int8_tensorwise || entry.second.w4_convrot_kind; diff --git a/src/dgl/ops/tensor.cpp b/src/dgl/ops/tensor.cpp index ff18e8f8fd..cbe9a12ec0 100644 --- a/src/dgl/ops/tensor.cpp +++ b/src/dgl/ops/tensor.cpp @@ -164,7 +164,7 @@ namespace sd::dgl::ops { } std::shared_ptr pool_tensor(const sd_tensor_t& source, const std::vector& axes, const std::vector& kernel, const std::vector& stride, const std::vector& before, const std::vector& after, std::optional pad_value, bool maximum) { - const auto* input = &source; + const auto* input = &source; const auto spatial = spatial_axes(source, axes); const auto x = spatial.first, y = spatial.second; if (kernel.size() != 2 || stride.size() != 2 || before.size() != 2 || after.size() != 2) diff --git a/src/model/diffusion/moss_image.hpp b/src/model/diffusion/moss_image.hpp index 3e87433394..c039f100dd 100644 --- a/src/model/diffusion/moss_image.hpp +++ b/src/model/diffusion/moss_image.hpp @@ -279,7 +279,7 @@ namespace MOSSImage { tokens += ref.shape()[1] * ref.shape()[0]; } } - auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() { + auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() { Rope::Embedding embedding; embedding.ids.reserve(tokens); auto append_image = [&](int64_t height, int64_t width, float ref_index, float text_position) { From d1d665f631b71c6918696c3486ac0a44645b769b Mon Sep 17 00:00:00 2001 From: leejet Date: Mon, 23 Nov 2026 23:57:39 +0800 Subject: [PATCH 2/2] fix: validate model switches and block replacement during probes --- docs/guides/c_api.md | 4 ++++ examples/server/api.md | 8 +++++-- examples/server/async_jobs.cpp | 4 ++-- examples/server/model_catalog.cpp | 20 ++++++++++++------ examples/server/model_catalog.h | 4 ++-- examples/server/routes_sdcpp.cpp | 2 +- include/stable-diffusion.h | 5 +++++ src/api/api.cpp | 35 +++++++++++++++++++++++-------- src/api/generation.cpp | 14 ++++++++++++- src/api/generation.h | 3 +++ src/api/generation_program.cpp | 2 +- 11 files changed, 77 insertions(+), 24 deletions(-) diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index c359b695da..fe1f836960 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -70,6 +70,10 @@ queries can probe the model family and reuse the detected type. Use `sd_ctx_set_model_options()` on an idle context to replace its model configuration. It copies the options and resets model detection. Later `sd_generate_image()` and `sd_generate_video()` calls use the new configuration. +Use `sd_ctx_set_model_options_for_generation()` to probe the candidate against +`SD_RESULT_IMAGE` or `SD_RESULT_VIDEO` before applying it. A failed check +preserves the current configuration. Model setters return `SD_STATUS_BUSY` +while model probing is in progress, including from file-access callbacks. The execution settings and component cache continue to serve generation and the DGL context borrowed through `sd_ctx_get_dgl_ctx()`. The borrowed pointer stays valid until `sd_ctx_free()`. Run scripts and generation calls one at a time. Set diff --git a/examples/server/api.md b/examples/server/api.md index d23a98687e..1421d287f9 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -70,8 +70,12 @@ Current endpoints include: All three API families share the server's execution context and its component cache. The command-line model supplies the initial configuration. Native image -and video jobs can select a recipe and component files in the request. The worker -applies that selection to the shared context before generation. It remains the +and video jobs can select a recipe and component files in the request. Video +requests with an explicit recipe require that recipe to declare +`defaults.video_frames`. The worker probes the selected model family and checks +that it supports the requested mode before applying the selection. A probe or +mode check failure is reported on the job and preserves the current model. +An applied selection remains the current model for later requests that omit `model`, including A1111 and OpenAI requests. Each native job reports loading and generation progress through the job API. diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index 5f15d6a6a8..13ca2a4524 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -344,15 +344,15 @@ json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJo static bool prepare_native_job(ServerRuntime& runtime, AsyncGenerationJob& job, std::string& error_message) { if (job.cancel_requested.load()) return false; + const SDMode mode = job.kind == AsyncJobKind::VidGen ? VID_GEN : IMG_GEN; if (job.model) { auto model = std::move(job.model); - return set_current_model(runtime, std::move(*model), error_message); + return set_current_model(runtime, std::move(*model), mode, error_message); } auto body = std::move(job.request_body); if (job.model_revision == runtime.models->revision) return true; // An earlier queued job can change the model and its defaults before this job starts. - const SDMode mode = job.kind == AsyncJobKind::VidGen ? VID_GEN : IMG_GEN; if (!runtime_supports_generation_mode(runtime, mode)) { error_message = unsupported_generation_mode_error(mode); return false; diff --git a/examples/server/model_catalog.cpp b/examples/server/model_catalog.cpp index acf02b04e4..4d51541fc4 100644 --- a/examples/server/model_catalog.cpp +++ b/examples/server/model_catalog.cpp @@ -721,7 +721,7 @@ void initialize_server_models(ServerRuntime& runtime) { refresh_model_catalog(runtime); } -ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body) { +ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body, SDMode mode) { check_keys(body, {"recipe", "models"}); const auto recipe_id = body.at("recipe").get(); // `models` is optional; unselected slots may fall back to recipe defaults below. @@ -734,10 +734,13 @@ ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& if (found == models.recipes.end()) throw std::runtime_error("unknown recipe"); const auto& recipe = found->second; + const auto recipe_defaults = recipe.value("defaults", json::object()); + if (mode == VID_GEN && !recipe_defaults.contains("video_frames")) + throw std::runtime_error("selected recipe does not support vid_gen: " + recipe_id); auto context = models.base_context; auto defaults = models.base_defaults; apply_recipe_context(recipe.value("context", json::object()), context); - apply_recipe_defaults(recipe.value("defaults", json::object()), defaults); + apply_recipe_defaults(recipe_defaults, defaults); // Recipe-provided default models fill any slot the request did not select. // An explicit selection blocks the default for that slot, including an // empty string (a deliberate opt-out of the default). The tae/taesd pair @@ -809,15 +812,20 @@ ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& return {std::move(context), std::move(defaults), recipe, std::move(selection), std::move(options)}; } -bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, std::string& error_message) { +bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, SDMode mode, std::string& error_message) { auto& models = *runtime.models; std::unique_lock lock(models.model_mutex); if (models.current_recipe == selection.recipe && models.current_files == selection.files && std::all_of(std::begin(k_model_slots), std::end(k_model_slots), [&](const ModelSlot& slot) { return runtime.ctx_params->*slot.field == selection.context.*slot.field; - })) - return true; - if (sd_ctx_set_model_options(runtime.sd_ctx, selection.options.get()) != SD_STATUS_OK) { + })) { + if (runtime_supports_generation_mode(runtime, mode)) + return true; + error_message = unsupported_generation_mode_error(mode); + return false; + } + const auto kind = mode == VID_GEN ? SD_RESULT_VIDEO : SD_RESULT_IMAGE; + if (sd_ctx_set_model_options_for_generation(runtime.sd_ctx, selection.options.get(), kind) != SD_STATUS_OK) { error_message = sd_get_last_error(); return false; } diff --git a/examples/server/model_catalog.h b/examples/server/model_catalog.h index 488cc14a52..934b246796 100644 --- a/examples/server/model_catalog.h +++ b/examples/server/model_catalog.h @@ -67,9 +67,9 @@ void initialize_server_models(ServerRuntime& runtime); json resolve_recipe_features(const json& recipe); json model_generation_features(const ServerRuntime& runtime); -ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body); +ServerModelSelection resolve_model_selection(ServerRuntime& runtime, const json& body, SDMode mode); // The caller holds the generation mutex across the switch and generation. -bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, std::string& error_message); +bool set_current_model(ServerRuntime& runtime, ServerModelSelection&& selection, SDMode mode, std::string& error_message); void add_startup_model_sources(ServerFileAccess& policy, const SDContextParams& config); #endif diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index 587407aa9d..3d68e60769 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -464,7 +464,7 @@ static void submit_generation_job(ServerRuntime& runtime, const httplib::Request std::shared_lock model_lock(runtime.models->model_mutex, std::defer_lock); if (auto model = body.find("model"); model != body.end()) { try { - job->model = std::make_unique(resolve_model_selection(runtime, *model)); + job->model = std::make_unique(resolve_model_selection(runtime, *model, mode)); } catch (const std::exception& error) { res.status = 400; res.set_content(json({{"error", error.what()}, {"code", "invalid_model_config"}}).dump(), "application/json"); diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 5bb5aeca1b..f23fd8a875 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -216,6 +216,7 @@ SD_API void sd_ctx_free(sd_ctx_t* ctx); SD_API sd_dgl_ctx_t* sd_ctx_get_dgl_ctx(sd_ctx_t* ctx); // Copies the new model configuration into an idle context. The execution // settings, callbacks, and DGL component cache belong to the existing context. +// Returns SD_STATUS_BUSY during generation, DGL execution, or a model probe. SD_API sd_status_t sd_ctx_set_model_options(sd_ctx_t* ctx, const sd_ctx_opt_t* params); // Applies to generated programs and model probing. Register or clear while idle. SD_API sd_status_t sd_ctx_set_file_access_callback(sd_ctx_t* ctx, sd_dgl_file_access_cb_t callback, void* userdata); @@ -248,6 +249,10 @@ typedef enum { SD_RESULT_VIDEO = 2, } sd_result_kind_t; +// Probes the candidate model before replacing the current configuration. +// Accepts SD_RESULT_IMAGE or SD_RESULT_VIDEO and preserves the current model on failure. +SD_API sd_status_t sd_ctx_set_model_options_for_generation(sd_ctx_t* ctx, const sd_ctx_opt_t* params, sd_result_kind_t kind); + // Results own all outputs independently of ctx and params. Views are read-only and // borrowed until sd_result_free(). Retain a tensor to keep its data independently. // Media descriptors contain metadata and borrowed immutable tensor handles. diff --git a/src/api/api.cpp b/src/api/api.cpp index b6bb214737..054e6ef9fd 100644 --- a/src/api/api.cpp +++ b/src/api/api.cpp @@ -116,20 +116,36 @@ sd_dgl_ctx_t* sd_ctx_get_dgl_ctx(sd_ctx_t* context) { return context && context->engine ? &context->engine->execution : nullptr; } -sd_status_t sd_ctx_set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* options) { +static sd_status_t set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* options, sd_result_kind_t kind) { return sd::api::call([&] { if (!context || !context->engine) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "context is required"); auto& engine = *context->engine; std::unique_lock lock(engine.mutex, std::try_to_lock); - if (!lock.owns_lock() || engine.executing) + if (!lock.owns_lock()) return sd::api::error(SD_STATUS_BUSY, nullptr, "context is busy"); - std::unique_lock execution_lock(engine.execution.mutex, std::try_to_lock); - if (!execution_lock.owns_lock() || engine.execution.active_run) - return sd::api::error(SD_STATUS_BUSY, nullptr, "DGL context is busy"); - engine.model = sd::api::GenerationModel(sd::api::copy_options(options), sd::api::Context); + sd::api::GenerationRun replacement(engine); + sd::api::GenerationModel candidate(sd::api::copy_options(options), sd::api::Context); + if (kind != SD_RESULT_INVALID) { + sd::FileAccessScope access(engine.file_access); + const bool video = kind == SD_RESULT_VIDEO; + if (!sd::api::supports_generation(candidate.definition(engine), video)) + return sd::api::error(SD_STATUS_UNSUPPORTED, nullptr, video ? "selected model does not support vid_gen" : "selected model does not support img_gen"); + } + engine.model = std::move(candidate); + sd::api::clear_error(); return SD_STATUS_OK; - }); + }, kind == SD_RESULT_INVALID ? SD_STATUS_INVALID_ARGUMENT : SD_STATUS_LOAD_FAILED); +} + +sd_status_t sd_ctx_set_model_options(sd_ctx_t* context, const sd_ctx_opt_t* options) { + return set_model_options(context, options, SD_RESULT_INVALID); +} + +sd_status_t sd_ctx_set_model_options_for_generation(sd_ctx_t* context, const sd_ctx_opt_t* options, sd_result_kind_t kind) { + if (kind != SD_RESULT_IMAGE && kind != SD_RESULT_VIDEO) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, nullptr, "image or video result kind is required"); + return set_model_options(context, options, kind); } void sd_cancel_generation(sd_ctx_t* context, enum sd_cancel_mode_t mode) { @@ -160,6 +176,7 @@ static const ModelDefinition* context_definition(const sd_ctx_t* context) { sd::FileAccessScope access(engine.file_access); definition = &engine.model.definition(engine); } + sd::api::clear_error(); return SD_STATUS_OK; }, SD_STATUS_LOAD_FAILED); @@ -168,12 +185,12 @@ static const ModelDefinition* context_definition(const sd_ctx_t* context) { bool sd_ctx_supports_image_generation(const sd_ctx_t* context) { const auto* definition = context_definition(context); - return definition && !definition->traits.supports_video_generation && definition->version != VERSION_ESRGAN && definition->version != VERSION_SEEDVR2 && definition->version != VERSION_RELAY_VSR; + return definition && sd::api::supports_generation(*definition, false); } bool sd_ctx_supports_video_generation(const sd_ctx_t* context) { const auto* definition = context_definition(context); - return definition && definition->traits.supports_video_generation && definition->version != VERSION_SEEDVR2 && definition->version != VERSION_RELAY_VSR; + return definition && sd::api::supports_generation(*definition, true); } const char* sd_get_model_version_name(const sd_ctx_t* context) { diff --git a/src/api/generation.cpp b/src/api/generation.cpp index 629b678e71..ba267c531f 100644 --- a/src/api/generation.cpp +++ b/src/api/generation.cpp @@ -52,6 +52,13 @@ namespace sd::api { const ModelDefinition& GenerationModel::definition(GenerationContext& context) { std::lock_guard lock(context.mutex); + if (context.probing_model) + throw dgl::Error(SD_STATUS_BUSY, "model probe is in progress"); + context.probing_model = true; + struct ProbeGuard { + bool& probing; + ~ProbeGuard() { probing = false; } + } probe{context.probing_model}; context.check_cancelled(); const auto& settings = config.context; const auto* path = settings.diffusion_model_path && *settings.diffusion_model_path ? settings.diffusion_model_path : settings.model_path; @@ -129,6 +136,11 @@ namespace sd::api { return *definition; } + bool supports_generation(const ModelDefinition& definition, bool video) { + return definition.traits.supports_video_generation == video && definition.version != VERSION_ESRGAN && + definition.version != VERSION_SEEDVR2 && definition.version != VERSION_RELAY_VSR; + } + void GenerationContext::check_cancelled() const { if (cancellation.load(std::memory_order_relaxed) == SD_CANCEL_ALL) throw dgl::Error(SD_STATUS_CANCELLED, "generation cancelled"); @@ -137,7 +149,7 @@ namespace sd::api { GenerationRun::GenerationRun(GenerationContext& context) : context_(context) { std::unique_lock lock(context_.mutex, std::try_to_lock); - if (!lock.owns_lock() || context_.executing) + if (!lock.owns_lock() || context_.executing || context_.probing_model) throw dgl::Error(SD_STATUS_BUSY, "context is busy"); std::unique_lock execution_lock(context_.execution.mutex, std::try_to_lock); if (!execution_lock.owns_lock() || context_.execution.active_run) diff --git a/src/api/generation.h b/src/api/generation.h index 287dad3801..43632efa7a 100644 --- a/src/api/generation.h +++ b/src/api/generation.h @@ -37,6 +37,7 @@ namespace sd::api { FileAccessPolicy file_access; std::recursive_mutex mutex; bool executing = false; + bool probing_model = false; std::atomic cancellation{SD_CANCEL_RESET}; dgl::RunEvents* active_run = nullptr; sd_generation_progress_cb_t progress = nullptr; @@ -49,6 +50,8 @@ namespace sd::api { void check_cancelled() const; }; + bool supports_generation(const ModelDefinition& definition, bool video); + class GenerationRun { GenerationContext& context_; diff --git a/src/api/generation_program.cpp b/src/api/generation_program.cpp index 9a1056d064..f3b87be6f0 100644 --- a/src/api/generation_program.cpp +++ b/src/api/generation_program.cpp @@ -204,7 +204,7 @@ namespace sd::api { auto& model = context.model; const auto& definition = model.definition(context); const auto& settings = model.config.context; - if (definition.traits.supports_video_generation != bool(video) || definition.version == VERSION_ESRGAN || definition.version == VERSION_SEEDVR2 || definition.version == VERSION_RELAY_VSR) + if (!supports_generation(definition, video != nullptr)) throw dgl::Error(SD_STATUS_UNSUPPORTED, "this model requires a video or dedicated DGL workflow"); const auto components = component_bindings(settings, definition); const auto method = image.sample_params.sample_method == SAMPLE_METHOD_COUNT ? definition.sampling.default_sample_method : image.sample_params.sample_method;