diff --git a/docs/dgl/minimax_h3/minimax-h3-av-continuation.dgl b/docs/dgl/minimax_h3/minimax-h3-av-continuation.dgl new file mode 100644 index 0000000000..a474643bac --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-av-continuation.dgl @@ -0,0 +1,137 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — AV continuation: chain segment B onto segment A's +# tail latent (video head and audio head pinned as never-denoised), seamless +# multi-part video without pixel-frame anchoring drift. + +var { + model_path = "../models/diffusion_models/minimax_h3_fl2va-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + + output_a_path = "continuation-part-a.avi" + output_b_path = "continuation-part-b.avi" + latent_a_path = "continuation-part-a.npy" + + prompt_a = "A cute American Shorthair silver tabby kitten surfs on a tropical ocean wave, cinematic tracking shot, bright sunlight. Upbeat tropical surf-rock background music with cheerful drums and guitar." + prompt_b = "The same kitten rides the wave toward the beach at sunset, spray in golden light, smooth motion. The surf-rock music continues seamlessly." + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + fps = 24 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 + + # latent frames carried from segment A's tail; clamped to the previous + # segment's length, and the same count pins audio latent frames + pin_frames = 4 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +# Fold an audio-space pattern [T, 2, 32, 1] into the packed latent's tail +# channels exactly the way pack_av folds audio content, so mask zeros land on +# the same flat positions as the pinned audio frames. +fn audio_pattern_to_tail(audio_pattern, video_shape_tensor) { + count = tensor::numel(audio_pattern) + shape = tensor::shape(video_shape_tensor) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(audio_pattern, [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count], value = 1) + return tensor::reshape(padded, tail_shape) +} + +fn main() { + model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_zeros = tensor::zeros(audio_latent_shape(audio_vae, frames = frames, fps = fps)) + c_video = tensor::shape(video_base)[3] + t_video = tensor::shape(video_base)[2] + + # ---------- segment A ---------- + condition_a = encode_prompt(text, prompt_a, width = width, height = height) + base_a = pack_av(video_base, audio_zeros, audio_scale = audio_scale) + predict_a = predictor(model, condition_a, audio_length = tensor::shape(audio_zeros)[0]) + sigmas_a = make_sigmas(predict_a, latent = base_a, steps = steps, scheduler = scheduler) + rng = make_rng(rng_type, seed = seed) + start_a = add_noise(predict_a, base_a, tensor::randn_like(base_a, rng = rng), sigma = sigmas_a[0]) + latent_a = sample(start_a, sigmas_a, predict = predict_a, method = method, rng = rng) + + # save after sampling completes (the save point is the final latent, so a + # later refinement pass would naturally run before this line) + tensor::save(latent_a_path, latent_a) + + frames_a = vae_decode(vae, dit_to_vae_latents(vae, latent_a[:, :, :t_video, :c_video])) + audio_a = audio_vae_decode(audio_vae, unpack_audio(latent_a, channels = c_video, audio_shape = tensor::shape(audio_zeros), audio_scale = audio_scale)) + video::save(output_a_path, {frames = frames_a, fps_num = fps, fps_den = 1}, audio = audio_a) + + # ---------- segment B: continuation ---------- + packed_prev = tensor::load(latent_a_path) + video_prev = packed_prev[:, :, :, :c_video] + # audio latent is t-major [T, 2, 32, 1]: the tail slice carries whole + # streams, so no flat-offset math is needed even for unequal segments + audio_prev = unpack_audio(packed_prev, channels = c_video, audio_shape = tensor::shape(audio_zeros), audio_scale = audio_scale) + t_audio = tensor::shape(audio_zeros)[0] + # negative-endpoint slices clip to bounds, so the pinned tail length is + # min(pin_frames, previous segment length, current segment length) + video_tail_raw = video_prev[:, :, -pin_frames:, :] + video_tail = video_tail_raw[:, :, -t_video:, :] + audio_tail_raw = audio_prev[-pin_frames:, :, :, :] + audio_tail = audio_tail_raw[-t_audio:, :, :, :] + h = tensor::shape(video_tail)[2] + n = tensor::shape(audio_tail)[0] + video_base_b = tensor::replace_slice(tensor::zeros(tensor::shape(video_base)), video_tail, axis = 2, start = 0) + audio_b = tensor::replace_slice(tensor::zeros(tensor::shape(audio_zeros)), audio_tail, axis = 0, start = 0) + base_b = pack_av(video_base_b, audio_b, audio_scale = audio_scale) + + # full-width denoise mask over the packed AV latent; zeros pin the carried + # heads exactly (per-step restore: denoised * mask + base * (1 - mask)). + # Audio zeros are folded with the same tail-channel layout as the content. + mask_video = tensor::concat([ + tensor::full([tensor::shape(video_base)[0], tensor::shape(video_base)[1], h, c_video, 1], 0), + tensor::full([tensor::shape(video_base)[0], tensor::shape(video_base)[1], t_video - h, c_video, 1], 1) + ], axis = 2) + mask_audio_pattern = tensor::concat([ + tensor::full([n, tensor::shape(audio_zeros)[1], tensor::shape(audio_zeros)[2], tensor::shape(audio_zeros)[3]], 0), + tensor::full([t_audio - n, tensor::shape(audio_zeros)[1], tensor::shape(audio_zeros)[2], tensor::shape(audio_zeros)[3]], 1) + ], axis = 0) + mask_b = tensor::concat([mask_video, audio_pattern_to_tail(mask_audio_pattern, video_base)], axis = 3) + + condition_b = encode_prompt(text, prompt_b, width = width, height = height) + predict_b = predictor(model, condition_b, audio_length = tensor::shape(audio_zeros)[0]) + sigmas_b = make_sigmas(predict_b, latent = base_b, steps = steps, scheduler = scheduler) + rng_b = make_rng(rng_type, seed = seed + 1) + start_b = add_noise(predict_b, base_b, tensor::randn_like(base_b, rng = rng_b), sigma = sigmas_b[0]) + latent_b = sample(start_b, sigmas_b, predict = predict_b, method = method, rng = rng_b, + base = base_b, denoise_mask = mask_b, mask_input = true) + + frames_b = vae_decode(vae, dit_to_vae_latents(vae, latent_b[:, :, :t_video, :c_video])) + audio_b_out = audio_vae_decode(audio_vae, unpack_audio(latent_b, channels = c_video, audio_shape = tensor::shape(audio_zeros), audio_scale = audio_scale)) + video::save(output_b_path, {frames = frames_b, fps_num = fps, fps_den = 1}, audio = audio_b_out) + return {video = {frames = frames_b, fps_num = fps, fps_den = 1}, latent = latent_b, audio = audio_b_out} +} diff --git a/examples/common/common.cpp b/examples/common/common.cpp deleted file mode 100644 index 0c155c1b89..0000000000 --- a/examples/common/common.cpp +++ /dev/null @@ -1,3030 +0,0 @@ -#include "common.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#if defined(_WIN32) -#define NOMINMAX -#include -#endif // _WIN32 - -#include "log.h" -#include "media_io.h" -#include "resource_owners.hpp" - -using json = nlohmann::json; -namespace fs = std::filesystem; - -const char* const modes_str[] = { - "img_gen", - "adetailer", - "vid_gen", - "convert", - "upscale", - "metadata", - "vid_upscale", -}; - -static void prepend_backend_assignment(std::string& spec, const char* assignment) { - spec = spec.empty() ? assignment : std::string(assignment) + "," + spec; -} - -#if defined(_WIN32) -static std::string utf16_to_utf8(const std::wstring& wstr) { - if (wstr.empty()) - return {}; - int size_needed = WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(), - nullptr, 0, nullptr, nullptr); - if (size_needed <= 0) - throw std::runtime_error("UTF-16 to UTF-8 conversion failed"); - - std::string utf8(size_needed, 0); - WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(), - (char*)utf8.data(), size_needed, nullptr, nullptr); - return utf8; -} - -std::string argv_to_utf8(int index, const char** argv) { - (void)argv; - int argc; - wchar_t** argv_w = CommandLineToArgvW(GetCommandLineW(), &argc); - if (!argv_w) - throw std::runtime_error("Failed to parse command line"); - - std::string result; - if (index < argc) { - result = utf16_to_utf8(argv_w[index]); - } - LocalFree(argv_w); - return result; -} - -#else // Linux / macOS -std::string argv_to_utf8(int index, const char** argv) { - return std::string(argv[index]); -} - -#endif - -template -static std::string vec_to_string(const std::vector& v) { - std::ostringstream oss; - oss << "["; - for (size_t i = 0; i < v.size(); i++) { - oss << v[i]; - if (i + 1 < v.size()) - oss << ", "; - } - oss << "]"; - return oss.str(); -} - -static std::string vec_str_to_string(const std::vector& v) { - std::ostringstream oss; - oss << "["; - for (size_t i = 0; i < v.size(); i++) { - oss << "\"" << v[i] << "\""; - if (i + 1 < v.size()) - oss << ", "; - } - oss << "]"; - return oss.str(); -} - -static bool is_absolute_path(const std::string& p) { -#ifdef _WIN32 - return p.size() > 1 && std::isalpha(static_cast(p[0])) && p[1] == ':'; -#else - return !p.empty() && p[0] == '/'; -#endif -} - -std::string ArgOptions::wrap_text(const std::string& text, size_t width, size_t indent) { - std::ostringstream oss; - size_t pos = 0; - size_t line_len = 0; - - while (pos < text.size()) { - if (text[pos] == '\n') { - oss << '\n' - << std::string(indent, ' '); - line_len = 0; - ++pos; - continue; - } - - if (std::isspace(static_cast(text[pos]))) { - ++pos; - continue; - } - - size_t word_start = pos; - while (pos < text.size() && - text[pos] != '\n' && - !std::isspace(static_cast(text[pos]))) { - ++pos; - } - - std::string word = text.substr(word_start, pos - word_start); - while (!word.empty()) { - size_t separator_len = line_len == 0 ? 0 : 1; - if (line_len + separator_len + word.size() <= width) { - if (separator_len > 0) { - oss << ' '; - ++line_len; - } - oss << word; - line_len += word.size(); - word.clear(); - continue; - } - - if (line_len > 0) { - oss << '\n' - << std::string(indent, ' '); - line_len = 0; - continue; - } - - size_t chunk_len = std::min(width, word.size()); - oss << word.substr(0, chunk_len); - line_len = chunk_len; - word.erase(0, chunk_len); - if (!word.empty()) { - oss << '\n' - << std::string(indent, ' '); - line_len = 0; - } - } - } - - return oss.str(); -} - -void ArgOptions::print() const { - constexpr size_t max_line_width = 120; - - struct Entry { - std::string names; - std::string desc; - }; - std::vector entries; - - auto add_entry = [&](const std::string& s, const std::string& l, - const std::string& desc, const std::string& hint = "") { - std::ostringstream ss; - if (!s.empty()) - ss << s; - if (!s.empty() && !l.empty()) - ss << ", "; - if (!l.empty()) - ss << l; - if (!hint.empty()) - ss << " " << hint; - entries.push_back({ss.str(), desc}); - }; - - for (auto& o : string_options) - add_entry(o.short_name, o.long_name, o.desc, ""); - for (auto& o : int_options) - add_entry(o.short_name, o.long_name, o.desc, ""); - for (auto& o : float_options) - add_entry(o.short_name, o.long_name, o.desc, ""); - for (auto& o : bool_options) - add_entry(o.short_name, o.long_name, o.desc, ""); - for (auto& o : manual_options) - add_entry(o.short_name, o.long_name, o.desc); - - size_t max_name_width = 0; - for (auto& e : entries) - max_name_width = std::max(max_name_width, e.names.size()); - - for (auto& e : entries) { - size_t indent = 2 + max_name_width + 4; - size_t desc_width = (max_line_width > indent ? max_line_width - indent : 40); - std::string wrapped_desc = wrap_text(e.desc, desc_width, indent); - std::cout << " " << std::left << std::setw(static_cast(max_name_width) + 4) - << e.names << wrapped_desc << "\n"; - } -} - -void add_log_options(ArgOptions& options, sd_log_level_t& level) { - options.manual_options.push_back({"", "--log-level", - "minimum log level, one of [debug, verbose, info, warn, error] (default: info)", - [&level](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - if (!parse_log_level(argv[index], level)) { - LOG_ERROR("invalid log level %s, must be one of [debug, verbose, info, warn, error]", argv[index]); - return -1; - } - return 1; - }}); - options.manual_options.push_back({"-v", "--verbose", "equivalent to --log-level verbose", - [&level](int, const char**, int) { - level = SD_LOG_VERBOSE; - return 0; - }}); -} - -bool parse_options(int argc, const char** argv, const std::vector& options_list) { - bool invalid_arg = false; - std::string arg; - - auto match_and_apply = [&](auto& opts, auto&& apply_fn) -> bool { - for (auto& option : opts) { - if ((option.short_name.size() > 0 && arg == option.short_name) || - (option.long_name.size() > 0 && arg == option.long_name)) { - apply_fn(option); - return true; - } - } - return false; - }; - - bool valid = false; - for (int i = 1; i < argc; i++) { - arg = argv[i]; - bool found_arg = false; - - for (auto& options : options_list) { - if (match_and_apply(options.string_options, [&](auto& option) { - if (++i >= argc) { - invalid_arg = true; - return; - } - if (option.concat && !option.target.get().empty()) { - if (option.concat > 0 && option.concat <= 0xff) { - option.target.set(option.target.get() + static_cast(option.concat)); - } - option.target.set(option.target.get() + argv_to_utf8(i, argv)); - } else { - option.target.set(argv_to_utf8(i, argv)); - } - found_arg = true; - })) - break; - - if (match_and_apply(options.int_options, [&](auto& option) { - if (++i >= argc) { - invalid_arg = true; - return; - } - try { - option.target.set(std::stoi(argv[i])); - } catch (const std::invalid_argument&) { - invalid_arg = true; - } - found_arg = true; - })) - break; - - if (match_and_apply(options.float_options, [&](auto& option) { - if (++i >= argc) { - invalid_arg = true; - return; - } - try { - option.target.set(std::stof(argv[i])); - } catch (const std::invalid_argument&) { - invalid_arg = true; - } - found_arg = true; - })) - break; - - if (match_and_apply(options.bool_options, [&](auto& option) { - option.target.set(option.keep_true); - found_arg = true; - })) - break; - - if (match_and_apply(options.manual_options, [&](auto& option) { - int ret = option.cb(argc, argv, i, valid); - if (ret < 0) { - invalid_arg = true; - return; - } - i += ret; - found_arg = true; - })) - break; - } - - if (invalid_arg) { - if (!valid) { - LOG_ERROR("error: invalid parameter for argument \"%s\": \"%s\"", - arg.c_str(), (i >= argc) ? "" : argv[i]); - } - return false; - } - if (!found_arg) { - LOG_ERROR("error: unknown argument: %s", arg.c_str()); - return false; - } - } - - return true; -} - -static int parse_scale_override(int argc, const char** argv, int index, std::optional& scale) { - if (++index >= argc) { - return -1; - } - try { - size_t end = 0; - const std::string value = argv[index]; - float parsed = std::stof(value, &end); - if (end != value.size() || !std::isfinite(parsed) || parsed < 0.f || - (parsed > 0.f && !std::isfinite(1.f / parsed))) { - return -1; - } - scale = parsed; - } catch (const std::exception&) { - return -1; - } - return 1; -} - -static int parse_on_off_arg(int argc, const char** argv, int index, const char* option, std::optional& value) { - if (++index >= argc) { - LOG_ERROR("%s requires 'on' or 'off'", option); - return -1; - } - const std::string arg = argv[index]; - if (arg == "on") { - value = true; - } else if (arg == "off") { - value = false; - } else { - LOG_ERROR("invalid %s value '%s'; expected 'on' or 'off'", option, argv[index]); - return -1; - } - return 1; -} - -ArgOptions SDContextParams::get_options() { - ArgOptions options; - options.string_options = { - {"-m", - "--model", - "path to full model", - 0, - &model_path}, - {"", - "--clip_l", - "path to the clip-l text encoder", - 0, - &clip_l_path}, - {"", "--clip_g", - "path to the clip-g text encoder", - 0, - &clip_g_path}, - {"", - "--clip_vision", - "path to the clip-vision encoder", - 0, - &clip_vision_path}, - {"", - "--t5xxl", - "path to the t5xxl text encoder", - 0, - &t5xxl_path}, - {"", - "--llm", - "path to the llm text encoder. For example: (qwenvl2.5 for qwen-image, mistral-small3.2 for flux2, ...)", - 0, - &llm_path}, - {"", - "--tokenizer", - "tokenizer.json path, or comma-separated main=FILE,clip-l=FILE,clip-g=FILE assignments; required for PiD and Lens", - (int)',', - &tokenizer}, - {"", - "--llm_vision", - "path to the llm vit", - 0, - &llm_vision_path}, - {"", - "--qwen2vl", - "alias of --llm. Deprecated.", - 0, - &llm_path}, - {"", - "--qwen2vl_vision", - "alias of --llm_vision. Deprecated.", - 0, - &llm_vision_path}, - {"", - "--diffusion-model", - "path to the standalone diffusion model", - 0, - &diffusion_model_path}, - {"", - "--high-noise-diffusion-model", - "path to the standalone high noise diffusion model", - 0, - &high_noise_diffusion_model_path}, - {"", - "--uncond-diffusion-model", - "path to the standalone unconditional diffusion model, currently used by Ideogram4 CFG", - 0, - &uncond_diffusion_model_path}, - {"", - "--embeddings-connectors", - "path to embeddings connectors (LTXAV or P-H3-Image)", - 0, - &embeddings_connectors_path}, - {"", - "--vae", - "path to standalone vae model", - 0, - &vae_path}, - {"", - "--vae-format", - "VAE latent format override: auto, flux, sd3, flux2, or wan (default: auto)", - 0, - &vae_format}, - {"", - "--audio-vae", - "path to standalone LTX audio vae model", - 0, - &audio_vae_path}, - {"", - "--audio-encoder", - "path to wav2vec2 audio encoder model (Wan2.2 S2V)", - 0, - &audio_encoder_path}, - {"", - "--taesd", - "path to taesd. Using Tiny AutoEncoder for fast decoding (low quality)", - 0, - &taesd_path}, - {"", - "--tae", - "alias of --taesd", - 0, - &taesd_path}, - {"", - "--control-net", - "path to control net model", - 0, - &control_net_path}, - {"", - "--ip-adapter", - "path to IP-Adapter model (requires --clip_vision)", - 0, - &ip_adapter_path}, - {"", - "--motion-module", - "path to AnimateDiff motion module (SD 1.5); enables video generation on --video-frames > 1", - 0, - &motion_module_path}, - {"", - "--embd-dir", - "embeddings directory", - 0, - &embedding_dir}, - {"", - "--lora-model-dir", - "lora model directory", - 0, - &lora_model_dir}, - {"", - "--hires-upscalers-dir", - "highres fix upscaler model directory", - 0, - &hires_upscalers_dir}, - {"", - "--tensor-type-rules", - "weight type per tensor pattern (example: \"^vae\\.=f16,model\\.=q8_0\")", - (int)',', - &tensor_type_rules}, - {"", - "--model-args", - "extra model args, key=value list. Supports chroma_use_dit_mask, chroma_use_t5_mask, " - "chroma_t5_mask_pad, qwen_image_zero_cond_t, qwen_image_2_1_prefix_cache, " - "qwen_image_2_1_prefix_cache_type (auto or a type name from --type)", - (int)',', - &model_args}, - {"", - "--photo-maker", - "path to PHOTOMAKER model", - 0, - &photo_maker_path}, - {"", - "--pulid-weights", - "path to PuLID Flux weights", - 0, - &pulid_weights_path}, - {"", - "--upscale-model", - "path to esrgan model.", - 0, - &esrgan_path}, - {"", - "--backend", - "runtime backend assignment, e.g. cpu or clip=cpu,vae=cuda0,diffusion=vulkan0", - (int)',', - &backend}, - {"", - "--params-backend", - "parameter backend assignment, e.g. disk, cpu, or diffusion=disk,clip=cpu", - (int)',', - ¶ms_backend}, - {"", - "--split-mode", - "weight distribution for modules assigned multiple devices (--backend \"diffusion=cuda0&cuda1\"): " - "layer (whole transformer blocks per device, default) or row (matmul rows split across devices, CUDA only). " - "Accepts a single mode or per-module assignments, e.g. row or diffusion=row,te=layer", - (int)',', - &split_mode}, - {"", - "--rpc-servers", - "comma-separated list of RPC servers to connect to for offloading, in the format host:port, e.g. localhost:50052,192.168.1.3:50052", - (int)',', - &rpc_servers}, - {"", - "--max-vram", - "optional per-device budget in GiB for managed weights and runner buffers during automatic graph-cut execution. Accepts a single value or assignments by backend/device, e.g. 6 or cuda0=6,vulkan0=4. 0 uses live free VRAM without an explicit budget; a negative value reserves that much free VRAM", - 0, - &max_vram}, - }; - - options.int_options = { - {"-t", - "--threads", - "positive number of computation threads; unset uses the library CPU core selection", - &n_threads}, - {"", - "--conditioning-cache-size", - "maximum cached conditioning results; unset uses the library default, 0 disables caching", - &conditioning_cache_size}, - }; - - options.bool_options = { - {"", - "--list-devices", - "list available ggml backend devices, including --rpc-servers (one 'namedescription' per line), and exit; " - "the names are the device names accepted by --backend and --params-backend", - true, &list_devices}, - {"", - "--disable-prefetch", - "disable asynchronous next-segment weight prefetch (defaults to false)", - true, &disable_prefetch}, - {"", - "--disable-segmented-compute", - "force monolithic graph execution even when automatic graph cutting is needed (defaults to false)", - true, &disable_segmented_compute}, - {"", - "--eager-load", - "load all params into the params backend at model-load time instead of lazily on first use (defaults to false)", - true, &eager_load}, - {"", - "--force-sdxl-vae-conv-scale", - "force use of conv scale on sdxl vae", - true, &force_sdxl_vae_conv_scale}, - {"", - "--offload-to-cpu", - "place the weights in RAM to save VRAM, and automatically load them into VRAM when needed", - true, &offload_params_to_cpu}, - {"", - "--mmap", - "whether to memory-map model", - true, &enable_mmap}, - {"", - "--control-net-cpu", - "deprecated; use --backend controlnet=cpu", - true, &control_net_cpu}, - {"", - "--clip-on-cpu", - "deprecated; use --backend te=cpu", - true, &clip_on_cpu}, - {"", - "--vae-on-cpu", - "deprecated; use --backend vae=cpu", - true, &vae_on_cpu}, - {"", - "--sage-attn", - "use native CUDA SageAttention in the diffusion model, with flash/default attention fallback", - true, &sage_attn}, - {"", - "--taesd-preview-only", - "prevents usage of taesd for decoding the final image; the VAE keeps encoding / decoding and taesd is only used for step previews", - true, &taesd_preview_only}, - }; - - auto on_type_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - wtype = str_to_sd_type(arg); - if (wtype == SD_TYPE_COUNT) { - LOG_ERROR("error: invalid weight format %s", - arg); - return -1; - } - return 1; - }; - - auto on_rng_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - rng_type = arg; - return 1; - }; - - auto on_sampler_rng_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - sampler_rng_type = arg; - return 1; - }; - - auto on_prediction_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - prediction = arg; - return 1; - }; - - auto on_lora_apply_mode_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - lora_apply_mode = arg; - return 1; - }; - - options.manual_options = { - {"", - "--linear-scale", - "linear input scale override (float, default: 0 = model default, 1 = no scaling)", - [this](int argc, const char** argv, int index) { - return parse_scale_override(argc, argv, index, linear_scale); - }}, - {"", - "--attn-scale", - "flash-attention K/V scale override (float, default: 0 = model default, 1 = no scaling); applies when flash attention is selected", - [this](int argc, const char** argv, int index) { - return parse_scale_override(argc, argv, index, attn_scale); - }}, - {"", - "--diffusion-conv-direct", - "deprecated; use --conv-direct auto,diffusion=on,controlnet=on", - [this](int, const char**, int) { - LOG_WARN("--diffusion-conv-direct is deprecated; use --conv-direct auto,diffusion=on,controlnet=on instead."); - diffusion_conv_direct = true; - return 0; - }}, - {"", - "--vae-conv-direct", - "deprecated; use --conv-direct auto,vae=on", - [this](int, const char**, int) { - LOG_WARN("--vae-conv-direct is deprecated; use --conv-direct auto,vae=on instead."); - vae_conv_direct = true; - return 0; - }}, - {"", - "--conv-direct", - "on|off|auto or diffusion/vae/controlnet assignments (default: auto), e.g. auto,vae=off. Overrides legacy convolution flags", - [this](int argc, const char** argv, int index) { - if (++index >= argc || argv[index][0] == '\0') { - LOG_ERROR("--conv-direct requires on, off, auto, or module assignments"); - return -1; - } - conv_direct_mode = argv[index]; - return 1; - }}, - {"", - "--flash-attn", - "on|off|auto or module assignments (default: auto), e.g. auto,te=off,vae=on. Last repeated option wins", - [this](int argc, const char** argv, int index) { - if (++index >= argc) { - LOG_ERROR("--flash-attn requires on, off, or auto"); - return -1; - } - const std::string value = argv[index]; - if (value.empty()) { - LOG_ERROR("--flash-attn requires a nonempty value"); - return -1; - } - flash_attn_mode = value; - return 1; - }}, - {"", - "--fa", - "deprecated; use --flash-attn on", - [this](int, const char**, int) { - LOG_WARN("--fa is deprecated; use --flash-attn on instead."); - flash_attn_mode = "on"; - return 0; - }}, - {"", - "--diffusion-fa", - "deprecated; use --flash-attn off,diffusion=on", - [this](int, const char**, int) { - LOG_WARN("--diffusion-fa is deprecated; use --flash-attn off,diffusion=on instead."); - flash_attn_mode = "off,diffusion=on"; - return 0; - }}, - {"", - "--auto-fit", - "on|off (default: on). Preserve --backend (otherwise select one GPU) and place weights on the compute GPU, " - "RAM, another GPU, or disk in that order, according to available memory (--max-vram limits GPU budgets). " - "Disabled by explicit --params-backend; uses automatic graph segmentation when needed", - [this](int argc, const char** argv, int index) { - return parse_on_off_arg(argc, argv, index, "--auto-fit", auto_fit); - }}, - {"", - "--batched-cfg", - "on|off (default: on). Run the conditional and unconditional CFG branches in one batched UNet forward when supported", - [this](int argc, const char** argv, int index) { - return parse_on_off_arg(argc, argv, index, "--batched-cfg", batched_cfg); - }}, - {"", - "--type", - "weight type (examples: f32, f16, q4_0, q4_1, q5_0, q5_1, q8_0, q2_K, q3_K, q4_K). " - "If not specified, the default is the type of the weight file", - on_type_arg}, - {"", - "--rng", - "RNG, one of [std_default, cuda, cpu], default: cuda(sd-webui), cpu(comfyui)", - on_rng_arg}, - {"", - "--sampler-rng", - "sampler RNG, one of [std_default, cuda, cpu]. If not specified, use --rng", - on_sampler_rng_arg}, - {"", - "--prediction", - "prediction type override, one of [eps, v, edm_v, sd3_flow, flux_flow, sefi_flow, minit2i_flow, sensenova_u1_flow, flux3_flow, h3_av_flow, ming_image_flow]", - on_prediction_arg}, - {"", - "--lora-apply-mode", - "the way to apply LoRA, one of [auto, immediately, at_runtime], default is auto. " - "In auto mode, if the model weights contain any quantized parameters, the at_runtime mode will be used; otherwise, immediately will be used." - "The immediately mode may have precision and compatibility issues with quantized parameters, " - "but it usually offers faster inference speed and, in some cases, lower memory usage. " - "The at_runtime mode, on the other hand, is exactly the opposite.", - on_lora_apply_mode_arg}, - }; - - return options; -} - -bool SDContextParams::print_devices() const { - if (!sd_add_rpc_servers(rpc_servers ? rpc_servers->c_str() : nullptr)) { - return false; - } - size_t device_list_size = sd_list_devices(nullptr, 0); - std::vector devices(device_list_size + 1); - sd_list_devices(devices.data(), devices.size()); - fputs(devices.data(), stdout); - return true; -} - -void SDContextParams::build_embedding_map() { - static const std::vector valid_ext = {".gguf", ".safetensors", ".pt", ".ckpt"}; - - const fs::path embedding_dir_path = fs::u8path(embedding_dir); - if (!fs::exists(embedding_dir_path) || !fs::is_directory(embedding_dir_path)) { - return; - } - - for (auto& p : fs::directory_iterator(embedding_dir_path)) { - if (!p.is_regular_file()) - continue; - - auto path = p.path(); - std::string ext = path.extension().u8string(); - - bool valid = false; - for (auto& e : valid_ext) { - if (ext == e) { - valid = true; - break; - } - } - if (!valid) - continue; - - std::string key = path.stem().u8string(); - std::string value = path.u8string(); - - embedding_map[key] = value; - } -} - -bool SDContextParams::resolve(SDMode mode) { - build_embedding_map(); - - return true; -} - -bool SDContextParams::validate(SDMode mode) { - if (mode == CONVERT) { - const bool has_convert_input = model_path.length() != 0 || - clip_l_path.length() != 0 || - clip_g_path.length() != 0 || - t5xxl_path.length() != 0 || - diffusion_model_path.length() != 0 || - vae_path.length() != 0; - if (!has_convert_input) { - LOG_ERROR("error: convert mode needs at least one model input path\n"); - return false; - } - } else if (mode != UPSCALE && mode != METADATA && model_path.length() == 0 && diffusion_model_path.length() == 0) { - LOG_ERROR("error: the following arguments are required: model_path/diffusion_model\n"); - return false; - } - - if (mode == UPSCALE) { - if (esrgan_path.length() == 0) { - LOG_ERROR("error: upscale mode needs an upscaler model (--upscale-model)\n"); - return false; - } - } - - if (!to_context_opt()) { - LOG_ERROR("%s", sd_get_last_error()); - return false; - } - - return true; -} - -bool SDContextParams::resolve_and_validate(SDMode mode) { - if (!resolve(mode)) { - return false; - } - if (!validate(mode)) { - return false; - } - return true; -} - -void SDContextParams::prepare_backend_assignments() { - effective_backend = backend.value_or(""); - effective_params_backend = params_backend.value_or(""); - - if (offload_params_to_cpu) { - prepend_backend_assignment(effective_params_backend, "*=cpu"); - } - - if (clip_on_cpu) { - prepend_backend_assignment(effective_backend, "te=cpu"); - } - if (vae_on_cpu) { - prepend_backend_assignment(effective_backend, "vae=cpu"); - } - if (control_net_cpu) { - prepend_backend_assignment(effective_backend, "controlnet=cpu"); - } -} - -std::string SDContextParams::to_string() const { - std::ostringstream emb_ss; - emb_ss << "{\n"; - for (auto it = embedding_map.begin(); it != embedding_map.end(); ++it) { - emb_ss << " \"" << it->first << "\": \"" << it->second << "\""; - if (std::next(it) != embedding_map.end()) { - emb_ss << ","; - } - emb_ss << "\n"; - } - emb_ss << " }"; - - std::string embeddings_str = emb_ss.str(); - std::ostringstream oss; - oss << "SDContextParams {\n" - << " n_threads: " << n_threads << ",\n" - << " conditioning_cache_size: " << conditioning_cache_size << ",\n" - << " model_path: \"" << model_path << "\",\n" - << " clip_l_path: \"" << clip_l_path << "\",\n" - << " clip_g_path: \"" << clip_g_path << "\",\n" - << " clip_vision_path: \"" << clip_vision_path << "\",\n" - << " t5xxl_path: \"" << t5xxl_path << "\",\n" - << " llm_path: \"" << llm_path << "\",\n" - << " llm_vision_path: \"" << llm_vision_path << "\",\n" - << " tokenizer: \"" << tokenizer << "\",\n" - << " diffusion_model_path: \"" << diffusion_model_path << "\",\n" - << " high_noise_diffusion_model_path: \"" << high_noise_diffusion_model_path << "\",\n" - << " uncond_diffusion_model_path: \"" << uncond_diffusion_model_path << "\",\n" - << " embeddings_connectors_path: \"" << embeddings_connectors_path << "\",\n" - << " vae_path: \"" << vae_path << "\",\n" - << " vae_format: \"" << vae_format << "\",\n" - << " audio_vae_path: \"" << audio_vae_path << "\",\n" - << " audio_encoder_path: \"" << audio_encoder_path << "\",\n" - << " taesd_path: \"" << taesd_path << "\",\n" - << " esrgan_path: \"" << esrgan_path << "\",\n" - << " control_net_path: \"" << control_net_path << "\",\n" - << " embedding_dir: \"" << embedding_dir << "\",\n" - << " embeddings: " << embeddings_str << "\n" - << " wtype: " << sd_type_name(wtype) << ",\n" - << " tensor_type_rules: \"" << tensor_type_rules << "\",\n" - << " lora_model_dir: \"" << lora_model_dir << "\",\n" - << " hires_upscalers_dir: \"" << hires_upscalers_dir << "\",\n" - << " photo_maker_path: \"" << photo_maker_path << "\",\n" - << " rng_type: " << rng_type << ",\n" - << " sampler_rng_type: " << sampler_rng_type << ",\n" - << " offload_params_to_cpu: " << (offload_params_to_cpu ? "true" : "false") << ",\n" - << " max_vram: \"" << max_vram << "\",\n" - << " disable_prefetch: " << disable_prefetch << ",\n" - << " disable_segmented_compute: " << disable_segmented_compute << ",\n" - << " batched_cfg: " << batched_cfg << ",\n" - << " eager_load: " << eager_load << ",\n" - << " backend: \"" << backend << "\",\n" - << " params_backend: \"" << params_backend << "\",\n" - << " split_mode: \"" << split_mode << "\",\n" - << " model_args: \"" << model_args << "\",\n" - << " auto_fit: " << auto_fit << ",\n" - << " enable_mmap: " << enable_mmap << ",\n" - << " control_net_cpu: " << (control_net_cpu ? "true" : "false") << ",\n" - << " clip_on_cpu: " << (clip_on_cpu ? "true" : "false") << ",\n" - << " vae_on_cpu: " << (vae_on_cpu ? "true" : "false") << ",\n" - << " flash_attn_mode: " << flash_attn_mode << ",\n" - << " conv_direct_mode: " << conv_direct_mode << ",\n" - << " sage_attn: " << sage_attn << ",\n" - << " linear_scale: " << linear_scale << ",\n" - << " attn_scale: " << attn_scale << ",\n" - << " diffusion_conv_direct: " << diffusion_conv_direct << ",\n" - << " vae_conv_direct: " << vae_conv_direct << ",\n" - << " taesd_preview_only: " << taesd_preview_only << ",\n" - << " prediction: " << prediction << ",\n" - << " lora_apply_mode: " << lora_apply_mode << ",\n" - << " force_sdxl_vae_conv_scale: " << force_sdxl_vae_conv_scale << "\n" - << "}"; - return oss.str(); -} - -SDOptPtr SDContextParams::to_context_opt() { - prepare_backend_assignments(); - embedding_vec.clear(); - embedding_vec.reserve(embedding_map.size()); - for (const auto& kv : embedding_map) { - sd_embedding_t item; - item.name = kv.first.c_str(); - item.path = kv.second.c_str(); - embedding_vec.emplace_back(item); - } - - SDOptBuilder opt(sd_ctx_opt_create()); - opt.set_string("model_path", model_path); - opt.set_string("clip_l_path", clip_l_path); - opt.set_string("clip_g_path", clip_g_path); - opt.set_string("clip_vision_path", clip_vision_path); - opt.set_string("t5xxl_path", t5xxl_path); - opt.set_string("llm_path", llm_path); - opt.set_string("llm_vision_path", llm_vision_path); - opt.set_string("tokenizer", tokenizer); - opt.set_string("diffusion_model_path", diffusion_model_path); - opt.set_string("high_noise_diffusion_model_path", high_noise_diffusion_model_path); - opt.set_string("uncond_diffusion_model_path", uncond_diffusion_model_path); - opt.set_string("embeddings_connectors_path", embeddings_connectors_path); - opt.set_string("vae_path", vae_path); - opt.set_string("audio_vae_path", audio_vae_path); - opt.set_string("audio_encoder_path", audio_encoder_path); - opt.set_string("taesd_path", taesd_path); - opt.set_string("control_net_path", control_net_path); - opt.set_string("ip_adapter_path", ip_adapter_path); - opt.set_string("motion_module_path", motion_module_path); - opt.set_string("photo_maker_path", photo_maker_path); - opt.set_string("pulid_weights_path", pulid_weights_path); - opt.set_string("tensor_type_rules", tensor_type_rules); - opt.set_int("n_threads", n_threads); - opt.set_int("conditioning_cache_size", conditioning_cache_size); - if (wtype != SD_TYPE_COUNT) - opt.set_string("wtype", sd_type_name(wtype)); - opt.set_string("rng_type", rng_type); - opt.set_string("sampler_rng_type", sampler_rng_type); - opt.set_string("prediction", prediction); - opt.set_string("lora_apply_mode", lora_apply_mode); - opt.set_bool("enable_mmap", enable_mmap); - opt.set_string("flash_attn_mode", flash_attn_mode); - opt.set_string("conv_direct_mode", conv_direct_mode); - opt.set_bool("sage_attn", sage_attn); - opt.set_float("linear_scale", linear_scale); - opt.set_float("attn_scale", attn_scale); - opt.set_bool("tae_preview_only", taesd_preview_only); - opt.set_bool("diffusion_conv_direct", diffusion_conv_direct); - opt.set_bool("vae_conv_direct", vae_conv_direct); - opt.set_bool("force_sdxl_vae_conv_scale", force_sdxl_vae_conv_scale); - opt.set_string("vae_format", vae_format); - opt.set_string("max_vram", max_vram); - opt.set_bool("disable_prefetch", disable_prefetch); - opt.set_bool("disable_segmented_compute", disable_segmented_compute); - opt.set_bool("batched_cfg", batched_cfg); - opt.set_bool("eager_load", eager_load); - if (backend || !effective_backend.empty()) - opt.set_string("backend", effective_backend); - if (params_backend || !effective_params_backend.empty()) - opt.set_string("params_backend", effective_params_backend); - opt.set_string("split_mode", split_mode); - opt.set_bool("auto_fit", auto_fit); - opt.set_string("rpc_servers", rpc_servers); - opt.set_string("model_args", model_args); - opt.set_embeddings("embeddings", embedding_vec.data(), embedding_vec.size()); - return opt.finish(); -} - -SDGenerationParams::SDGenerationParams() { -} - -ArgOptions SDGenerationParams::get_options() { - ArgOptions options; - options.string_options = { - {"-p", - "--prompt", - "the prompt to render", - 0, - &prompt}, - {"-n", - "--negative-prompt", - "the negative prompt (default: \"\")", - 0, - &negative_prompt}, - {"", - "--ad-model", - "path to a converted YOLOv8 detection model for ADetailer", - 0, - &ad_model_path}, - {"", - "--ad-prompt", - "ADetailer prompt; empty inherits the main prompt, supports [PROMPT], [SEP], and [SKIP]", - 0, - &ad_prompt}, - {"", - "--ad-negative-prompt", - "ADetailer negative prompt; empty inherits the main negative prompt, supports [PROMPT] and [SEP]", - 0, - &ad_negative_prompt}, - {"", - "--extra-ad-args", - "extra ADetailer args, key=value list. Supports input_size, confidence, nms, max_detections, mask_k_largest, mask_min_ratio, mask_max_ratio, dilate_erode, x_offset, y_offset, mask_mode, merge_masks, invert_mask, mask_blur, inpaint_padding, inpaint_width, inpaint_height, denoising_strength, steps, cfg_scale, sample_method, scheduler, sort_by", - (int)',', - &extra_ad_args}, - {"-i", - "--init-img", - "path to the init image, or a single input image for vid_upscale", - 0, - &init_image_path}, - {"", - "--end-img", - "path to the end image, required by flf2v", - 0, - &end_image_path}, - {"", - "--mask", - "path to the mask image", - 0, - &mask_image_path}, - {"", - "--control-image", - "path to control image, control net", - 0, - &control_image_path}, - {"", - "--ip-adapter-image", - "path to the IP-Adapter reference image", - 0, - &ip_adapter_image_path}, - {"", - "--control-video", - "path to control video frames, It must be a directory path. The video frames inside should be stored as images in " - "lexicographical (character) order. For example, if the control video path is `frames`, the directory contain images " - "such as 00.png, 01.png, ... etc.", - 0, - &control_video_path}, - {"", - "--pm-id-images-dir", - "path to PHOTOMAKER input id images dir", - 0, - &pm_id_images_dir}, - {"", - "--pm-id-embed-path", - "path to PHOTOMAKER v2 id embed", - 0, - &pm_id_embed_path}, - {"", - "--pulid-id-embedding", - "path to PuLID id embedding", - 0, - &pulid_id_embedding_path}, - {"", - "--hires-upscaler", - "highres fix upscaler, Lanczos, Nearest, Latent, Latent (nearest), Latent (nearest-exact), " - "Latent (antialiased), Latent (bicubic), Latent (bicubic antialiased), or a model name " - "under --hires-upscalers-dir (default: Latent)", - 0, - &hires_upscaler}, - {"", - "--control-type", - "kind of the control image, one of [openpose, depth, scribble, canny, normal, segment, tile, repaint]. " - "Required by an SDXL Control Net Union model (tile and repaint only exist in its ProMax variant), ignored by any other Control Net. " - "Also accepted: hed, softedge, pidi, ted (scribble); lineart, anime_lineart, mlsd (canny); seg (segment); inpaint, outpaint (repaint)", - 0, - &control_type}, - {"", - "--extra-sample-args", - "extra sampler/scheduler/guidance args, key=value list. CFG supports guidance_schedule; APG supports apg_eta, apg_momentum, apg_norm_threshold, apg_norm_threshold_smoothing; SLG supports slg_uncond; lcm supports noise_clip_std, noise_scale_start, noise_scale_end; flux supports base_shift, max_shift; ltx2 supports max_shift, base_shift, stretch, terminal; euler_ge supports gamma; beta scheduler supports alpha, beta; logit_normal supports mu, std, logsnr_min, logsnr_max, resolution_aware; llada_image supports uniform; lms supports lms_max_order, lms_shift, lms_divisions; noise-injecting samplers support noise_sampler with value iid (default except for dpm++2m_sde_bt) or brownian_tree; brownian_tree_rng supports cpu (default), cuda, std_default or sampler_rng", - (int)',', - &extra_sample_args}, - {"", - "--extra-tiling-args", - "extra VAE tiling args, key=value list. Supported video VAEs accept temporal_tile_frames/temporal_tile_size (default: 4), temporal_tile_overlap (default: 1); Wan2.2 TI2V 5B accepts temporal_decode_frames (default: 1)", - (int)',', - &extra_tiling_args}, - {"", - "--ref-image-args", - "Key-value list to set up the way the reference images are processed (empty = auto-detect from model weigths)", - (int)',', - &ref_image_args}, - {"", "--image-preprocess", - "Image preprocessing rule: target=init|end|mask|control|ref|ip-adapter|id|control-frame,index=N,mode=auto|none|stretch|crop|crop-resize|fit-pad,filter=auto|nearest|nearest-exact|bilinear|bicubic|lanczos,antialias=auto|true|false,width=W,height=H,anchor=center|top|bottom|left|right,pad_color=#RRGGBB[AA],canny=true|false. Repeat for multiple rules.", - (int)';', &image_preprocess}, - }; - - options.int_options = { - {"-H", - "--height", - "image height, in pixel space (default: 512)", - &height}, - {"-W", - "--width", - "image width, in pixel space (default: 512)", - &width}, - {"", - "--steps", - "number of sample steps (default: 20)", - &sample_params.sample_steps}, - {"", - "--high-noise-steps", - "(high noise) number of sample steps (default: -1 = auto)", - &high_noise_sample_params.sample_steps}, - {"", - "--clip-skip", - "ignore last layers of CLIP network; 1 ignores none, 2 ignores one layer (default: -1). " - "<= 0 represents unspecified, will be 1 for SD1.x, 2 for SD2.x", - &clip_skip}, - {"-b", - "--batch-count", - "batch count", - &batch_count}, - {"", - "--qwen-image-layers", - "number of Qwen Image Layered layers; latent/output count is layers + 1 (default: 3)", - &qwen_image_layers}, - {"", - "--video-frames", - "video frames; unset uses the library default", - &video_frames}, - {"", - "--fps", - "fps (default: 24)", - &fps}, - {"", - "--timestep-shift", - "shift timestep for NitroFusion models (default: 0). " - "recommended N for NitroSD-Realism around 250 and 500 for NitroSD-Vibrant", - &sample_params.shifted_timestep}, - {"", - "--upscale-repeats", - "Run the ESRGAN upscaler this many times (default: 1)", - &upscale_repeats}, - {"", - "--upscale-tile-size", - "tile size for ESRGAN upscaling (default: 128)", - &upscale_tile_size}, - {"", - "--hires-width", - "highres fix target width, 0 to use --hires-scale (default: 0)", - &hires_width}, - {"", - "--hires-height", - "highres fix target height, 0 to use --hires-scale (default: 0)", - &hires_height}, - {"", - "--hires-steps", - "highres fix second pass sample steps, 0 to reuse --steps (default: 0)", - &hires_steps}, - {"", - "--hires-upscale-tile-size", - "highres fix upscaler tile size, reserved for model-backed upscalers (default: 128)", - &hires_upscale_tile_size}, - }; - - options.float_options = { - {"", - "--cfg-scale", - "unconditional guidance scale: (default: 7.0)", - &sample_params.guidance.txt_cfg}, - {"", - "--img-cfg-scale", - "image guidance scale for inpaint or image edit models: (default: same as --cfg-scale)", - &sample_params.guidance.img_cfg}, - {"", - "--guidance", - "distilled guidance scale for models with guidance input (default: 3.5)", - &sample_params.guidance.distilled_guidance}, - {"", - "--slg-scale", - "skip layer guidance (SLG) scale, only for DiT models: (default: 0). 0 means disabled, a value of 2.5 is nice for sd3.5 medium", - &sample_params.guidance.slg.scale}, - {"", - "--skip-layer-start", - "SLG enabling point (default: 0.01)", - &sample_params.guidance.slg.layer_start}, - {"", - "--skip-layer-end", - "SLG disabling point (default: 0.2)", - &sample_params.guidance.slg.layer_end}, - {"", - "--eta", - "noise multiplier (default: 0 for ddim_trailing, tcd, res_multistep and res_2s; 1 for euler_a, er_sde, dpm++2s_a, dpm++2m_sde and dpm++2m_sde_bt)", - &sample_params.eta}, - {"", - "--flow-shift", - "shift value for Flow models like SD3.x or WAN (default: auto)", - &sample_params.flow_shift}, - {"", - "--high-noise-cfg-scale", - "(high noise) unconditional guidance scale: (default: 7.0)", - &high_noise_sample_params.guidance.txt_cfg}, - {"", - "--high-noise-img-cfg-scale", - "(high noise) image guidance scale for inpaint or image edit models (default: same as --cfg-scale)", - &high_noise_sample_params.guidance.img_cfg}, - {"", - "--high-noise-guidance", - "(high noise) distilled guidance scale for models with guidance input (default: 3.5)", - &high_noise_sample_params.guidance.distilled_guidance}, - {"", - "--high-noise-slg-scale", - "(high noise) skip layer guidance (SLG) scale, only for DiT models: (default: 0)", - &high_noise_sample_params.guidance.slg.scale}, - {"", - "--high-noise-skip-layer-start", - "(high noise) SLG enabling point (default: 0.01)", - &high_noise_sample_params.guidance.slg.layer_start}, - {"", - "--high-noise-skip-layer-end", - "(high noise) SLG disabling point (default: 0.2)", - &high_noise_sample_params.guidance.slg.layer_end}, - {"", - "--high-noise-eta", - "(high noise) noise multiplier (default: 0 for ddim_trailing, tcd, res_multistep and res_2s; 1 for euler_a, er_sde, dpm++2s_a, dpm++2m_sde and dpm++2m_sde_bt)", - &high_noise_sample_params.eta}, - {"", - "--strength", - "strength for noising/unnoising (default: 0.75)", - &strength}, - {"", - "--pm-style-strength", - "", - &pm_style_strength}, - {"", - "--pulid-id-weight", - "strength of PuLID identity injection", - &pulid_id_weight}, - {"", - "--control-strength", - "strength to apply Control Net (default: 0.9). 1.0 corresponds to full destruction of information in init image", - &control_strength}, - {"", - "--ip-adapter-strength", - "strength to apply IP-Adapter (default: 1.0)", - &ip_adapter_strength}, - {"", - "--moe-boundary", - "timestep boundary for Wan2.2 MoE model. (default: 0.875). Only enabled if `--high-noise-steps` is set to -1", - &moe_boundary}, - {"", - "--vace-strength", - "wan vace strength", - &vace_strength}, - {"", - "--vae-tile-overlap", - "tile overlap for vae tiling, in fraction of tile size (default: 0.5)", - &vae_tiling_params.target_overlap}, - {"", - "--hires-scale", - "highres fix scale when target size is not set (default: 2.0)", - &hires_scale}, - {"", - "--hires-denoising-strength", - "highres fix second pass denoising strength (default: 0.7)", - &hires_denoising_strength}, - }; - - options.bool_options = { - {"", - "--increase-ref-index", - "automatically increase the indices of references images based on the order they are listed (starting with 1).", - true, - &increase_ref_index}, - {"", - "--circular", - "enable circular padding on both axes for tileable output", - true, &circular}, - {"", - "--circularx", - "enable circular padding on x-axis (width) only", - true, &circular_x}, - {"", - "--circulary", - "enable circular padding on y-axis (height) only", - true, &circular_y}, - {"", - "--disable-image-metadata", - "do not embed generation metadata on image files", - false, - &embed_image_metadata}, - {"", - "--vae-tiling", - "process vae encode and decode in spatial tiles to reduce memory usage (default: 256x256 image pixels)", - true, - &vae_tiling_params.enabled}, - {"", - "--temporal-tiling", - "enable temporal tiling for supported video VAE decode", - true, - &vae_tiling_params.temporal_tiling}, - {"", - "--hires", - "enable highres fix", - true, - &hires_enabled}, - }; - - auto on_seed_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - seed = std::stoll(argv[index]); - return 1; - }; - - auto on_sample_method_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - sample_params.sample_method = arg; - return 1; - }; - - auto on_high_noise_sample_method_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - high_noise_sample_params.sample_method = arg; - return 1; - }; - - auto on_scheduler_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const char* arg = argv[index]; - sample_params.scheduler = arg; - return 1; - }; - - auto on_skip_layers_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - std::string layers_str = argv[index]; - if (layers_str.size() < 2 || layers_str.front() != '[' || layers_str.back() != ']') { - return -1; - } - - layers_str = layers_str.substr(1, layers_str.size() - 2); - - std::regex regex("[, ]+"); - std::sregex_token_iterator iter(layers_str.begin(), layers_str.end(), regex, -1); - std::sregex_token_iterator end; - std::vector tokens(iter, end); - std::vector layers; - for (const auto& token : tokens) { - try { - size_t used = 0; - const int layer = std::stoi(token, &used); - if (used != token.size()) - return -1; - layers.push_back(layer); - } catch (const std::exception&) { - return -1; - } - } - skip_layers = layers; - return 1; - }; - - auto on_high_noise_skip_layers_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - std::string layers_str = argv[index]; - if (layers_str.size() < 2 || layers_str.front() != '[' || layers_str.back() != ']') { - return -1; - } - - layers_str = layers_str.substr(1, layers_str.size() - 2); - - std::regex regex("[, ]+"); - std::sregex_token_iterator iter(layers_str.begin(), layers_str.end(), regex, -1); - std::sregex_token_iterator end; - std::vector tokens(iter, end); - std::vector layers; - for (const auto& token : tokens) { - try { - size_t used = 0; - const int layer = std::stoi(token, &used); - if (used != token.size()) - return -1; - layers.push_back(layer); - } catch (const std::exception&) { - return -1; - } - } - high_noise_skip_layers = layers; - return 1; - }; - - auto parse_sigmas_arg = [&](const char* value, std::optional>* target, const char* option_name) { - if (target == nullptr || value == nullptr) { - return -1; - } - std::string sigmas_str = value; - if (sigmas_str == "qwen-image-2.1-turbo") { - sigmas_str = "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0"; - } else if (sigmas_str == "p-h3-image") { - sigmas_str = "1.0,0.984753,0.967905,0.951688,0.925372,0.881923,0.810083,0.528718,0.0"; - } else if (sigmas_str == "minimax-h3-image") { - sigmas_str = "1.0,0.9675236940383911,0.8875485062599182,0.75,0.5327739119529724,0.23200887441635132,0.0"; - } else if (sigmas_str == "hyperflow-h3-flash-4") { - sigmas_str = "1.0,0.962575853,0.755781889,0.312497854,0.0"; - } else if (sigmas_str == "hyperflow-h3-flash-6") { - sigmas_str = "1.0,0.982655942,0.914642572,0.674755692,0.385223746,0.159055337,0.0"; - } else if (sigmas_str == "hyperflow-h3-flash-8") { - sigmas_str = "1.0,0.993909776,0.9842875,0.966063678,0.923076928,0.834942341,0.696852028,0.468753338,0.0"; - } - if (!sigmas_str.empty() && sigmas_str.front() == '[') { - sigmas_str.erase(0, 1); - } - if (!sigmas_str.empty() && sigmas_str.back() == ']') { - sigmas_str.pop_back(); - } - - std::vector parsed; - std::stringstream ss(sigmas_str); - std::string item; - while (std::getline(ss, item, ',')) { - item.erase(0, item.find_first_not_of(" \t\n\r\f\v")); - item.erase(item.find_last_not_of(" \t\n\r\f\v") + 1); - if (!item.empty()) { - try { - parsed.push_back(std::stof(item)); - } catch (const std::invalid_argument&) { - LOG_ERROR("error: invalid float value '%s' in %s", item.c_str(), option_name); - return -1; - } catch (const std::out_of_range&) { - LOG_ERROR("error: float value '%s' out of range in %s", item.c_str(), option_name); - return -1; - } - } - } - - if (parsed.empty() && !sigmas_str.empty()) { - LOG_ERROR("error: could not parse any sigma values from '%s'", value); - return -1; - } - *target = std::move(parsed); - return 1; - }; - - auto on_sigmas_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - return parse_sigmas_arg(argv[index], &custom_sigmas, "--sigmas"); - }; - - auto on_hires_sigmas_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - return parse_sigmas_arg(argv[index], &hires_custom_sigmas, "--hires-sigmas"); - }; - - auto on_ref_image_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - ref_image_paths.push_back(argv_to_utf8(index, argv)); - return 1; - }; - - auto on_ref_video_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - ref_video_paths.push_back(argv_to_utf8(index, argv)); - return 1; - }; - - auto on_ref_video_audio_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - ref_video_audio_paths.push_back(argv_to_utf8(index, argv)); - return 1; - }; - - auto on_ref_audio_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - ref_audio_paths.push_back(argv_to_utf8(index, argv)); - return 1; - }; - - auto on_audio_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - ref_audio_paths.push_back(argv_to_utf8(index, argv)); - return 1; - }; - - auto on_cache_mode_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - cache_mode = argv_to_utf8(index, argv); - if (cache_mode != "easycache" && cache_mode != "ucache" && - cache_mode != "dbcache" && cache_mode != "taylorseer" && cache_mode != "cache-dit" && cache_mode != "spectrum") { - fprintf(stderr, "error: invalid cache mode '%s', must be 'easycache', 'ucache', 'dbcache', 'taylorseer', 'cache-dit', or 'spectrum'\n", cache_mode.c_str()); - return -1; - } - return 1; - }; - - auto on_cache_option_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - cache_option = argv_to_utf8(index, argv); - return 1; - }; - - auto on_scm_mask_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - scm_mask = argv_to_utf8(index, argv); - return 1; - }; - - auto on_scm_policy_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - std::string policy = argv_to_utf8(index, argv); - if (policy == "dynamic") { - scm_policy_dynamic = true; - } else if (policy == "static") { - scm_policy_dynamic = false; - } else { - fprintf(stderr, "error: invalid scm policy '%s', must be 'dynamic' or 'static'\n", policy.c_str()); - return -1; - } - return 1; - }; - - auto on_tile_size_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - std::string tile_size_str = argv[index]; - size_t x_pos = tile_size_str.find('x'); - try { - if (x_pos != std::string::npos) { - std::string tile_w_str = tile_size_str.substr(0, x_pos); - std::string tile_h_str = tile_size_str.substr(x_pos + 1); - vae_tiling_params.tile_size_w = std::stoi(tile_w_str); - vae_tiling_params.tile_size_h = std::stoi(tile_h_str); - } else { - vae_tiling_params.tile_size_w = vae_tiling_params.tile_size_h = std::stoi(tile_size_str); - } - } catch (const std::invalid_argument&) { - return -1; - } catch (const std::out_of_range&) { - return -1; - } - return 1; - }; - - auto on_relative_tile_size_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - std::string rel_size_str = argv[index]; - size_t x_pos = rel_size_str.find('x'); - try { - if (x_pos != std::string::npos) { - std::string rel_w_str = rel_size_str.substr(0, x_pos); - std::string rel_h_str = rel_size_str.substr(x_pos + 1); - vae_tiling_params.rel_size_w = std::stof(rel_w_str); - vae_tiling_params.rel_size_h = std::stof(rel_h_str); - } else { - vae_tiling_params.rel_size_w = vae_tiling_params.rel_size_h = std::stof(rel_size_str); - } - } catch (const std::invalid_argument&) { - return -1; - } catch (const std::out_of_range&) { - return -1; - } - return 1; - }; - - auto on_prompt_file_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const std::string arg = argv_to_utf8(index, argv); - std::ifstream f(fs::u8path(arg), std::ios::binary); - try { - prompt = std::string(std::istreambuf_iterator{f}, {}); - } catch (const std::ios_base::failure&) { - f.setstate(std::ios_base::failbit); - } - if (f.fail()) { - LOG_ERROR("error: failed to read prompt file '%s'\n", arg.c_str()); - return -1; - } - return 1; - }; - - auto on_negative_prompt_file_arg = [&](int argc, const char** argv, int index) { - if (++index >= argc) { - return -1; - } - const std::string arg = argv_to_utf8(index, argv); - std::ifstream f(fs::u8path(arg), std::ios::binary); - try { - negative_prompt = std::string(std::istreambuf_iterator{f}, {}); - } catch (const std::ios_base::failure&) { - f.setstate(std::ios_base::failbit); - } - if (f.fail()) { - LOG_ERROR("error: failed to read negative prompt file '%s'\n", arg.c_str()); - return -1; - } - return 1; - }; - - std::string sample_methods; - for (const char* name : example_options::sample_methods) { - if (!sample_methods.empty()) - sample_methods += ", "; - sample_methods += name; - } - std::string schedulers; - for (const char* name : example_options::schedulers) { - if (!schedulers.empty()) - schedulers += ", "; - schedulers += name; - } - - options.manual_options = { - {"-s", - "--seed", - "RNG seed; unset or a negative value requests a random seed", - on_seed_arg}, - {"", - "--sampling-method", - "sampling method, one of [" + sample_methods + "], " - "default: euler for Flux/SD3/Wan, euler_a otherwise", - on_sample_method_arg}, - {"", - "--high-noise-sampling-method", - "(high noise) sampling method, one of [" + sample_methods + "], " - "default: euler for Flux/SD3/Wan, euler_a otherwise", - on_high_noise_sample_method_arg}, - {"", - "--scheduler", - "denoiser sigma scheduler, one of [" + schedulers + "], " - "alias: normal=discrete, default: model-specific", - on_scheduler_arg}, - {"", - "--sigmas", - "custom sigma values for the sampler, comma-separated (e.g., \"14.61,7.8,3.5,0.0\") or preset: qwen-image-2.1-turbo, p-h3-image, minimax-h3-image, hyperflow-h3-flash-4, hyperflow-h3-flash-6, hyperflow-h3-flash-8.", - on_sigmas_arg}, - {"", - "--hires-sigmas", - "custom sigma values for the highres fix second pass, comma-separated (e.g., \"0.85,0.725,0.421875,0.0\") or preset: qwen-image-2.1-turbo, p-h3-image, minimax-h3-image, hyperflow-h3-flash-4, hyperflow-h3-flash-6, hyperflow-h3-flash-8.", - on_hires_sigmas_arg}, - {"", - "--skip-layers", - "layers to skip for SLG steps; unset uses the library default", - on_skip_layers_arg}, - {"", - "--high-noise-skip-layers", - "(high noise) layers to skip for SLG steps; unset uses the library default", - on_high_noise_skip_layers_arg}, - {"-r", - "--ref-image", - "reference image for Flux Kontext or MiniMax-H3 Ref2VA (can be used multiple times)", - on_ref_image_arg}, - {"", - "--ref-video", - "MiniMax-H3 Ref2VA reference video frame directory at 24 fps (can be used multiple times)", - on_ref_video_arg}, - {"", - "--ref-video-audio", - "WAV soundtrack paired by index with --ref-video (can be used multiple times)", - on_ref_video_audio_arg}, - {"", - "--ref-audio", - "standalone WAV reference for MiniMax-H3 Ref2VA (can be used multiple times)", - on_ref_audio_arg}, - {"", - "--audio", - "driving audio track (Wan2.2 S2V; can be used once)", - on_audio_arg}, - {"", - "--cache-mode", - "caching method: 'easycache' (DiT), 'ucache' (UNET), 'dbcache'/'taylorseer'/'cache-dit' (DiT block-level), 'spectrum' (UNET/DiT Chebyshev+Taylor forecasting)", - on_cache_mode_arg}, - {"", - "--cache-option", - "named cache params (key=value format, comma-separated). easycache/ucache: threshold=,start=,end=,decay=,relative=,reset=; dbcache/taylorseer/cache-dit: Fn=,Bn=,threshold=,warmup=; spectrum: w=,m=,lam=,window=,flex=,warmup=,stop=. Examples: \"threshold=0.25\" or \"threshold=1.5,reset=0\"", - on_cache_option_arg}, - {"", - "--scm-mask", - "SCM steps mask for cache-dit: comma-separated 0/1 (e.g., \"1,1,1,0,0,1,0,0,1,0\") - 1=compute, 0=can cache", - on_scm_mask_arg}, - {"", - "--scm-policy", - "SCM policy: 'dynamic' (default) or 'static'", - on_scm_policy_arg}, - {"", - "--vae-tile-size", - "tile size for vae encode and decode in image pixels, format [W]x[H] or [S] (default: 256x256; requires --vae-tiling)", - on_tile_size_arg}, - {"", - "--vae-relative-tile-size", - "relative tile size for vae encode and decode, format [W]x[H] or [S]: <=1 is a dimension fraction, >1 a target tile count (overrides --vae-tile-size; requires --vae-tiling)", - on_relative_tile_size_arg}, - {"", - "--prompt-file", - "path to the file containing the prompt to render", - on_prompt_file_arg}, - {"", - "--negative-prompt-file", - "path to the file containing the negative prompt", - on_negative_prompt_file_arg}, - - }; - - return options; -} - -static const std::string k_base64_chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - -static bool is_base64(unsigned char c) { - return std::isalnum(c) || c == '+' || c == '/'; -} - -static std::vector decode_base64_bytes(const std::string& encoded_string) { - int in_len = static_cast(encoded_string.size()); - int i = 0; - int j = 0; - int in_ = 0; - uint8_t char_array_4[4]; - uint8_t char_array_3[3]; - std::vector ret; - - while (in_len-- && encoded_string[in_] != '=' && is_base64(encoded_string[in_])) { - char_array_4[i++] = encoded_string[in_]; - in_++; - if (i == 4) { - for (i = 0; i < 4; i++) { - char_array_4[i] = static_cast(k_base64_chars.find(char_array_4[i])); - } - - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - - for (i = 0; i < 3; i++) { - ret.push_back(char_array_3[i]); - } - i = 0; - } - } - - if (i) { - for (j = i; j < 4; j++) { - char_array_4[j] = 0; - } - - for (j = 0; j < 4; j++) { - char_array_4[j] = static_cast(k_base64_chars.find(char_array_4[j])); - } - - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - - for (j = 0; j < i - 1; j++) { - ret.push_back(char_array_3[j]); - } - } - - return ret; -} - -bool decode_base64_image(const std::string& encoded_input, - int target_channels, - int expected_width, - int expected_height, - SDImageOwner& out_image) { - std::string encoded = encoded_input; - auto comma_pos = encoded.find(','); - if (comma_pos != std::string::npos) { - encoded = encoded.substr(comma_pos + 1); - } - - std::vector image_bytes = decode_base64_bytes(encoded); - if (image_bytes.empty()) { - return false; - } - - int decoded_width = 0; - int decoded_height = 0; - int resolved_channel = target_channels; - uint8_t* raw_data = load_image_from_memory(reinterpret_cast(image_bytes.data()), - static_cast(image_bytes.size()), - decoded_width, - decoded_height, - resolved_channel, - expected_width, - expected_height, - target_channels); - if (raw_data == nullptr) { - return false; - } - - out_image.reset({(uint32_t)decoded_width, (uint32_t)decoded_height, (uint32_t)resolved_channel, raw_data}); - return true; -} - -static bool parse_image_json_field(const json& parent, - const char* key, - int channels, - SDImageOwner& out_image) { - if (!parent.contains(key)) { - return true; - } - if (parent.at(key).is_null()) { - out_image.reset({0, 0, (uint32_t)channels, nullptr}); - return true; - } - if (!parent.at(key).is_string()) { - return false; - } - return decode_base64_image(parent.at(key).get(), channels, 0, 0, out_image); -} - -/** Parses a JSON array of base64 image strings into owned images. */ -static bool parse_image_array_json_field(const json& parent, - const char* key, - int channels, - std::vector& out_images) { - if (!parent.contains(key)) { - return true; - } - if (parent.at(key).is_null()) { - out_images.clear(); - return true; - } - if (!parent.at(key).is_array()) { - return false; - } - - out_images.clear(); - for (const auto& item : parent.at(key)) { - if (!item.is_string()) { - return false; - } - SDImageOwner image; - if (!decode_base64_image(item.get(), channels, 0, 0, image)) { - return false; - } - out_images.push_back(std::move(image)); - } - return true; -} - -/** Parses a JSON array of base64 WAV strings into owned audio clips. */ -static bool parse_audio_array_json_field(const json& parent, - const char* key, - std::vector& out_audios) { - if (!parent.contains(key)) { - return true; - } - if (parent.at(key).is_null()) { - out_audios.clear(); - return true; - } - if (!parent.at(key).is_array()) { - return false; - } - - out_audios.clear(); - for (const auto& item : parent.at(key)) { - if (!item.is_string()) { - return false; - } - std::string encoded = item.get(); - auto comma_pos = encoded.find(','); - if (comma_pos != std::string::npos) { - encoded = encoded.substr(comma_pos + 1); - } - std::vector audio_bytes = decode_base64_bytes(encoded); - if (audio_bytes.empty()) { - return false; - } - std::vector samples; - uint32_t sample_rate = 0; - uint32_t channels = 0; - if (!load_wav_from_memory(audio_bytes.data(), audio_bytes.size(), samples, sample_rate, channels)) { - return false; - } - SDAudioOwner audio; - audio.reset(std::move(samples), sample_rate, channels); - out_audios.push_back(std::move(audio)); - } - return true; -} - -/** Parses a JSON array of per-video base64 frame arrays into owned videos. */ -static bool parse_video_array_json_field(const json& parent, - const char* key, - std::vector>& out_videos) { - if (!parent.contains(key)) { - return true; - } - if (parent.at(key).is_null()) { - out_videos.clear(); - return true; - } - if (!parent.at(key).is_array()) { - return false; - } - - out_videos.clear(); - for (const auto& video : parent.at(key)) { - if (!video.is_array() || video.empty()) { - return false; - } - std::vector frames; - for (const auto& frame : video) { - if (!frame.is_string()) { - return false; - } - SDImageOwner image; - if (!decode_base64_image(frame.get(), 0, 0, 0, image)) { - return false; - } - frames.push_back(std::move(image)); - } - out_videos.push_back(std::move(frames)); - } - return true; -} - -static bool parse_lora_json_field(const json& parent, - const std::function& lora_path_resolver, - std::map& lora_map, - std::map& high_noise_lora_map) { - if (!parent.contains("lora")) { - return true; - } - if (!parent.at("lora").is_array()) { - return false; - } - - lora_map.clear(); - high_noise_lora_map.clear(); - for (const auto& item : parent.at("lora")) { - if (!item.is_object()) { - return false; - } - - std::string path = item.value("path", ""); - if (path.empty()) { - return false; - } - - std::string resolved_path = lora_path_resolver ? lora_path_resolver(path) : path; - if (resolved_path.empty()) { - return false; - } - - const float multiplier = item.value("multiplier", 1.0f); - const bool is_high_noise = item.value("is_high_noise", false); - if (is_high_noise) { - high_noise_lora_map[resolved_path] += multiplier; - } else { - lora_map[resolved_path] += multiplier; - } - } - - return true; -} - -static bool resolve_model_file_from_dir(const std::string& model_name, - const std::string& model_dir, - const std::vector& valid_ext, - const char* label, - std::string& resolved_path) { - if (model_dir.empty()) { - LOG_ERROR("%s directory is empty", label); - return false; - } - auto ends_with_valid_ext = [&]() { - for (const auto& ext : valid_ext) { - if (model_name.size() < ext.size()) { - continue; - } - auto suffix = model_name.substr(model_name.size() - ext.size()); - std::transform(suffix.begin(), suffix.end(), suffix.begin(), [](unsigned char c) { - return static_cast(std::tolower(c)); - }); - std::string lower_ext = ext; - std::transform(lower_ext.begin(), lower_ext.end(), lower_ext.begin(), [](unsigned char c) { - return static_cast(std::tolower(c)); - }); - if (suffix == lower_ext) { - return true; - } - } - return false; - }; - - if (model_name.empty() || - model_name.find('/') != std::string::npos || - model_name.find('\\') != std::string::npos || - fs::u8path(model_name).has_root_path() || - ends_with_valid_ext()) { - LOG_ERROR("%s must be a model name without path or extension: %s", label, model_name.c_str()); - return false; - } - - fs::path model_dir_path = fs::u8path(model_dir); - for (const auto& ext : valid_ext) { - fs::path try_path = model_dir_path / fs::u8path(model_name + ext); - if (fs::exists(try_path) && fs::is_regular_file(try_path)) { - resolved_path = try_path.lexically_normal().u8string(); - return true; - } - } - - LOG_ERROR("can not find %s %s in %s", label, model_name.c_str(), model_dir_path.lexically_normal().u8string().c_str()); - return false; -} - -bool SDGenerationParams::parse_image_preprocess_json(const std::string& json_str) { - const auto value = json::parse(json_str, nullptr, false); - std::string rules; - if (value.is_string()) { - rules = value.get(); - } else if (value.is_array()) { - for (const auto& item : value) { - if (!item.is_string()) { - LOG_ERROR("image_preprocess must contain rule strings"); - return false; - } - if (!rules.empty()) - rules += ";"; - rules += item.get(); - } - } else { - LOG_ERROR("image_preprocess must be a string or array of strings"); - return false; - } - image_preprocess = std::move(rules); - return true; -} - -bool SDGenerationParams::parse_prompt_images_json(const std::string& json_str) { - auto images = json::parse(json_str, nullptr, false); - if (!images.is_object()) { - return false; - } - std::map decoded; - for (auto it = images.begin(); it != images.end(); ++it) { - if (it.key().empty() || it.key().find('>') != std::string::npos || !it.value().is_string()) { - return false; - } - SDImageOwner image; - if (!decode_base64_image(it.value().get(), 3, 0, 0, image)) { - return false; - } - decoded.emplace(it.key(), std::move(image)); - } - prompt_images = std::move(decoded); - return true; -} - -template -static void load_json_input(const json& object, const char* key, Field& out) { - if (!object.contains(key)) - return; - const auto& value = object.at(key); - if (value.is_null()) { - out = Field{}; - return; - } - using T = typename InputType::type; - bool valid = false; - if constexpr (std::is_same_v) - valid = value.is_string(); - else if constexpr (std::is_same_v) - valid = value.is_boolean(); - else if constexpr (std::is_integral_v) { - valid = value.is_number_integer(); - if (valid) { - if (value.is_number_unsigned()) - valid = value.get() <= static_cast(std::numeric_limits::max()); - else { - const auto integer = value.get(); - valid = integer >= std::numeric_limits::min() && integer <= std::numeric_limits::max(); - } - } - } else if constexpr (std::is_floating_point_v) - valid = value.is_number(); - else - valid = value.is_array(); - if (!valid) - throw std::invalid_argument(std::string(key) + ": invalid value type or range"); - out = value.get(); -} - -/** Populates generation params from a JSON payload (server APIs); returns false on any malformed field. */ -bool SDGenerationParams::from_json_str( - const std::string& json_str, - const std::function& lora_path_resolver) try { - json j; - try { - j = json::parse(json_str); - } catch (...) { - LOG_ERROR("json parse failed %s", json_str.c_str()); - return false; - } - - if (j.contains("image_preprocess") && !parse_image_preprocess_json(j["image_preprocess"].dump())) - return false; - if (j.contains("prompt_images") && !parse_prompt_images_json(j["prompt_images"].dump())) - return false; - - auto load_if_exists = [&](const char* key, auto& out) { load_json_input(j, key, out); }; - - load_if_exists("prompt", prompt); - load_if_exists("negative_prompt", negative_prompt); - load_if_exists("ad_model", ad_model_path); - load_if_exists("ad_prompt", ad_prompt); - load_if_exists("ad_negative_prompt", ad_negative_prompt); - load_if_exists("extra_ad_args", extra_ad_args); - load_if_exists("cache_mode", cache_mode); - load_if_exists("cache_option", cache_option); - load_if_exists("scm_mask", scm_mask); - load_if_exists("ref_image_args", ref_image_args); - - load_if_exists("clip_skip", clip_skip); - load_if_exists("width", width); - load_if_exists("height", height); - load_if_exists("batch_count", batch_count); - load_if_exists("qwen_image_layers", qwen_image_layers); - load_if_exists("video_frames", video_frames); - load_if_exists("fps", fps); - load_if_exists("upscale_repeats", upscale_repeats); - load_if_exists("seed", seed); - - load_if_exists("strength", strength); - load_if_exists("control_strength", control_strength); - load_if_exists("control_type", control_type); - load_if_exists("ip_adapter_strength", ip_adapter_strength); - load_if_exists("moe_boundary", moe_boundary); - load_if_exists("vace_strength", vace_strength); - - load_if_exists("increase_ref_index", increase_ref_index); - load_if_exists("embed_image_metadata", embed_image_metadata); - - if (j.contains("hires") && j["hires"].is_object()) { - const json& hires_json = j["hires"]; - load_json_input(hires_json, "enabled", hires_enabled); - load_json_input(hires_json, "upscaler", hires_upscaler); - load_json_input(hires_json, "scale", hires_scale); - load_json_input(hires_json, "target_width", hires_width); - load_json_input(hires_json, "target_height", hires_height); - load_json_input(hires_json, "steps", hires_steps); - load_json_input(hires_json, "denoising_strength", hires_denoising_strength); - load_json_input(hires_json, "custom_sigmas", hires_custom_sigmas); - load_json_input(hires_json, "upscale_tile_size", hires_upscale_tile_size); - } - - auto parse_sample_params_json = [&](const json& sample_json, - SDSampleParams& target_params, - std::string& target_extra_sample_args, - std::optional>& target_skip_layers, - std::optional>* target_custom_sigmas) { - load_json_input(sample_json, "sample_steps", target_params.sample_steps); - load_json_input(sample_json, "eta", target_params.eta); - load_json_input(sample_json, "shifted_timestep", target_params.shifted_timestep); - load_json_input(sample_json, "flow_shift", target_params.flow_shift); - load_json_input(sample_json, "extra_sample_args", target_extra_sample_args); - if (target_custom_sigmas) - load_json_input(sample_json, "custom_sigmas", *target_custom_sigmas); - load_json_input(sample_json, "sample_method", target_params.sample_method); - load_json_input(sample_json, "scheduler", target_params.scheduler); - if (sample_json.contains("guidance") && sample_json["guidance"].is_object()) { - const json& guidance_json = sample_json["guidance"]; - load_json_input(guidance_json, "txt_cfg", target_params.guidance.txt_cfg); - load_json_input(guidance_json, "img_cfg", target_params.guidance.img_cfg); - load_json_input(guidance_json, "distilled_guidance", target_params.guidance.distilled_guidance); - if (guidance_json.contains("slg") && guidance_json["slg"].is_object()) { - const json& slg_json = guidance_json["slg"]; - load_json_input(slg_json, "layers", target_skip_layers); - load_json_input(slg_json, "layer_start", target_params.guidance.slg.layer_start); - load_json_input(slg_json, "layer_end", target_params.guidance.slg.layer_end); - load_json_input(slg_json, "scale", target_params.guidance.slg.scale); - } - } - }; - - if (j.contains("sample_params") && j["sample_params"].is_object()) { - parse_sample_params_json(j["sample_params"], sample_params, extra_sample_args, skip_layers, &custom_sigmas); - } - if (j.contains("high_noise_sample_params") && j["high_noise_sample_params"].is_object()) { - parse_sample_params_json(j["high_noise_sample_params"], - high_noise_sample_params, - high_noise_extra_sample_args, - high_noise_skip_layers, - nullptr); - } - - if (j.contains("vae_tiling_params") && j["vae_tiling_params"].is_object()) { - const json& tiling_json = j["vae_tiling_params"]; - load_json_input(tiling_json, "enabled", vae_tiling_params.enabled); - load_json_input(tiling_json, "temporal_tiling", vae_tiling_params.temporal_tiling); - load_json_input(tiling_json, "tile_size_w", vae_tiling_params.tile_size_w); - load_json_input(tiling_json, "tile_size_h", vae_tiling_params.tile_size_h); - load_json_input(tiling_json, "target_overlap", vae_tiling_params.target_overlap); - load_json_input(tiling_json, "rel_size_w", vae_tiling_params.rel_size_w); - load_json_input(tiling_json, "rel_size_h", vae_tiling_params.rel_size_h); - load_json_input(tiling_json, "extra_tiling_args", extra_tiling_args); - } - - if (!parse_lora_json_field(j, lora_path_resolver, lora_map, high_noise_lora_map)) { - LOG_ERROR("invalid lora"); - return false; - } - auto load_image = [&](const char* key, int channels, SDImageOwner& image) { - if (!parse_image_json_field(j, key, channels, image)) { - LOG_ERROR("invalid %s", key); - return false; - } - return true; - }; - if (!load_image("init_image", 0, init_image) || - !load_image("end_image", 3, end_image) || - !load_image("mask_image", 1, mask_image) || - !load_image("control_image", 3, control_image) || - !load_image("ip_adapter_image", 3, ip_adapter_image)) { - return false; - } - if (!parse_image_array_json_field(j, "ref_images", 0, ref_images) || - !parse_image_array_json_field(j, "control_frames", 3, control_frames) || - !parse_audio_array_json_field(j, "ref_audios", ref_audios) || - !parse_audio_array_json_field(j, "ref_video_audios", ref_video_audios) || - !parse_video_array_json_field(j, "ref_videos", ref_videos)) { - LOG_ERROR("invalid input image/audio/video array"); - return false; - } - - return true; -} catch (const std::exception& error) { - LOG_ERROR("invalid generation parameters: %s", error.what()); - return false; -} - -bool SDGenerationParams::extract_and_remove_lora(const std::string& lora_model_dir) { - if (lora_model_dir.empty()) { - return true; - } - static const std::regex re(R"(]+):([^>]+)>)"); - static const std::vector valid_ext = {".gguf", ".safetensors", ".pt", ".ckpt"}; - std::smatch m; - - bool missing = false; - std::string tmp = prompt; - - while (std::regex_search(tmp, m, re)) { - std::string raw_path = m[1].str(); - const std::string raw_mul = m[2].str(); - - float mul = 0.f; - try { - mul = std::stof(raw_mul); - } catch (...) { - tmp = m.suffix().str(); - prompt = std::regex_replace(prompt, re, "", std::regex_constants::format_first_only); - continue; - } - - bool is_high_noise = false; - static const std::string prefix = "|high_noise|"; - if (raw_path.rfind(prefix, 0) == 0) { - raw_path.erase(0, prefix.size()); - is_high_noise = true; - } - - fs::path final_path; - try { - if (is_absolute_path(raw_path)) { - final_path = fs::u8path(raw_path); - } else { - final_path = fs::u8path(lora_model_dir) / fs::u8path(raw_path); - } - } catch (const std::exception&) { // not UTF-8, e.g. a prompt file in another encoding - LOG_WARN("invalid lora path %s", raw_path.c_str()); - tmp = m.suffix().str(); - prompt = std::regex_replace(prompt, re, "", std::regex_constants::format_first_only); - missing = true; - continue; - } - if (!fs::exists(final_path)) { - bool found = false; - for (const auto& ext : valid_ext) { - fs::path try_path = final_path; - try_path += ext; - if (fs::exists(try_path)) { - final_path = try_path; - found = true; - break; - } - } - if (!found) { - LOG_WARN("can not found lora %s", final_path.lexically_normal().u8string().c_str()); - tmp = m.suffix().str(); - prompt = std::regex_replace(prompt, re, "", std::regex_constants::format_first_only); - missing = true; - continue; - } - } - - const std::string key = final_path.lexically_normal().u8string(); - - if (is_high_noise) - high_noise_lora_map[key] += mul; - else - lora_map[key] += mul; - - prompt = std::regex_replace(prompt, re, "", std::regex_constants::format_first_only); - - tmp = m.suffix().str(); - } - - return !missing; -} - -bool SDGenerationParams::width_and_height_are_set() const { - return width.has_value() && height.has_value(); -} - -void SDGenerationParams::set_width_and_height_if_unset(int w, int h) { - if (!width) - width = w; - if (!height) - height = h; -} - -int SDGenerationParams::get_requested_width() const { - return width.value_or(0); -} - -int SDGenerationParams::get_requested_height() const { - return height.value_or(0); -} - -bool SDGenerationParams::initialize_cache_params() { - cache_params = SDCacheParams{}; - - auto parse_named_params = [&](const std::string& opt_str) -> bool { - std::stringstream ss(opt_str); - std::string token; - while (std::getline(ss, token, ',')) { - size_t eq_pos = token.find('='); - if (eq_pos == std::string::npos) { - LOG_ERROR("error: cache option '%s' missing '=' separator", token.c_str()); - return false; - } - std::string key = token.substr(0, eq_pos); - std::string val = token.substr(eq_pos + 1); - try { - if (key == "threshold") { - if (cache_mode == "easycache" || cache_mode == "ucache") { - cache_params.reuse_threshold = std::stof(val); - } else { - cache_params.residual_diff_threshold = std::stof(val); - } - } else if (key == "start") { - cache_params.start_percent = std::stof(val); - } else if (key == "end") { - cache_params.end_percent = std::stof(val); - } else if (key == "decay") { - cache_params.error_decay_rate = std::stof(val); - } else if (key == "relative") { - cache_params.use_relative_threshold = (std::stof(val) != 0.0f); - } else if (key == "reset") { - cache_params.reset_error_on_compute = (std::stof(val) != 0.0f); - } else if (key == "Fn" || key == "fn") { - cache_params.Fn_compute_blocks = std::stoi(val); - } else if (key == "Bn" || key == "bn") { - cache_params.Bn_compute_blocks = std::stoi(val); - } else if (key == "warmup") { - if (cache_mode == "spectrum") { - cache_params.spectrum_warmup_steps = std::stoi(val); - } else { - cache_params.max_warmup_steps = std::stoi(val); - } - } else if (key == "w") { - cache_params.spectrum_w = std::stof(val); - } else if (key == "m") { - cache_params.spectrum_m = std::stoi(val); - } else if (key == "lam") { - cache_params.spectrum_lam = std::stof(val); - } else if (key == "window") { - cache_params.spectrum_window_size = std::stoi(val); - } else if (key == "flex") { - cache_params.spectrum_flex_window = std::stof(val); - } else if (key == "stop") { - cache_params.spectrum_stop_percent = std::stof(val); - } else { - LOG_ERROR("error: unknown cache parameter '%s'", key.c_str()); - return false; - } - } catch (const std::exception&) { - LOG_ERROR("error: invalid value '%s' for parameter '%s'", val.c_str(), key.c_str()); - return false; - } - } - return true; - }; - - if (!cache_mode.empty()) { - if (cache_mode == "disabled") { - cache_params.mode = "disabled"; - } else if (cache_mode == "easycache") { - cache_params.mode = "easycache"; - } else if (cache_mode == "ucache") { - cache_params.mode = "ucache"; - } else if (cache_mode == "dbcache") { - cache_params.mode = "dbcache"; - } else if (cache_mode == "taylorseer") { - cache_params.mode = "taylorseer"; - } else if (cache_mode == "cache-dit") { - cache_params.mode = "cache_dit"; - } else if (cache_mode == "spectrum") { - cache_params.mode = "spectrum"; - } else { - LOG_ERROR("error: invalid cache mode '%s'", cache_mode.c_str()); - return false; - } - } - - if (!cache_option.empty() && !parse_named_params(cache_option)) { - return false; - } - - if (cache_params.mode == "dbcache" || - cache_params.mode == "taylorseer" || - cache_params.mode == "cache_dit") { - cache_params.scm_policy_dynamic = scm_policy_dynamic; - } - - return true; -} - -bool SDGenerationParams::resolve(const std::string& lora_model_dir, const std::string& hires_upscalers_dir, bool strict, bool validate_missing_loras) { - vae_tiling_params.extra_tiling_args = extra_tiling_args.empty() ? nullptr : extra_tiling_args.c_str(); - - if (!initialize_cache_params()) { - return false; - } - - if (strict && ((batch_count && (*batch_count < 1 || *batch_count > 8)) || - (sample_params.sample_steps && (*sample_params.sample_steps < 1 || *sample_params.sample_steps > 100)))) { - LOG_ERROR("server requests require batch_count in [1, 8] and sample_steps in [1, 100]"); - return false; - } - - hires_upscaler_model_path.clear(); - resolved_hires_upscaler.clear(); - if (hires_upscaler) { - static const std::map names = { - {"None", "none"}, {"Latent", "latent"}, {"Latent (nearest)", "latent_nearest"}, {"Latent (nearest-exact)", "latent_nearest_exact"}, {"Latent (antialiased)", "latent_antialiased"}, {"Latent (bicubic)", "latent_bicubic"}, {"Latent (bicubic antialiased)", "latent_bicubic_antialiased"}, {"Lanczos", "lanczos"}, {"Nearest", "nearest"}, {"Model", "model"}}; - const auto it = names.find(*hires_upscaler); - if (it != names.end()) { - resolved_hires_upscaler = it->second; - } else if (std::any_of(names.begin(), names.end(), [&](const auto& name) { return name.second == *hires_upscaler; })) { - resolved_hires_upscaler = *hires_upscaler; - } else { - static const std::vector valid_ext = {".gguf", ".safetensors", ".pt", ".pth"}; - if (hires_enabled.value_or(false) && - !resolve_model_file_from_dir(*hires_upscaler, hires_upscalers_dir, valid_ext, "hires upscaler", hires_upscaler_model_path)) - return false; - resolved_hires_upscaler = "model"; - } - if (resolved_hires_upscaler == "none") - hires_enabled = false; - } - - prompt_with_lora = prompt; - if (!lora_model_dir.empty()) { - if (!extract_and_remove_lora(lora_model_dir) && validate_missing_loras) { - return false; - } - } - return true; -} - -/** Validates params for a generation mode; enforces mode-specific input rules. */ -bool SDGenerationParams::validate(SDMode mode) { - if (!image_preprocess.empty() && mode != IMG_GEN && mode != VID_GEN) { - LOG_ERROR("--image-preprocess requires img_gen or vid_gen mode"); - return false; - } - if (ref_video_audio_paths.size() + ref_video_audios.size() > ref_video_paths.size() + ref_videos.size()) { - LOG_ERROR("error: each --ref-video-audio needs a corresponding --ref-video"); - return false; - } - - if (mode != VID_GEN && (!ref_video_paths.empty() || !ref_video_audio_paths.empty() || !ref_audio_paths.empty() || - !ref_videos.empty() || !ref_video_audios.empty() || !ref_audios.empty())) { - LOG_ERROR("error: reference video and audio inputs require vid_gen mode"); - return false; - } - - if (upscale_repeats < 1) { - return false; - } - - if (mode == UPSCALE || mode == ADETAILER) { - if (init_image_path.length() == 0) { - LOG_ERROR("error: %s mode needs an init image (--init-img)\n", - mode == UPSCALE ? "upscale" : "adetailer"); - return false; - } - } - - if (mode == ADETAILER && ad_model_path.empty()) { - LOG_ERROR("error: adetailer mode needs a detector model (--ad-model)\n"); - return false; - } - - if (mode == IMG_GEN || mode == ADETAILER || mode == VID_GEN) { - auto opt = mode == VID_GEN ? to_video_opt() : to_image_opt(mode == ADETAILER); - if (!opt) { - LOG_ERROR("%s", sd_get_last_error()); - return false; - } - } - return true; -} - -bool SDGenerationParams::resolve_and_validate(SDMode mode, - const std::string& lora_model_dir, - const std::string& hires_upscalers_dir, - bool strict) { - if (!resolve(lora_model_dir, hires_upscalers_dir, strict, mode == CONVERT)) { - return false; - } - if (!validate(mode)) { - return false; - } - return true; -} - -static void set_sample_options(SDOptBuilder& opt, const std::string& prefix, const SDSampleParams& params, const std::optional>& layers, const std::optional>& sigmas, const std::string& extra_args) { - if (!extra_args.empty()) - opt.set_string((prefix + "args").c_str(), extra_args); - opt.set_float((prefix + "eta").c_str(), params.eta); - opt.set_float((prefix + "guidance.distilled_guidance").c_str(), params.guidance.distilled_guidance); - opt.set_float((prefix + "guidance.img_cfg").c_str(), params.guidance.img_cfg); - opt.set_float((prefix + "guidance.slg.layer_end").c_str(), params.guidance.slg.layer_end); - opt.set_float((prefix + "guidance.slg.layer_start").c_str(), params.guidance.slg.layer_start); - if (layers) - opt.set_ints((prefix + "guidance.slg.layers").c_str(), layers->data(), layers->size()); - opt.set_float((prefix + "guidance.slg.scale").c_str(), params.guidance.slg.scale); - opt.set_float((prefix + "guidance.txt_cfg").c_str(), params.guidance.txt_cfg); - opt.set_string((prefix + "method").c_str(), params.sample_method); - if (prefix == "sample.") { - opt.set_string("sample.scheduler", params.scheduler); - opt.set_float("sample.flow_shift", params.flow_shift); - opt.set_int("sample.shifted_timestep", params.shifted_timestep); - if (sigmas) - opt.set_floats((prefix + "sigmas").c_str(), sigmas->data(), sigmas->size()); - } - opt.set_int((prefix + "steps").c_str(), params.sample_steps); -} - -static void set_cache_options(SDOptBuilder& opt, const SDCacheParams& params) { - opt.set_int("cache.bn_compute_blocks", params.Bn_compute_blocks); - opt.set_float("cache.end_percent", params.end_percent); - opt.set_float("cache.error_decay_rate", params.error_decay_rate); - opt.set_int("cache.fn_compute_blocks", params.Fn_compute_blocks); - opt.set_int("cache.max_cached_steps", params.max_cached_steps); - opt.set_int("cache.max_continuous_cached_steps", params.max_continuous_cached_steps); - opt.set_int("cache.max_warmup_steps", params.max_warmup_steps); - opt.set_string("cache.mode", params.mode); - opt.set_bool("cache.reset_error_on_compute", params.reset_error_on_compute); - opt.set_float("cache.residual_diff_threshold", params.residual_diff_threshold); - opt.set_float("cache.reuse_threshold", params.reuse_threshold); - opt.set_string("cache.scm_mask", params.scm_mask); - opt.set_bool("cache.scm_policy_dynamic", params.scm_policy_dynamic); - opt.set_float("cache.spectrum_flex_window", params.spectrum_flex_window); - opt.set_float("cache.spectrum_lam", params.spectrum_lam); - opt.set_int("cache.spectrum_m", params.spectrum_m); - opt.set_float("cache.spectrum_stop_percent", params.spectrum_stop_percent); - opt.set_float("cache.spectrum_w", params.spectrum_w); - opt.set_int("cache.spectrum_warmup_steps", params.spectrum_warmup_steps); - opt.set_int("cache.spectrum_window_size", params.spectrum_window_size); - opt.set_float("cache.start_percent", params.start_percent); - opt.set_int("cache.taylorseer_n_derivatives", params.taylorseer_n_derivatives); - opt.set_int("cache.taylorseer_skip_interval", params.taylorseer_skip_interval); - opt.set_bool("cache.use_relative_threshold", params.use_relative_threshold); -} - -static void set_tiling_options(SDOptBuilder& opt, const SDTilingParams& params) { - opt.set_bool("vae_tiling.enabled", params.enabled); - opt.set_string("vae_tiling.extra_tiling_args", params.extra_tiling_args); - opt.set_float("vae_tiling.rel_size_h", params.rel_size_h); - opt.set_float("vae_tiling.rel_size_w", params.rel_size_w); - opt.set_float("vae_tiling.target_overlap", params.target_overlap); - opt.set_bool("vae_tiling.temporal_tiling", params.temporal_tiling); - opt.set_int("vae_tiling.tile_size_h", params.tile_size_h); - opt.set_int("vae_tiling.tile_size_w", params.tile_size_w); -} - -SDOptPtr SDGenerationParams::to_image_opt(bool adetail) { - lora_vec.clear(); - lora_vec.reserve(lora_map.size() + high_noise_lora_map.size()); - for (const auto& kv : lora_map) { - lora_vec.push_back({false, kv.second, kv.first.c_str()}); - } - for (const auto& kv : high_noise_lora_map) { - lora_vec.push_back({true, kv.second, kv.first.c_str()}); - } - - ref_image_views.clear(); - ref_image_views.reserve(ref_images.size()); - for (auto& ref_image : ref_images) { - ref_image_views.push_back(ref_image.get()); - } - - pm_id_image_views.clear(); - pm_id_image_views.reserve(pm_id_images.size()); - for (auto& image : pm_id_images) { - pm_id_image_views.push_back(image.get()); - } - - vae_tiling_params.extra_tiling_args = extra_tiling_args.empty() ? nullptr : extra_tiling_args.c_str(); - cache_params.scm_mask = scm_mask.empty() ? nullptr : scm_mask.c_str(); - - std::string effective_ref_image_args = ref_image_args; - if (!adetail && increase_ref_index) { - if (!effective_ref_image_args.empty()) - effective_ref_image_args += ","; - effective_ref_image_args += "ref_index_mode=increase"; - } - - SDOptBuilder opt(adetail ? sd_adetail_opt_create() : sd_img_gen_opt_create()); - opt.set_string("prompt", prompt); - opt.set_string("negative_prompt", negative_prompt); - opt.set_int("clip_skip", clip_skip); - if (!adetail) - opt.set_image("init_image", init_image.get()); - if (!adetail) - opt.set_string("ref_image_args", effective_ref_image_args); - if (!adetail) - opt.set_image("mask_image", mask_image.get()); - opt.set_int("width", width); - opt.set_int("height", height); - opt.set_float("strength", strength); - opt.set_int("seed", seed); - if (!adetail) - opt.set_int("batch_count", batch_count); - if (!adetail) - opt.set_int("qwen_image_layers", qwen_image_layers); - if (!adetail) - opt.set_image("control_image", control_image.get()); - if (!adetail) - opt.set_float("control_strength", control_strength); - if (!adetail) - opt.set_string("control_type", control_type); - if (!adetail) - opt.set_image("ip_adapter_image", ip_adapter_image.get()); - if (!adetail) - opt.set_float("ip_adapter_strength", ip_adapter_strength); - if (!adetail) - opt.set_bool("hires.enabled", hires_enabled); - if (!adetail) - opt.set_string("hires.upscaler", resolved_hires_upscaler.empty() ? hires_upscaler : std::optional(resolved_hires_upscaler)); - if (!adetail) - opt.set_string("hires.model_path", hires_upscaler_model_path); - if (!adetail) - opt.set_float("hires.scale", hires_scale); - if (!adetail) - opt.set_int("hires.target_width", hires_width); - if (!adetail) - opt.set_int("hires.target_height", hires_height); - if (!adetail) - opt.set_int("hires.steps", hires_steps); - if (!adetail) - opt.set_float("hires.denoising_strength", hires_denoising_strength); - if (!adetail) - opt.set_int("hires.upscale_tile_size", hires_upscale_tile_size); - if (circular) - opt.set_bool("circular_x", true); - else - opt.set_bool("circular_x", circular_x); - if (circular) - opt.set_bool("circular_y", true); - else - opt.set_bool("circular_y", circular_y); - opt.set_loras("loras", lora_vec.data(), lora_vec.size()); - if (!adetail) - opt.set_images("ref_images", ref_image_views.data(), ref_image_views.size()); - if (!adetail) - opt.set_images("photomaker.id_images", pm_id_image_views.data(), pm_id_image_views.size()); - if (!adetail) - opt.set_string("photomaker.id_embed_path", pm_id_embed_path); - if (!adetail) - opt.set_float("photomaker.style_strength", pm_style_strength); - if (!adetail) - opt.set_string("pulid.id_embedding_path", pulid_id_embedding_path); - if (!adetail) - opt.set_float("pulid.id_weight", pulid_id_weight); - if (!adetail) - opt.set_floats("hires.sigmas", hires_custom_sigmas); - if (!adetail) - opt.set_string("image_preprocess.rules", image_preprocess); - set_sample_options(opt, "sample.", sample_params, skip_layers, custom_sigmas, extra_sample_args); - set_cache_options(opt, cache_params); - set_tiling_options(opt, vae_tiling_params); - if (adetail) { - if (!ad_prompt.empty()) - opt.set_string("adetail.prompt", ad_prompt); - if (!ad_negative_prompt.empty()) - opt.set_string("adetail.negative_prompt", ad_negative_prompt); - opt.set_string("adetail.args", extra_ad_args); - } - return opt.finish(); -} - -SDOptPtr SDGenerationParams::to_video_opt() { - lora_vec.clear(); - lora_vec.reserve(lora_map.size() + high_noise_lora_map.size()); - for (const auto& kv : lora_map) { - lora_vec.push_back({false, kv.second, kv.first.c_str()}); - } - for (const auto& kv : high_noise_lora_map) { - lora_vec.push_back({true, kv.second, kv.first.c_str()}); - } - - control_frame_views.clear(); - control_frame_views.reserve(control_frames.size()); - for (auto& frame : control_frames) { - control_frame_views.push_back(frame.get()); - } - - ref_image_views.clear(); - ref_image_views.reserve(ref_images.size()); - for (auto& image : ref_images) { - ref_image_views.push_back(image.get()); - } - - ref_video_frame_views.clear(); - ref_video_frame_views.resize(ref_videos.size()); - ref_video_views.clear(); - ref_video_views.reserve(ref_videos.size()); - for (size_t i = 0; i < ref_videos.size(); ++i) { - auto& frame_views = ref_video_frame_views[i]; - frame_views.reserve(ref_videos[i].size()); - for (auto& frame : ref_videos[i]) { - frame_views.push_back(frame.get()); - } - SDAudio audio = i < ref_video_audios.size() ? ref_video_audios[i].get() : SDAudio{}; - ref_video_views.push_back({frame_views.empty() ? nullptr : frame_views.data(), - static_cast(frame_views.size()), - 24, - audio}); - } - - ref_audio_views.clear(); - ref_audio_views.reserve(ref_audios.size()); - for (auto& audio : ref_audios) { - ref_audio_views.push_back(audio.get()); - } - - vae_tiling_params.extra_tiling_args = extra_tiling_args.empty() ? nullptr : extra_tiling_args.c_str(); - cache_params.scm_mask = scm_mask.empty() ? nullptr : scm_mask.c_str(); - - SDOptBuilder opt(sd_vid_gen_opt_create()); - opt.set_string("prompt", prompt); - opt.set_string("negative_prompt", negative_prompt); - opt.set_int("clip_skip", clip_skip); - opt.set_image("init_image", init_image.get()); - opt.set_image("end_image", end_image.get()); - opt.set_int("width", width); - opt.set_int("height", height); - opt.set_float("moe_boundary", moe_boundary); - opt.set_float("strength", strength); - opt.set_int("seed", seed); - opt.set_int("video_frames", video_frames); - opt.set_int("fps", fps); - opt.set_float("vace_strength", vace_strength); - opt.set_bool("hires.enabled", hires_enabled); - opt.set_string("hires.upscaler", resolved_hires_upscaler.empty() ? hires_upscaler : std::optional(resolved_hires_upscaler)); - opt.set_string("hires.model_path", hires_upscaler_model_path); - opt.set_float("hires.scale", hires_scale); - opt.set_int("hires.target_width", hires_width); - opt.set_int("hires.target_height", hires_height); - opt.set_int("hires.steps", hires_steps); - opt.set_float("hires.denoising_strength", hires_denoising_strength); - opt.set_int("hires.upscale_tile_size", hires_upscale_tile_size); - if (circular) - opt.set_bool("circular_x", true); - else - opt.set_bool("circular_x", circular_x); - if (circular) - opt.set_bool("circular_y", true); - else - opt.set_bool("circular_y", circular_y); - opt.set_string("ref_image_args", ref_image_args); - opt.set_loras("loras", lora_vec.data(), lora_vec.size()); - opt.set_images("ref_images", ref_image_views.data(), ref_image_views.size()); - opt.set_videos("ref_videos", ref_video_views.data(), ref_video_views.size()); - opt.set_audios("ref_audios", ref_audio_views.data(), ref_audio_views.size()); - opt.set_frames("control_frames", control_frame_views.data(), control_frame_views.size()); - opt.set_floats("hires.sigmas", hires_custom_sigmas); - opt.set_string("image_preprocess.rules", image_preprocess); - opt.set_string("sample.scheduler", high_noise_sample_params.scheduler); - opt.set_float("sample.flow_shift", high_noise_sample_params.flow_shift); - opt.set_int("sample.shifted_timestep", high_noise_sample_params.shifted_timestep); - set_sample_options(opt, "sample.", sample_params, skip_layers, custom_sigmas, extra_sample_args); - set_sample_options(opt, "high_noise_sample.", high_noise_sample_params, high_noise_skip_layers, {}, high_noise_extra_sample_args); - set_cache_options(opt, cache_params); - set_tiling_options(opt, vae_tiling_params); - return opt.finish(); -} - -std::string SDGenerationParams::to_string() const { - const std::string sample_params_str = sample_params.sample_method.value_or("unset") + ", " + sample_params.scheduler.value_or("unset") + ", steps=" + (sample_params.sample_steps ? std::to_string(*sample_params.sample_steps) : "unset"); - const std::string high_noise_sample_params_str = high_noise_sample_params.sample_method.value_or("unset") + ", " + high_noise_sample_params.scheduler.value_or("unset") + ", steps=" + (high_noise_sample_params.sample_steps ? std::to_string(*high_noise_sample_params.sample_steps) : "unset"); - - std::ostringstream lora_ss; - lora_ss << "{\n"; - for (auto it = lora_map.begin(); it != lora_map.end(); ++it) { - lora_ss << " \"" << it->first << "\": \"" << it->second << "\""; - if (std::next(it) != lora_map.end()) { - lora_ss << ","; - } - lora_ss << "\n"; - } - lora_ss << " }"; - std::string loras_str = lora_ss.str(); - - lora_ss = std::ostringstream(); - ; - lora_ss << "{\n"; - for (auto it = high_noise_lora_map.begin(); it != high_noise_lora_map.end(); ++it) { - lora_ss << " \"" << it->first << "\": \"" << it->second << "\""; - if (std::next(it) != high_noise_lora_map.end()) { - lora_ss << ","; - } - lora_ss << "\n"; - } - lora_ss << " }"; - std::string high_noise_loras_str = lora_ss.str(); - - std::ostringstream oss; - oss << "SDGenerationParams {\n" - << " loras: \"" << loras_str << "\",\n" - << " high_noise_loras: \"" << high_noise_loras_str << "\",\n" - << " prompt: \"" << prompt << "\",\n" - << " negative_prompt: \"" << negative_prompt << "\",\n" - << " ad_model_path: \"" << ad_model_path << "\",\n" - << " ad_prompt: \"" << ad_prompt << "\",\n" - << " ad_negative_prompt: \"" << ad_negative_prompt << "\",\n" - << " extra_ad_args: \"" << extra_ad_args << "\",\n" - << " clip_skip: " << clip_skip << ",\n" - << " width: " << width << ",\n" - << " height: " << height << ",\n" - << " batch_count: " << batch_count << ",\n" - << " qwen_image_layers: " << qwen_image_layers << ",\n" - << " init_image_path: \"" << init_image_path << "\",\n" - << " end_image_path: \"" << end_image_path << "\",\n" - << " mask_image_path: \"" << mask_image_path << "\",\n" - << " control_image_path: \"" << control_image_path << "\",\n" - << " ref_image_paths: " << vec_str_to_string(ref_image_paths) << ",\n" - << " ref_video_paths: " << vec_str_to_string(ref_video_paths) << ",\n" - << " ref_video_audio_paths: " << vec_str_to_string(ref_video_audio_paths) << ",\n" - << " ref_audio_paths: " << vec_str_to_string(ref_audio_paths) << ",\n" - << " control_video_path: \"" << control_video_path << "\",\n" - << " image_preprocess: " << image_preprocess << ",\n" - << " ref_image_args: " << ref_image_args << ",\n" - << " increase_ref_index: " << (increase_ref_index ? "true" : "false") << ",\n" - << " pm_id_images_dir: \"" << pm_id_images_dir << "\",\n" - << " pm_id_embed_path: \"" << pm_id_embed_path << "\",\n" - << " pm_style_strength: " << pm_style_strength << ",\n" - << " skip_layers: " << (skip_layers ? vec_to_string(*skip_layers) : "unset") << ",\n" - << " sample_params: " << SAFE_STR(sample_params_str.c_str()) << ",\n" - << " high_noise_skip_layers: " << (high_noise_skip_layers ? vec_to_string(*high_noise_skip_layers) : "unset") << ",\n" - << " high_noise_sample_params: " << SAFE_STR(high_noise_sample_params_str.c_str()) << ",\n" - << " custom_sigmas: " << (custom_sigmas ? vec_to_string(*custom_sigmas) : "unset") << ",\n" - << " cache_mode: \"" << cache_mode << "\",\n" - << " cache_option: \"" << cache_option << "\",\n" - << " cache: " - << cache_params.mode - << " (threshold=" << cache_params.reuse_threshold - << ", start=" << cache_params.start_percent - << ", end=" << cache_params.end_percent << "),\n" - << " moe_boundary: " << moe_boundary << ",\n" - << " video_frames: " << video_frames << ",\n" - << " fps: " << fps << ",\n" - << " vace_strength: " << vace_strength << ",\n" - << " strength: " << strength << ",\n" - << " control_strength: " << control_strength << ",\n" - << " control_type: \"" << control_type << "\",\n" - << " seed: " << seed << ",\n" - << " upscale_repeats: " << upscale_repeats << ",\n" - << " upscale_tile_size: " << upscale_tile_size << ",\n" - << " hires: { enabled: " << hires_enabled - << ", upscaler: \"" << hires_upscaler << "\"" - << ", model_path: \"" << hires_upscaler_model_path << "\"" - << ", scale: " << hires_scale - << ", target_width: " << hires_width - << ", target_height: " << hires_height - << ", steps: " << hires_steps - << ", denoising_strength: " << hires_denoising_strength - << ", custom_sigmas: " << (hires_custom_sigmas ? vec_to_string(*hires_custom_sigmas) : "unset") - << ", upscale_tile_size: " << hires_upscale_tile_size << " },\n" - << " vae_tiling_params: { " - << vae_tiling_params.enabled << ", " - << vae_tiling_params.temporal_tiling << ", " - << vae_tiling_params.tile_size_w << ", " - << vae_tiling_params.tile_size_h << ", " - << vae_tiling_params.target_overlap << ", " - << vae_tiling_params.rel_size_w << ", " - << vae_tiling_params.rel_size_h << ", " - << "\"" << extra_tiling_args << "\" },\n" - << "}"; - return oss.str(); -} - -std::string version_string() { - return std::string("stable-diffusion.cpp version ") + sd_version() + ", commit " + sd_commit(); -} diff --git a/examples/common/common.h b/examples/common/common.h index eb4a043a7f..f4418adf4d 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -1,7 +1,6 @@ #ifndef __EXAMPLES_COMMON_COMMON_H__ #define __EXAMPLES_COMMON_COMMON_H__ -#include "generation_metadata.h" #include "options.h" #include @@ -23,16 +22,15 @@ std::string argv_to_utf8(int index, const char** argv); #define BOOL_STR(b) ((b) ? "true" : "false") extern const char* const modes_str[]; -#define SD_ALL_MODES_STR "img_gen, adetailer, vid_gen, convert, upscale, metadata, vid_upscale" +#define SD_ALL_MODES_STR "img_gen, vid_gen, convert, upscale, metadata, dgl" enum SDMode { IMG_GEN, - ADETAILER, VID_GEN, CONVERT, UPSCALE, METADATA, - VID_UPSCALE, + DGL, MODE_COUNT }; @@ -202,6 +200,8 @@ struct SDContextParams { bool resolve_and_validate(SDMode mode); std::string to_string() const; SDOptPtr to_context_opt(); + bool configure_dgl(sd_dgl_ctx_t* ctx) const; + bool register_rpc_devices() const; }; struct SDGenerationParams { @@ -221,7 +221,6 @@ struct SDGenerationParams { std::optional strength; std::optional control_strength; std::optional ip_adapter_strength; - bool increase_ref_index = false; bool embed_image_metadata = true; std::string init_image_path; @@ -229,7 +228,6 @@ struct SDGenerationParams { std::string mask_image_path; std::string control_image_path; std::optional control_type; - std::string ip_adapter_image_path; std::vector ref_image_paths; std::vector ref_video_paths; std::vector ref_video_audio_paths; @@ -258,16 +256,6 @@ struct SDGenerationParams { SDTilingParams vae_tiling_params; std::string extra_tiling_args; - std::string ref_image_args; - std::string image_preprocess; - - std::string pm_id_images_dir; - std::string pm_id_embed_path; - std::optional pm_style_strength; - - std::string pulid_id_embedding_path; - std::optional pulid_id_weight; - int upscale_repeats = 1; std::optional upscale_tile_size; @@ -305,7 +293,6 @@ struct SDGenerationParams { SDImageOwner mask_image; SDImageOwner control_image; SDImageOwner ip_adapter_image; - std::vector pm_id_images; std::vector control_frames; // Media views used while populating the opaque options. @@ -313,7 +300,6 @@ struct SDGenerationParams { std::vector> ref_video_frame_views; std::vector ref_video_views; std::vector ref_audio_views; - std::vector pm_id_image_views; std::vector control_frame_views; SDGenerationParams(); @@ -324,7 +310,6 @@ struct SDGenerationParams { ArgOptions get_options(); bool from_json_str(const std::string& json_str, const std::function& lora_path_resolver = {}); - bool parse_image_preprocess_json(const std::string& json_str); bool parse_prompt_images_json(const std::string& json_str); bool initialize_cache_params(); bool extract_and_remove_lora(const std::string& lora_model_dir); @@ -338,7 +323,7 @@ struct SDGenerationParams { const std::string& lora_model_dir, const std::string& hires_upscalers_dir, bool strict = false); - SDOptPtr to_image_opt(bool adetail = false); + SDOptPtr to_image_opt(); SDOptPtr to_video_opt(); std::string to_string() const; }; diff --git a/src/api/options.cpp b/src/api/options.cpp index 591cce3448..5ec536a757 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -1,5 +1,6 @@ #include "options.h" #include "core/option_types.h" +#include "core/util.h" #include "tensor.h" #include @@ -8,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -97,16 +99,6 @@ static sd_vae_format_t parse_vae_format(const char* text) { return SD_VAE_FORMAT_COUNT; } -static sd_hires_upscaler_t parse_hires_upscaler(const char* text) { - static const char* names[] = {"none", "latent", "latent_nearest", "latent_nearest_exact", - "latent_antialiased", "latent_bicubic", "latent_bicubic_antialiased", - "lanczos", "nearest", "model"}; - for (int i = 0; i < SD_HIRES_UPSCALER_COUNT; ++i) - if (strcmp(text, names[i]) == 0) - return static_cast(i); - return SD_HIRES_UPSCALER_COUNT; -} - static bool valid_sigmas(const ParamValue& value) { const auto& sigmas = std::get>(value); if (sigmas.empty()) @@ -119,11 +111,6 @@ static bool valid_sigmas(const ParamValue& value) { return true; } -static bool valid_layers(const ParamValue& value) { - const auto& layers = std::get>(value); - return std::all_of(layers.begin(), layers.end(), [](int index) { return index >= 0; }); -} - template static ParamSpec parameter(const char* key, ParamType type, int operations, Apply apply) { return {key, type, operations, [apply](const ParamValue& value, sd::OptConfig& config) { @@ -311,6 +298,7 @@ static void add_context_specs(std::vector& specs) { ctx.string("clip_vision_path", &sd::ContextConfig::clip_vision_path); ctx.integer("conditioning_cache_size", &sd::ContextConfig::conditioning_cache_size, 0, INT32_MAX); ctx.string("control_net_path", &sd::ContextConfig::control_net_path); + ctx.string("max_ram", &sd::ContextConfig::max_ram); ctx.boolean("diffusion_conv_direct", &sd::ContextConfig::diffusion_conv_direct); ctx.boolean("diffusion_flash_attn", &sd::ContextConfig::diffusion_flash_attn); ctx.boolean("disable_prefetch", &sd::ContextConfig::disable_prefetch); @@ -322,18 +310,14 @@ static void add_context_specs(std::vector& specs) { ctx.boolean("flash_attn", &sd::ContextConfig::flash_attn); ctx.boolean("force_sdxl_vae_conv_scale", &sd::ContextConfig::force_sdxl_vae_conv_scale); ctx.string("high_noise_diffusion_model_path", &sd::ContextConfig::high_noise_diffusion_model_path); - ctx.string("ip_adapter_path", &sd::ContextConfig::ip_adapter_path); ctx.number("linear_scale", &sd::ContextConfig::linear_scale, 0, std::numeric_limits::max()); ctx.string("llm_path", &sd::ContextConfig::llm_path); ctx.string("llm_vision_path", &sd::ContextConfig::llm_vision_path); ctx.choice("lora_apply_mode", &sd::ContextConfig::lora_apply_mode, str_to_lora_apply_mode, LORA_APPLY_MODE_COUNT); ctx.string("max_vram", &sd::ContextConfig::max_vram); ctx.string("model_args", &sd::ContextConfig::model_args); - ctx.for_operations(Context | Upscaler | ADetailer).string("model_path", &sd::ContextConfig::model_path); - ctx.string("motion_module_path", &sd::ContextConfig::motion_module_path); - ctx.string("photo_maker_path", &sd::ContextConfig::photo_maker_path); + ctx.for_operations(Context | Upscaler).string("model_path", &sd::ContextConfig::model_path); ctx.choice("prediction", &sd::ContextConfig::prediction, str_to_prediction, PREDICTION_COUNT, true); - ctx.string("pulid_weights_path", &sd::ContextConfig::pulid_weights_path); ctx.choice("rng_type", &sd::ContextConfig::rng_type, str_to_rng_type, RNG_TYPE_COUNT, true); ctx.string("rpc_servers", &sd::ContextConfig::rpc_servers); ctx.boolean("sage_attn", &sd::ContextConfig::sage_attn); @@ -349,116 +333,78 @@ static void add_context_specs(std::vector& specs) { ctx.choice("vae_format", &sd::ContextConfig::vae_format, parse_vae_format, SD_VAE_FORMAT_COUNT); ctx.choice("wtype", &sd::ContextConfig::wtype, str_to_sd_type, SD_TYPE_COUNT, true); - specs.push_back(parameter("backend", ParamType::String, Context | Upscaler | VidUpscaler | ADetailer, [](const std::string& value, sd::OptConfig& config) { config.context.backend = value.c_str(); config.post.video_upscaler.backend = value.c_str(); })); - specs.push_back(parameter("conv_direct_mode", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.conv_direct_mode = value.c_str(); config.post.video_upscaler.conv_direct_mode = value.c_str(); })); - specs.push_back(parameter("diffusion_model_path", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.diffusion_model_path = value.c_str(); config.post.video_upscaler.diffusion_model_path = value.c_str(); })); - specs.push_back(parameter("flash_attn_mode", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.flash_attn_mode = value.c_str(); config.post.video_upscaler.flash_attn_mode = value.c_str(); })); + specs.push_back(parameter("backend", ParamType::String, Context | Upscaler, [](const std::string& value, sd::OptConfig& config) { config.context.backend = value.c_str(); })); + specs.push_back(parameter("conv_direct_mode", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.conv_direct_mode = value.c_str(); })); + specs.push_back(parameter("diffusion_model_path", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.diffusion_model_path = value.c_str(); })); + specs.push_back(parameter("flash_attn_mode", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.flash_attn_mode = value.c_str(); })); specs.push_back(integer_parameter( - "n_threads", Context | Upscaler | VidUpscaler | ADetailer, [](const int64_t& value, sd::OptConfig& config) { config.context.n_threads = static_cast(value); config.post.video_upscaler.n_threads = static_cast(value); }, 1, INT32_MAX)); - specs.push_back(parameter("params_backend", ParamType::String, Context | Upscaler | VidUpscaler | ADetailer, [](const std::string& value, sd::OptConfig& config) { config.context.params_backend = value.c_str(); config.post.video_upscaler.params_backend = value.c_str(); })); - specs.push_back(parameter("vae_path", ParamType::String, Context | VidUpscaler, [](const std::string& value, sd::OptConfig& config) { config.context.vae_path = value.c_str(); config.post.video_upscaler.vae_path = value.c_str(); })); + "n_threads", Context | Upscaler, [](const int64_t& value, sd::OptConfig& config) { config.context.n_threads = static_cast(value); }, 1, INT32_MAX)); + specs.push_back(parameter("params_backend", ParamType::String, Context | Upscaler, [](const std::string& value, sd::OptConfig& config) { config.context.params_backend = value.c_str(); })); + specs.push_back(parameter("vae_path", ParamType::String, Context, [](const std::string& value, sd::OptConfig& config) { config.context.vae_path = value.c_str(); })); } static void add_generation_specs(std::vector& specs) { using namespace sd::api; ParamGroup img(specs, Image, [](sd::OptConfig& config) { return std::tie(config.image); }); ParamGroup vid(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video); }); - ParamGroup preprocess(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.image_preprocess, config.video.image_preprocess); }); - ParamGroup photomaker(specs, Image, [](sd::OptConfig& config) { return std::tie(config.image.pm_params); }); - ParamGroup pulid(specs, Image, [](sd::OptConfig& config) { return std::tie(config.image.pulid_params); }); img.integer("batch_count", &sd::ImageConfig::batch_count, 1, INT32_MAX); img.image("control_image", &sd::ImageConfig::control_image); img.number("control_strength", &sd::ImageConfig::control_strength, 0, std::numeric_limits::max()); img.choice("control_type", &sd::ImageConfig::control_type, str_to_sd_control_type, SD_CONTROL_TYPE_COUNT); - img.image("ip_adapter_image", &sd::ImageConfig::ip_adapter_image); - img.number("ip_adapter_strength", &sd::ImageConfig::ip_adapter_strength, 0, std::numeric_limits::max()); img.image("mask_image", &sd::ImageConfig::mask_image); img.integer("qwen_image_layers", &sd::ImageConfig::qwen_image_layers, 0, INT32_MAX); vid.frames("control_frames", &sd::VideoConfig::control_frames, &sd::VideoConfig::control_frames_size); vid.image("end_image", &sd::VideoConfig::end_image); vid.number("moe_boundary", &sd::VideoConfig::moe_boundary, 0, 1); + vid.integer("high_noise_sample.steps", &sd::VideoConfig::high_noise_steps, -1, INT32_MAX); vid.array("ref_audios", &sd::VideoConfig::ref_audios, &sd::VideoConfig::ref_audios_count); vid.array("ref_videos", &sd::VideoConfig::ref_videos, &sd::VideoConfig::ref_videos_count); vid.number("vace_strength", &sd::VideoConfig::vace_strength, 0, std::numeric_limits::max()); vid.integer("video_frames", &sd::VideoConfig::video_frames, 1, INT32_MAX); - preprocess.string("image_preprocess.rules", &sd::ImagePreprocessConfig::rules); - - photomaker.string("photomaker.id_embed_path", &sd::PhotoMakerConfig::id_embed_path); - photomaker.array("photomaker.id_images", &sd::PhotoMakerConfig::id_images, &sd::PhotoMakerConfig::id_images_count); - photomaker.number("photomaker.style_strength", &sd::PhotoMakerConfig::style_strength, 0, 100); - - pulid.string("pulid.id_embedding_path", &sd::PuLIDConfig::id_embedding_path); - pulid.number("pulid.id_weight", &sd::PuLIDConfig::id_weight, 0, std::numeric_limits::max()); - - specs.push_back(parameter("circular_x", ParamType::Bool, Image | Video | ADetail, [](const bool& value, sd::OptConfig& config) { config.image.circular_x = value; config.video.circular_x = value; })); - specs.push_back(parameter("circular_y", ParamType::Bool, Image | Video | ADetail, [](const bool& value, sd::OptConfig& config) { config.image.circular_y = value; config.video.circular_y = value; })); + specs.push_back(parameter("circular_x", ParamType::Bool, Image | Video, [](const bool& value, sd::OptConfig& config) { config.image.circular_x = value; config.video.circular_x = value; })); + specs.push_back(parameter("circular_y", ParamType::Bool, Image | Video, [](const bool& value, sd::OptConfig& config) { config.image.circular_y = value; config.video.circular_y = value; })); specs.push_back(integer_parameter( - "clip_skip", Image | Video | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.clip_skip = static_cast(value); config.video.clip_skip = static_cast(value); }, INT32_MIN, INT32_MAX)); + "clip_skip", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.clip_skip = static_cast(value); config.video.clip_skip = static_cast(value); }, INT32_MIN, INT32_MAX)); specs.push_back(integer_parameter( - "fps", Video | VidUpscale, [](const int64_t& value, sd::OptConfig& config) { config.video.fps = static_cast(value); config.post.video_upscale.fps = static_cast(value); }, 1, INT32_MAX)); + "fps", Video, [](const int64_t& value, sd::OptConfig& config) { config.video.fps = static_cast(value); }, 1, INT32_MAX)); specs.push_back(integer_parameter( - "height", Image | Video | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.height = static_cast(value); config.video.height = static_cast(value); }, 1, INT32_MAX)); + "height", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.height = static_cast(value); config.video.height = static_cast(value); }, 1, INT32_MAX)); specs.push_back(parameter("init_image", ParamType::Tensor, Image | Video, [](const TensorValue& value, sd::OptConfig& config) { config.image.init_image = sd::api::image_view(*value.tensor.get()); config.video.init_image = config.image.init_image; })); - specs.push_back(parameter("loras", ParamType::Loras, Image | Video | ADetail, [](const LoraValues& value, sd::OptConfig& config) { config.image.loras = value.items.data(); config.image.lora_count = static_cast(value.items.size()); config.video.loras = value.items.data(); config.video.lora_count = static_cast(value.items.size()); })); - specs.push_back(parameter("negative_prompt", ParamType::String, Image | Video | ADetail, [](const std::string& value, sd::OptConfig& config) { config.image.negative_prompt = value.c_str(); config.video.negative_prompt = value.c_str(); })); - specs.push_back(parameter("prompt", ParamType::String, Image | Video | ADetail, [](const std::string& value, sd::OptConfig& config) { config.image.prompt = value.c_str(); config.video.prompt = value.c_str(); })); - specs.push_back(parameter("ref_image_args", ParamType::String, Image | Video, [](const std::string& value, sd::OptConfig& config) { config.image.ref_image_args = value.c_str(); config.video.ref_image_args = value.c_str(); })); + specs.push_back(parameter("loras", ParamType::Loras, Image | Video, [](const LoraValues& value, sd::OptConfig& config) { config.image.loras = value.items.data(); config.image.lora_count = static_cast(value.items.size()); config.video.loras = value.items.data(); config.video.lora_count = static_cast(value.items.size()); })); + specs.push_back(parameter("negative_prompt", ParamType::String, Image | Video, [](const std::string& value, sd::OptConfig& config) { config.image.negative_prompt = value.c_str(); config.video.negative_prompt = value.c_str(); })); + specs.push_back(parameter("prompt", ParamType::String, Image | Video, [](const std::string& value, sd::OptConfig& config) { config.image.prompt = value.c_str(); config.video.prompt = value.c_str(); })); specs.push_back(parameter("ref_images", ParamType::Tensors, Image | Video, [](const ImageValues& value, sd::OptConfig& config) { config.image.ref_images = const_cast(value.items.data()); config.image.ref_images_count = static_cast(value.items.size()); config.video.ref_images = config.image.ref_images; config.video.ref_images_count = config.image.ref_images_count; })); - specs.push_back(integer_parameter("seed", Image | Video | VidUpscale | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.seed = static_cast(value); config.video.seed = static_cast(value); config.post.video_upscale.seed = value; })); + specs.push_back(integer_parameter("seed", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.seed = static_cast(value); config.video.seed = static_cast(value); })); specs.push_back(float_parameter( - "strength", Image | Video | ADetail, [](const double& value, sd::OptConfig& config) { config.image.strength = static_cast(value); config.video.strength = static_cast(value); }, 0, 1)); + "strength", Image | Video, [](const double& value, sd::OptConfig& config) { config.image.strength = static_cast(value); config.video.strength = static_cast(value); }, 0, 1)); specs.push_back(integer_parameter( - "width", Image | Video | ADetail, [](const int64_t& value, sd::OptConfig& config) { config.image.width = static_cast(value); config.video.width = static_cast(value); }, 1, INT32_MAX)); + "width", Image | Video, [](const int64_t& value, sd::OptConfig& config) { config.image.width = static_cast(value); config.video.width = static_cast(value); }, 1, INT32_MAX)); } static void add_sampling_specs(std::vector& specs) { using namespace sd::api; - ParamGroup high_noise(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video.high_noise_sample_params); }); - ParamGroup high_noise_guidance(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video.high_noise_sample_params.guidance); }); - ParamGroup high_noise_slg(specs, Video, [](sd::OptConfig& config) { return std::tie(config.video.high_noise_sample_params.guidance.slg); }); - ParamGroup sample(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.sample_params, config.video.sample_params); }); - ParamGroup guidance(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.sample_params.guidance, config.video.sample_params.guidance); }); - ParamGroup slg(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.sample_params.guidance.slg, config.video.sample_params.guidance.slg); }); - - high_noise.string("high_noise_sample.args", &sd::SampleConfig::extra_sample_args); - high_noise.number("high_noise_sample.eta", &sd::SampleConfig::eta, 0, std::numeric_limits::max()); - high_noise.choice("high_noise_sample.method", &sd::SampleConfig::sample_method, str_to_sample_method, SAMPLE_METHOD_COUNT, true); - high_noise.integer("high_noise_sample.steps", &sd::SampleConfig::sample_steps, -1, INT32_MAX); - - high_noise_guidance.number("high_noise_sample.guidance.distilled_guidance", &sd::GuidanceConfig::distilled_guidance); - high_noise_guidance.number("high_noise_sample.guidance.img_cfg", &sd::GuidanceConfig::img_cfg); - high_noise_guidance.number("high_noise_sample.guidance.txt_cfg", &sd::GuidanceConfig::txt_cfg); - - high_noise_slg.number("high_noise_sample.guidance.slg.layer_end", &sd::SLGConfig::layer_end, 0, 1); - high_noise_slg.number("high_noise_sample.guidance.slg.layer_start", &sd::SLGConfig::layer_start, 0, 1); - high_noise_slg.array("high_noise_sample.guidance.slg.layers", &sd::SLGConfig::layers, &sd::SLGConfig::layer_count, valid_layers, "layer indices must be nonnegative"); - high_noise_slg.number("high_noise_sample.guidance.slg.scale", &sd::SLGConfig::scale, 0, std::numeric_limits::max()); + ParamGroup sample(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.sample_params, config.video.sample_params); }); + ParamGroup guidance(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.sample_params.guidance, config.video.sample_params.guidance); }); sample.string("sample.args", &sd::SampleConfig::extra_sample_args); sample.number("sample.eta", &sd::SampleConfig::eta, 0, std::numeric_limits::max()); sample.number("sample.flow_shift", &sd::SampleConfig::flow_shift, 0, std::numeric_limits::max()); sample.choice("sample.method", &sd::SampleConfig::sample_method, str_to_sample_method, SAMPLE_METHOD_COUNT, true); sample.choice("sample.scheduler", &sd::SampleConfig::scheduler, str_to_scheduler, SCHEDULER_COUNT, true); - sample.integer("sample.shifted_timestep", &sd::SampleConfig::shifted_timestep, 0, INT32_MAX); sample.array("sample.sigmas", &sd::SampleConfig::custom_sigmas, &sd::SampleConfig::custom_sigmas_count, valid_sigmas, "sigmas require at least two strictly decreasing nonnegative entries ending in zero, or an empty array"); sample.integer("sample.steps", &sd::SampleConfig::sample_steps, 1, INT32_MAX); guidance.number("sample.guidance.distilled_guidance", &sd::GuidanceConfig::distilled_guidance); guidance.number("sample.guidance.img_cfg", &sd::GuidanceConfig::img_cfg); guidance.number("sample.guidance.txt_cfg", &sd::GuidanceConfig::txt_cfg); - - slg.number("sample.guidance.slg.layer_end", &sd::SLGConfig::layer_end, 0, 1); - slg.number("sample.guidance.slg.layer_start", &sd::SLGConfig::layer_start, 0, 1); - slg.array("sample.guidance.slg.layers", &sd::SLGConfig::layers, &sd::SLGConfig::layer_count, valid_layers, "layer indices must be nonnegative"); - slg.number("sample.guidance.slg.scale", &sd::SLGConfig::scale, 0, std::numeric_limits::max()); } static void add_cache_specs(std::vector& specs) { using namespace sd::api; - ParamGroup cache(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.cache, config.video.cache); }); + ParamGroup cache(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.cache, config.video.cache); }); cache.integer("cache.bn_compute_blocks", &sd::CacheConfig::Bn_compute_blocks, 0, INT32_MAX); cache.number("cache.end_percent", &sd::CacheConfig::end_percent, 0, 1); @@ -489,22 +435,21 @@ static void add_cache_specs(std::vector& specs) { static void add_hires_specs(std::vector& specs) { using namespace sd::api; ParamGroup hires(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.hires, config.video.hires); }); - - hires.number("hires.denoising_strength", &sd::HiresConfig::denoising_strength, 0, 1); hires.boolean("hires.enabled", &sd::HiresConfig::enabled); + hires.string("hires.upscaler", &sd::HiresConfig::upscaler); hires.string("hires.model_path", &sd::HiresConfig::model_path); - hires.number("hires.scale", &sd::HiresConfig::scale, 0, std::numeric_limits::max()); - hires.array("hires.sigmas", &sd::HiresConfig::custom_sigmas, &sd::HiresConfig::custom_sigmas_count, valid_sigmas, "sigmas require at least two strictly decreasing nonnegative entries ending in zero, or an empty array"); - hires.integer("hires.steps", &sd::HiresConfig::steps, 0, INT32_MAX); - hires.integer("hires.target_height", &sd::HiresConfig::target_height, 0, INT32_MAX); - hires.integer("hires.target_width", &sd::HiresConfig::target_width, 0, INT32_MAX); + hires.number("hires.scale", &sd::HiresConfig::scale, std::numeric_limits::min(), 64); + hires.integer("hires.target_width", &sd::HiresConfig::target_width, 0, 16384); + hires.integer("hires.target_height", &sd::HiresConfig::target_height, 0, 16384); + hires.integer("hires.steps", &sd::HiresConfig::steps, 0, 10000); + hires.number("hires.denoising_strength", &sd::HiresConfig::denoising_strength, 0.0001, 1); hires.integer("hires.upscale_tile_size", &sd::HiresConfig::upscale_tile_size, 1, INT32_MAX); - hires.choice("hires.upscaler", &sd::HiresConfig::upscaler, parse_hires_upscaler, SD_HIRES_UPSCALER_COUNT); + hires.array("hires.sigmas", &sd::HiresConfig::custom_sigmas, &sd::HiresConfig::custom_sigmas_count, valid_sigmas, "hires sigmas require at least two strictly decreasing nonnegative entries ending in zero, or an empty array"); } static void add_tiling_specs(std::vector& specs) { using namespace sd::api; - ParamGroup tiling(specs, Image | Video | ADetail, [](sd::OptConfig& config) { return std::tie(config.image.vae_tiling_params, config.video.vae_tiling_params); }); + ParamGroup tiling(specs, Image | Video, [](sd::OptConfig& config) { return std::tie(config.image.vae_tiling_params, config.video.vae_tiling_params); }); tiling.boolean("vae_tiling.enabled", &sd::TilingConfig::enabled); tiling.string("vae_tiling.extra_tiling_args", &sd::TilingConfig::extra_tiling_args); @@ -518,26 +463,23 @@ static void add_tiling_specs(std::vector& specs) { static void add_postprocess_specs(std::vector& specs) { using namespace sd::api; - ParamGroup input(specs, Upscale | ADetail, [](sd::OptConfig& config) { return std::tie(config.post); }); + ParamGroup input(specs, Upscale, [](sd::OptConfig& config) { return std::tie(config.post); }); ParamGroup upscaler(specs, Upscaler, [](sd::OptConfig& config) { return std::tie(config.post); }); - ParamGroup video_upscaler(specs, VidUpscaler, [](sd::OptConfig& config) { return std::tie(config.post.video_upscaler); }); - ParamGroup video_upscale(specs, VidUpscale, [](sd::OptConfig& config) { return std::tie(config.post.video_upscale); }); - ParamGroup adetail(specs, ADetail, [](sd::OptConfig& config) { return std::tie(config.post.adetail); }); - input.image("image", &sd::PostprocessConfig::image); - + input.integer("repeats", &sd::PostprocessConfig::repeats, 1, 16); upscaler.boolean("conv_direct", &sd::PostprocessConfig::conv_direct); upscaler.integer("tile_size", &sd::PostprocessConfig::tile_size, 1, INT32_MAX); +} - video_upscaler.integer("upscale_factor", &sd::VideoUpscalerConfig::upscale_factor, 1, INT32_MAX); - - video_upscale.frames("frames", &sd::VideoUpscaleConfig::frames, &sd::VideoUpscaleConfig::frame_count); - video_upscale.integer("window_size", &sd::VideoUpscaleConfig::window_size, 1, INT32_MAX); - video_upscale.integer("temporal_chunk_size", &sd::VideoUpscaleConfig::temporal_chunk_size, 1, INT32_MAX); - - adetail.string("adetail.prompt", &sd::ADetailConfig::prompt); - adetail.string("adetail.negative_prompt", &sd::ADetailConfig::negative_prompt); - adetail.string("adetail.args", &sd::ADetailConfig::extra_ad_args); +static bool dgl_only_parameter(const char* key) { + const std::string name = key; + if (name == "high_noise_sample.steps") + return false; + for (const auto* prefix : {"photomaker.", "pulid.", "high_noise_sample.", "sample.guidance.slg.", "adetail."}) + if (name.rfind(prefix, 0) == 0) + return true; + static const std::set names{"ip_adapter_path", "ip_adapter_image", "ip_adapter_strength", "motion_module_path", "photo_maker_path", "pulid_weights_path", "image_preprocess.rules", "sample.shifted_timestep"}; + return names.count(name) != 0; } static std::vector make_specs() { @@ -565,6 +507,8 @@ static const ParamSpec* find_spec(const char* key) { static sd_status_t check_key(sd_opt_t* params, const char* key, ParamType type, const ParamSpec** out) { if (!params || !key) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, key, "params and key are required"); + if (dgl_only_parameter(key)) + return sd::api::error(SD_STATUS_UNSUPPORTED, key, "this parameter requires an explicit DGL workflow (-M dgl --script FILE)"); *out = find_spec(key); if (!*out) return sd::api::error(SD_STATUS_UNKNOWN_KEY, key, "unknown parameter"); @@ -589,6 +533,8 @@ static sd_status_t store_value(sd_opt_t* params, const ParamSpec& spec, ParamVal if (spec.valid && !spec.valid(value)) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, spec.key, spec.invalid_reason); params->values.insert_or_assign(spec.key, std::move(value)); + if (strcmp(spec.key, "cache.fn_compute_blocks") == 0 || strcmp(spec.key, "cache.bn_compute_blocks") == 0) + LOG_WARN("parameter '%s' is ignored: condition-level caching does not support front/back block counts", spec.key); return SD_STATUS_OK; } @@ -615,22 +561,6 @@ sd_upscale_opt_t* sd_upscale_opt_create(void) { return create_opt(sd::api::Upscale); } -sd_vid_upscaler_opt_t* sd_vid_upscaler_opt_create(void) { - return create_opt(sd::api::VidUpscaler); -} - -sd_vid_upscale_opt_t* sd_vid_upscale_opt_create(void) { - return create_opt(sd::api::VidUpscale); -} - -sd_adetailer_opt_t* sd_adetailer_opt_create(void) { - return create_opt(sd::api::ADetailer); -} - -sd_adetail_opt_t* sd_adetail_opt_create(void) { - return create_opt(sd::api::ADetail); -} - void sd_opt_free(sd_opt_t* params) { delete params; } @@ -820,6 +750,8 @@ sd_status_t sd_opt_unset(sd_opt_t* params, const char* key) { return sd::api::call([&] { if (!params || !key) return sd::api::error(SD_STATUS_INVALID_ARGUMENT, key, "params and key are required"); + if (dgl_only_parameter(key)) + return sd::api::error(SD_STATUS_UNSUPPORTED, key, "this parameter requires an explicit DGL workflow (-M dgl --script FILE)"); const auto* spec = find_spec(key); if (!spec) return sd::api::error(SD_STATUS_UNKNOWN_KEY, key, "unknown parameter"); @@ -834,6 +766,96 @@ bool sd::api::is_set(const sd_opt_t* params, const char* key) { return params && params->values.count(key) != 0; } +std::shared_ptr sd::api::copy_options(const sd_opt_t* params) { + if (!params) + throw sd::dgl::Error(SD_STATUS_INVALID_ARGUMENT, "params is required"); + auto copy = std::make_shared(*params); + for (auto& [key, value] : copy->values) { + if (auto* loras = std::get_if(&value)) { + for (size_t i = 0; i < loras->items.size(); ++i) + loras->items[i].path = loras->paths[i].c_str(); + } else if (auto* embeddings = std::get_if(&value)) { + for (size_t i = 0; i < embeddings->items.size(); ++i) { + embeddings->items[i].name = embeddings->strings[i * 2].c_str(); + embeddings->items[i].path = embeddings->strings[i * 2 + 1].c_str(); + } + } else if (auto* videos = std::get_if(&value)) { + for (size_t i = 0; i < videos->items.size(); ++i) + videos->items[i].frames = videos->frames[i].data(); + } + } + return copy; +} + +std::vector sd::api::explicit_keys(const sd_opt_t* params) { + std::vector keys; + if (params) + for (const auto& [key, value] : params->values) + keys.push_back(key); + return keys; +} + +const sd_tensor_t* sd::api::bound_tensor(const sd_opt_t* params, const char* key) { + if (!params) + return nullptr; + const auto found = params->values.find(key); + if (found == params->values.end()) + return nullptr; + const auto* value = std::get_if(&found->second); + return value ? value->tensor.get() : nullptr; +} + +std::vector sd::api::bound_tensors(const sd_opt_t* params, const char* key) { + std::vector tensors; + if (!params) + return tensors; + const auto found = params->values.find(key); + if (found == params->values.end()) + return tensors; + if (const auto* values = std::get_if(&found->second)) + for (const auto& tensor : values->tensors) + tensors.push_back(tensor.get()); + return tensors; +} + +std::vector sd::api::bound_audios(const sd_opt_t* params, const char* key) { + std::vector audios; + if (params && params->values.count(key)) + if (const auto* values = std::get_if(¶ms->values.at(key))) + for (size_t i = 0; i < values->items.size(); ++i) + audios.push_back({uint32_t(values->items[i].sample_rate), values->tensors[i].get()}); + return audios; +} + +std::vector sd::api::bound_videos(const sd_opt_t* params, const char* key) { + std::vector videos; + if (params && params->values.count(key)) + if (const auto* values = std::get_if(¶ms->values.at(key))) { + size_t tensor = 0; + for (const auto& item : values->items) { + sd_video_t video{values->tensors[tensor++].get(), item.fps, {}}; + if (item.audio.data) + video.audio = {uint32_t(item.audio.sample_rate), values->tensors[tensor++].get()}; + videos.push_back(video); + } + } + return videos; +} + +nlohmann::json sd::api::scalar_values(const sd_opt_t* params) { + auto values = nlohmann::json::object(); + if (params) + for (const auto& entry : params->values) + std::visit([&](const auto& item) { + using T = std::decay_t; + if constexpr (std::is_arithmetic_v || std::is_same_v || + std::is_same_v> || std::is_same_v>) + values[entry.first] = item; + }, + entry.second); + return values; +} + bool sd::api::has_prefix(const sd_opt_t* params, const char* prefix) { if (!params) return false; @@ -847,51 +869,18 @@ sd_status_t sd::api::resolve(const sd_opt_t* params, Operation operation, OptCon if (params->operation != operation) return error(SD_STATUS_UNSUPPORTED, nullptr, "option object has the wrong purpose for this operation"); config = OptConfig{}; - if (operation == ADetail) - config.image.strength = 0.4f; for (const auto& entry : params->values) { const auto* spec = find_spec(entry.first.c_str()); - if (!(spec->operations & operation)) - return error(SD_STATUS_UNSUPPORTED, spec->key, "parameter does not apply to this operation"); + if (!spec || !(spec->operations & operation)) + return error(SD_STATUS_UNSUPPORTED, entry.first.c_str(), "parameter does not apply to this operation"); spec->apply(entry.second, config); } - const auto& image = config.image; - const auto& video = config.video; - const bool sampling = operation == Image || operation == Video || operation == ADetail; - const auto& cache = operation == Video ? video.cache : image.cache; - if (sampling && cache.mode != SD_CACHE_DISABLED) { - if (cache.start_percent >= cache.end_percent) - return error(SD_STATUS_INVALID_ARGUMENT, "cache", "start_percent must precede end_percent"); - } - if (sampling) { - const auto& sample = operation == Video ? video.sample_params : image.sample_params; - if (sample.guidance.slg.layer_start > sample.guidance.slg.layer_end) - return error(SD_STATUS_INVALID_ARGUMENT, "sample.guidance.slg", "layer_start must not exceed layer_end"); - const auto& hires = operation == Video ? video.hires : image.hires; - if (hires.enabled && hires.upscaler != SD_HIRES_UPSCALER_NONE && - hires.scale <= 0.f && hires.target_width <= 0 && hires.target_height <= 0) - return error(SD_STATUS_INVALID_ARGUMENT, "hires", "enabled hires requires a positive scale or target size"); - } - if (operation == Video && video.high_noise_sample_params.guidance.slg.layer_start > video.high_noise_sample_params.guidance.slg.layer_end) - return error(SD_STATUS_INVALID_ARGUMENT, "high_noise_sample.guidance.slg", "layer_start must not exceed layer_end"); - if ((operation == Upscaler || operation == ADetailer) && (!config.context.model_path || !*config.context.model_path)) + const auto& cache = operation == Video ? config.video.cache : config.image.cache; + if ((operation == Image || operation == Video) && cache.mode != SD_CACHE_DISABLED && cache.start_percent >= cache.end_percent) + return error(SD_STATUS_INVALID_ARGUMENT, "cache", "start_percent must precede end_percent"); + if (operation == Upscaler && (!config.context.model_path || !*config.context.model_path)) return error(SD_STATUS_INVALID_ARGUMENT, "model_path", "model path is required"); - if (operation == VidUpscaler) { - const auto& load = config.post.video_upscaler; - if (!load.diffusion_model_path || !*load.diffusion_model_path || !load.vae_path || !*load.vae_path || load.upscale_factor <= 0) - return error(SD_STATUS_INVALID_ARGUMENT, nullptr, "diffusion_model_path, vae_path and upscale_factor are required"); - } - if ((operation == Upscale || operation == ADetail) && !config.post.image.data) - return error(SD_STATUS_INVALID_ARGUMENT, "image", "input image is required"); - if (operation == Upscale && config.post.image.channel != 3) + if (operation == Upscale && (!config.post.image.data || config.post.image.channel != 3)) return error(SD_STATUS_INVALID_ARGUMENT, "image", "upscaling requires an RGB image"); - if (operation == VidUpscale) { - const auto& input = config.post.video_upscale; - if (!input.frames || input.frame_count <= 0) - return error(SD_STATUS_INVALID_ARGUMENT, "frames", "video upscaling requires nonempty frames"); - for (int i = 0; i < input.frame_count; ++i) - if (input.frames[i].channel != 3 || input.frames[i].width != input.frames[0].width || input.frames[i].height != input.frames[0].height) - return error(SD_STATUS_INVALID_ARGUMENT, "frames", "frames must be RGB and have equal dimensions"); - } return SD_STATUS_OK; } diff --git a/src/config.h b/src/config.h index 7331ccc4b9..5319863f0b 100644 --- a/src/config.h +++ b/src/config.h @@ -20,24 +20,10 @@ namespace sd { const char* extra_tiling_args; }; - struct ImagePreprocessConfig { - // Semicolon-separated target=...,key=value rules. NULL preserves defaults. - const char* rules; - }; - - struct SLGConfig { - int* layers; - size_t layer_count; - float layer_start; - float layer_end; - float scale; - }; - struct GuidanceConfig { float txt_cfg; float img_cfg; float distilled_guidance; - sd::SLGConfig slg; }; struct SampleConfig { @@ -46,7 +32,6 @@ namespace sd { enum sample_method_t sample_method; int sample_steps; float eta; - int shifted_timestep; float* custom_sigmas; int custom_sigmas_count; float flow_shift; @@ -55,18 +40,6 @@ namespace sd { SampleConfig(); }; - struct PhotoMakerConfig { - sd::Image* id_images; - int id_images_count; - const char* id_embed_path; - float style_strength; - }; - - struct PuLIDConfig { - const char* id_embedding_path; - float id_weight; - }; - struct CacheConfig { enum sd_cache_mode_t mode; float reuse_threshold; @@ -96,22 +69,6 @@ namespace sd { CacheConfig(); }; - struct HiresConfig { - bool enabled; - enum sd_hires_upscaler_t upscaler; - const char* model_path; - float scale; - int target_width; - int target_height; - int steps; - float denoising_strength; - int upscale_tile_size; - float* custom_sigmas; - int custom_sigmas_count; - - HiresConfig(); - }; - struct ContextConfig { const char* model_path{}; const char* clip_l_path{}; @@ -129,12 +86,8 @@ namespace sd { const char* audio_encoder_path{}; const char* taesd_path{}; const char* control_net_path{}; - const char* ip_adapter_path{}; - const char* motion_module_path{}; const sd_embedding_t* embeddings{}; uint32_t embedding_count{}; - const char* photo_maker_path{}; - const char* pulid_weights_path{}; const char* tensor_type_rules{}; int n_threads{}; enum sd_type_t wtype {}; @@ -150,7 +103,8 @@ namespace sd { bool vae_conv_direct{}; bool force_sdxl_vae_conv_scale{}; enum sd_vae_format_t vae_format {}; - const char* max_vram{}; // Optional per-device GiB budget for managed weights and runner buffers; 0 uses live free VRAM without an explicit budget + const char* max_vram{}; // Optional per-device GiB budget for managed weights and runner buffers; 0 uses live free VRAM without an explicit budget + const char* max_ram{}; bool disable_prefetch{}; // Disable asynchronous next-segment weight prefetch bool eager_load{}; // Load all params into the params backend at model-load time instead of lazily on first use const char* backend{}; @@ -172,6 +126,20 @@ namespace sd { ContextConfig(); }; + struct HiresConfig { + bool enabled = false; + const char* upscaler = "latent"; + const char* model_path{}; + float scale = 2.f; + int target_width{}; + int target_height{}; + int steps{}; + float denoising_strength = 0.7f; + int upscale_tile_size = 128; + float* custom_sigmas{}; + int custom_sigmas_count{}; + }; + struct ImageConfig { const sd_lora_t* loras{}; uint32_t lora_count{}; @@ -181,7 +149,6 @@ namespace sd { sd::Image init_image{}; sd::Image* ref_images{}; int ref_images_count{}; - const char* ref_image_args{}; sd::Image mask_image{}; int width{}; int height{}; @@ -191,17 +158,12 @@ namespace sd { int batch_count{}; sd::Image control_image{}; float control_strength{}; - sd::Image ip_adapter_image{}; - float ip_adapter_strength{}; - sd::PhotoMakerConfig pm_params{}; - sd::PuLIDConfig pulid_params{}; sd::TilingConfig vae_tiling_params{}; sd::CacheConfig cache{}; - sd::HiresConfig hires{}; + HiresConfig hires{}; int qwen_image_layers{}; bool circular_x{}; bool circular_y{}; - sd::ImagePreprocessConfig image_preprocess{}; enum sd_control_type_t control_type {}; ImageConfig(); @@ -226,8 +188,8 @@ namespace sd { int width{}; int height{}; sd::SampleConfig sample_params{}; - sd::SampleConfig high_noise_sample_params{}; float moe_boundary{}; + int high_noise_steps = -1; float strength{}; int64_t seed{}; int video_frames{}; @@ -235,52 +197,18 @@ namespace sd { float vace_strength{}; sd::TilingConfig vae_tiling_params{}; sd::CacheConfig cache{}; - sd::HiresConfig hires{}; + HiresConfig hires{}; bool circular_x{}; bool circular_y{}; - sd::ImagePreprocessConfig image_preprocess{}; - const char* ref_image_args{}; VideoConfig(); }; - struct VideoUpscalerConfig { - const char* diffusion_model_path{}; - const char* vae_path{}; - // Explicit output scale; RelayVSR requires 2 or 4 matching both checkpoints. - int upscale_factor{}; - int n_threads{}; - const char* backend{}; - const char* params_backend{}; - // auto/on/off or diffusion/vae assignments; null selects auto. - const char* flash_attn_mode{}; - const char* conv_direct_mode{}; - }; - - struct VideoUpscaleConfig { - const sd::Image* frames{}; - int frame_count{}; - int fps = 24; - int64_t seed = 42; - // RelayVSR reference window, including both endpoints; defaults to 16. - int window_size = 16; - // SeedVR2 independent temporal chunks in input frames (1 or 4n+1); defaults to 5. - int temporal_chunk_size = 5; - }; - - struct ADetailConfig { - const char* prompt{}; - const char* negative_prompt{}; - const char* extra_ad_args{}; - }; - struct PostprocessConfig { sd::Image image{}; bool conv_direct = false; int tile_size = 128; - VideoUpscalerConfig video_upscaler; - VideoUpscaleConfig video_upscale; - ADetailConfig adetail; + int repeats = 1; }; struct OptConfig { diff --git a/src/pipeline/video.cpp b/src/pipeline/video.cpp deleted file mode 100644 index 529bbb60ce..0000000000 --- a/src/pipeline/video.cpp +++ /dev/null @@ -1,2317 +0,0 @@ -#include "core/option_types.h" -#include "generation.h" -#include "generation_info.h" - -#include -#include -#include -#include -#include - -#include "conditioning/wan_audio.h" -#include "core/rng.hpp" -#include "core/rng_philox.hpp" -#include "diffusion_engine.h" -#include "model/diffusion/minimax_h3.hpp" -#include "model/upscaler/h3_latent_upscaler.hpp" -#include "model/upscaler/ltx_latent_upscaler.hpp" -#include "model/vae/audio_vae.hpp" -#include "model/vae/vae.hpp" -#include "request.h" -#include "runtime/denoiser.hpp" -#include "runtime/image_preprocess.h" - -namespace sd::pipeline { - - static sd::Audio* waveform_to_sd_audio(const StableDiffusionGGML* sd, - const sd::Tensor& waveform) { - if (sd == nullptr || waveform.empty()) { - return nullptr; - } - - int64_t sample_count = waveform.shape()[0]; - int64_t channels = waveform.shape().size() > 1 ? waveform.shape()[1] : 1; - if (sample_count <= 0 || channels <= 0) { - return nullptr; - } - - sd::Audio* audio = (sd::Audio*)malloc(sizeof(sd::Audio)); - if (audio == nullptr) { - return nullptr; - } - - audio->sample_rate = static_cast(sd->audio_vae_model != nullptr ? sd->audio_vae_model->output_sample_rate() : 0); - audio->channels = static_cast(channels); - audio->sample_count = static_cast(sample_count); - size_t sample_bytes = waveform.numel() * sizeof(float); - audio->data = (float*)malloc(sample_bytes); - if (audio->data == nullptr) { - free(audio); - return nullptr; - } - - auto wavaform_t = waveform.permute({1, 0, 2, 3}); - std::memcpy(audio->data, wavaform_t.data(), sample_bytes); - - return audio; - } - - static float ltxv_latent_corner_to_pixel_frame(int64_t corner_index, - int temporal_scale, - bool causal_temporal_positioning) { - float pixel_t = static_cast(corner_index * temporal_scale); - if (causal_temporal_positioning) { - pixel_t = std::max(0.f, pixel_t + 1.f - static_cast(temporal_scale)); - } - return pixel_t; - } - - static void set_ltxv_video_position(sd::Tensor* positions, - int64_t token, - float t_start, - float t_end, - float h_start, - float h_end, - float w_start, - float w_end) { - positions->index(0, 0, token, 0) = t_start; - positions->index(1, 0, token, 0) = t_end; - positions->index(0, 1, token, 0) = h_start; - positions->index(1, 1, token, 0) = h_end; - positions->index(0, 2, token, 0) = w_start; - positions->index(1, 2, token, 0) = w_end; - } - - static sd::Tensor build_ltxv_video_positions(int64_t width, - int64_t height, - int64_t target_latent_frames, - int64_t keyframe_latent_frames, - int keyframe_frame_idx, - int keyframe_pixel_frames, - int fps, - int spatial_scale, - int temporal_scale, - bool causal_temporal_positioning) { - GGML_ASSERT(width > 0 && height > 0 && target_latent_frames > 0); - GGML_ASSERT(keyframe_latent_frames > 0); - GGML_ASSERT(fps > 0); - - int64_t total_tokens = width * height * (target_latent_frames + keyframe_latent_frames); - sd::Tensor positions({2, 3, total_tokens, 1}); - int64_t token = 0; - - for (int64_t t = 0; t < target_latent_frames; t++) { - float t_start = ltxv_latent_corner_to_pixel_frame(t, temporal_scale, causal_temporal_positioning) / static_cast(fps); - float t_end = ltxv_latent_corner_to_pixel_frame(t + 1, temporal_scale, causal_temporal_positioning) / static_cast(fps); - for (int64_t h = 0; h < height; h++) { - float h_start = static_cast(h * spatial_scale); - float h_end = static_cast((h + 1) * spatial_scale); - for (int64_t w = 0; w < width; w++) { - float w_start = static_cast(w * spatial_scale); - float w_end = static_cast((w + 1) * spatial_scale); - set_ltxv_video_position(&positions, token++, t_start, t_end, h_start, h_end, w_start, w_end); - } - } - } - - for (int64_t t = 0; t < keyframe_latent_frames; t++) { - float t_start = static_cast(keyframe_frame_idx + t * temporal_scale); - float t_end = static_cast(keyframe_frame_idx + (t + 1) * temporal_scale); - if (keyframe_pixel_frames == 1) { - t_end = t_start + 1.f; - } - t_start /= static_cast(fps); - t_end /= static_cast(fps); - for (int64_t h = 0; h < height; h++) { - float h_start = static_cast(h * spatial_scale); - float h_end = static_cast((h + 1) * spatial_scale); - for (int64_t w = 0; w < width; w++) { - float w_start = static_cast(w * spatial_scale); - float w_end = static_cast((w + 1) * spatial_scale); - set_ltxv_video_position(&positions, token++, t_start, t_end, h_start, h_end, w_start, w_end); - } - } - } - - return positions; - } - - static sd::Tensor pack_ltxav_audio_and_video_latents(const sd::Tensor& video_latent, - const sd::Tensor& audio_latent) { - if (audio_latent.empty()) { - return video_latent; - } - - GGML_ASSERT(video_latent.dim() == 4 || video_latent.dim() == 5); - GGML_ASSERT(audio_latent.dim() == 3 || audio_latent.dim() == 4); - if (video_latent.dim() == 5) { - GGML_ASSERT(video_latent.shape()[4] == 1); - } - if (audio_latent.dim() == 4) { - GGML_ASSERT(audio_latent.shape()[3] == 1); - } - - int64_t width = video_latent.shape()[0]; - int64_t height = video_latent.shape()[1]; - int64_t frames = video_latent.shape()[2]; - int64_t video_ch = video_latent.shape()[3]; - int64_t spatial_size = width * height * frames; - int64_t audio_values = audio_latent.numel(); - int64_t extra_ch = (audio_values + spatial_size - 1) / spatial_size; - - std::vector packed_shape = video_latent.shape(); - packed_shape[3] = video_ch + extra_ch; - sd::Tensor packed = sd::zeros(packed_shape); - - std::copy_n(video_latent.data(), video_latent.numel(), packed.data()); - std::copy_n(audio_latent.data(), audio_latent.numel(), packed.data() + video_latent.numel()); - return packed; - } - - static sd::Tensor pack_ltxav_audio_and_video_denoise_mask(const sd::Tensor& video_mask, - const sd::Tensor& video_latent, - const sd::Tensor& audio_latent) { - if (video_mask.empty() || audio_latent.empty()) { - return video_mask; - } - - GGML_ASSERT(video_latent.dim() == 4 || video_latent.dim() == 5); - GGML_ASSERT(audio_latent.dim() == 3 || audio_latent.dim() == 4); - if (video_latent.dim() == 5) { - GGML_ASSERT(video_latent.shape()[4] == 1); - } - if (audio_latent.dim() == 4) { - GGML_ASSERT(audio_latent.shape()[3] == 1); - } - - int64_t width = video_latent.shape()[0]; - int64_t height = video_latent.shape()[1]; - int64_t frames = video_latent.shape()[2]; - int64_t video_ch = video_latent.shape()[3]; - int64_t spatial_size = width * height * frames; - int64_t audio_values = audio_latent.numel(); - int64_t extra_ch = (audio_values + spatial_size - 1) / spatial_size; - - GGML_ASSERT(video_mask.dim() == video_latent.dim()); - GGML_ASSERT(video_mask.shape()[0] == width); - GGML_ASSERT(video_mask.shape()[1] == height); - GGML_ASSERT(video_mask.shape()[2] == frames); - if (video_mask.dim() == 5) { - GGML_ASSERT(video_mask.shape()[4] == video_latent.shape()[4]); - } - - int64_t mask_ch = video_mask.shape()[3]; - if (mask_ch == video_ch + extra_ch) { - return video_mask; - } - GGML_ASSERT(mask_ch == 1 || mask_ch == video_ch); - - sd::Tensor video_mask_full = video_mask; - if (mask_ch == 1 && video_ch != 1) { - video_mask_full = video_mask * sd::Tensor::ones(video_latent.shape()); - } - - std::vector audio_mask_shape = video_latent.shape(); - audio_mask_shape[3] = extra_ch; - auto audio_mask = sd::Tensor::ones(audio_mask_shape); - return sd::ops::concat(video_mask_full, audio_mask, 3); - } - - static sd::Tensor make_ltxav_video_denoise_mask(const sd::Tensor& video_latent, float value = 1.f) { - if (video_latent.empty()) { - return {}; - } - return sd::full({video_latent.shape()[0], - video_latent.shape()[1], - video_latent.shape()[2], - 1, - 1}, - value); - } - - static sd::Tensor encode_ltxav_condition_image(StableDiffusionGGML* sd, - const sd::Tensor& image, - const char* name) { - if (sd == nullptr || image.empty()) { - return {}; - } - auto condition_image = image.reshape({image.shape()[0], - image.shape()[1], - 1, - image.shape()[2], - image.shape()[3]}); - auto condition_latent = sd->encode_first_stage(condition_image); - if (condition_latent.empty()) { - LOG_ERROR("failed to encode LTXAV %s image", name); - } - return condition_latent; - } - - static bool apply_ltxav_condition_by_latent_index(sd::Tensor* video_latent, - sd::Tensor* video_mask, - const sd::Tensor& condition_latent, - int64_t latent_idx, - const char* name, - float conditioned_mask) { - if (video_latent == nullptr || video_mask == nullptr || video_latent->empty() || video_mask->empty()) { - return false; - } - if (condition_latent.empty() || - condition_latent.shape()[0] != video_latent->shape()[0] || - condition_latent.shape()[1] != video_latent->shape()[1] || - condition_latent.shape()[3] != video_latent->shape()[3]) { - LOG_ERROR("invalid LTXAV %s condition latent shape", name); - return false; - } - int64_t latent_frames = video_latent->shape()[2]; - int64_t condition_frames = condition_latent.shape()[2]; - if (latent_idx < 0 || condition_frames <= 0 || latent_idx + condition_frames > latent_frames) { - LOG_ERROR("invalid LTXAV %s image latent range: start=%" PRId64 ", length=%" PRId64 ", latent_frames=%" PRId64, - name, - latent_idx, - condition_frames, - latent_frames); - return false; - } - - sd::ops::slice_assign(video_latent, 2, latent_idx, latent_idx + condition_frames, condition_latent); - sd::ops::fill_slice(video_mask, 2, latent_idx, latent_idx + condition_frames, conditioned_mask); - return true; - } - - static bool apply_ltxav_condition_image_by_latent_index(StableDiffusionGGML* sd, - const sd::Tensor& image, - sd::Tensor* video_latent, - sd::Tensor* video_mask, - int64_t latent_idx, - const char* name, - float strength) { - auto condition_latent = encode_ltxav_condition_image(sd, image, name); - return !condition_latent.empty() && - apply_ltxav_condition_by_latent_index(video_latent, - video_mask, - condition_latent, - latent_idx, - name, - 1.0f - std::clamp(strength, 0.f, 1.f)); - } - - static sd::Tensor unpack_ltxav_audio_latent(const sd::Tensor& packed_latent, - int audio_length, - int video_channels) { - if (packed_latent.empty() || audio_length <= 0) { - return {}; - } - - GGML_ASSERT(packed_latent.dim() == 4 || packed_latent.dim() == 5); - int64_t width = packed_latent.shape()[0]; - int64_t height = packed_latent.shape()[1]; - int64_t frames = packed_latent.shape()[2]; - int64_t total_channels = packed_latent.shape()[3]; - int64_t spatial_size = width * height * frames; - if (total_channels <= video_channels) { - return {}; - } - - constexpr int kLtxavAudioFrequencyBins = 16; - constexpr int kLtxavAudioChannels = 8; - int64_t required_values = static_cast(audio_length) * kLtxavAudioFrequencyBins * kLtxavAudioChannels; - int64_t packed_values = (total_channels - video_channels) * spatial_size; - if (packed_values < required_values) { - return {}; - } - - sd::Tensor audio_latent({kLtxavAudioFrequencyBins, audio_length, kLtxavAudioChannels, 1}); - const float* audio_src = packed_latent.data() + static_cast(video_channels) * static_cast(spatial_size); - std::copy_n(audio_src, static_cast(required_values), audio_latent.data()); - return audio_latent; - } - - static sd::Tensor make_ltxav_empty_audio_latent(int audio_length) { - if (audio_length <= 0) { - return {}; - } - constexpr int kLtxavAudioFrequencyBins = 16; - constexpr int kLtxavAudioChannels = 8; - return sd::zeros({kLtxavAudioFrequencyBins, audio_length, kLtxavAudioChannels, 1}); - } - - static sd::Tensor resize_ltxav_audio_latent(const sd::Tensor& audio_latent, - int target_audio_length) { - auto resized = make_ltxav_empty_audio_latent(target_audio_length); - if (resized.empty() || audio_latent.empty()) { - return resized; - } - GGML_ASSERT(audio_latent.dim() == 3 || audio_latent.dim() == 4); - int copy_length = std::min(static_cast(audio_latent.shape()[1]), target_audio_length); - if (copy_length > 0) { - auto copied = sd::ops::slice(audio_latent, 1, 0, copy_length); - sd::ops::slice_assign(&resized, 1, 0, copy_length, copied); - } - return resized; - } - - static int get_ltxav_num_audio_latents(int frames, int fps) { - GGML_ASSERT(frames > 0); - GGML_ASSERT(fps > 0); - constexpr float kSampleRate = 16000.0f; - constexpr float kMelHopLength = 160.0f; - constexpr float kAudioLatentDownsample = 4.0f; - constexpr float kLatentsPerSecond = kSampleRate / kMelHopLength / kAudioLatentDownsample; - return static_cast(std::ceil((static_cast(frames) / static_cast(fps)) * kLatentsPerSecond)); - } - - static int get_minimax_h3_num_audio_latents(int frames, int fps) { - GGML_ASSERT(frames > 0 && fps > 0); - return std::max(1, - static_cast(std::lround( - static_cast(frames) * 40.0 / fps))); - } - - static sd::Tensor make_minimax_h3_empty_audio_latent(int audio_length) { - if (audio_length <= 0) { - return {}; - } - return sd::zeros({audio_length, 2, 32, 1}); - } - - static sd::Tensor prepare_minimax_h3_reference_waveform(const sd::Audio& audio, - int target_sample_rate = 32000) { - if (audio.data == nullptr || audio.sample_count == 0 || audio.channels == 0 || audio.sample_rate == 0) { - return {}; - } - uint64_t output_samples = static_cast(std::llround( - static_cast(audio.sample_count) * target_sample_rate / audio.sample_rate)); - output_samples = std::max(1, output_samples); - uint64_t padded_samples = (output_samples + 799) / 800 * 800; - // Keep stereo streams planar for the mono-per-stream audio encoder: - // [samples, 1, stereo, batch]. This avoids flattening interleaved L/R - // storage into alternating samples when the encoder folds streams into - // its batch dimension. - sd::Tensor waveform({static_cast(padded_samples), 1, 2, 1}); - - for (uint64_t i = 0; i < output_samples; ++i) { - long double source_pos = static_cast(i) * audio.sample_rate / target_sample_rate; - uint64_t source0 = std::min(static_cast(source_pos), audio.sample_count - 1); - uint64_t source1 = std::min(source0 + 1, audio.sample_count - 1); - float fraction = static_cast(source_pos - source0); - for (uint32_t channel = 0; channel < 2; ++channel) { - uint32_t source_channel = audio.channels == 1 ? 0 : std::min(channel, audio.channels - 1); - float a = audio.data[source0 * audio.channels + source_channel]; - float b = audio.data[source1 * audio.channels + source_channel]; - waveform.index(static_cast(i), 0, channel, 0) = - std::clamp(a + (b - a) * fraction, -1.f, 1.f); - } - } - return waveform; - } - - static sd::Tensor unpack_minimax_h3_audio_latent(const sd::Tensor& packed_latent, - int audio_length, - int video_channels) { - if (packed_latent.empty() || audio_length <= 0) { - return {}; - } - GGML_ASSERT(packed_latent.dim() == 4 || packed_latent.dim() == 5); - int64_t spatial_size = packed_latent.shape()[0] * packed_latent.shape()[1] * packed_latent.shape()[2]; - int64_t required = static_cast(audio_length) * 2 * 32; - int64_t available = (packed_latent.shape()[3] - video_channels) * spatial_size; - if (available < required) { - return {}; - } - sd::Tensor audio({audio_length, 2, 32, 1}); - const float* source = packed_latent.data() + - static_cast(video_channels) * static_cast(spatial_size); - std::copy_n(source, static_cast(required), audio.data()); - return audio; - } - - // Build the first 16 fps audio window, zero-padding past the track end. - static sd::Tensor build_s2v_audio_window(const sd::Tensor& stacked, int64_t batch_frames) { - const int64_t embed_dim = stacked.shape()[0]; - const int64_t in_frames = stacked.shape()[1]; - const int64_t num_layers = stacked.shape()[2]; - if (embed_dim <= 0 || in_frames <= 0 || num_layers <= 0 || batch_frames <= 0) { - return {}; - } - std::vector layer_first(static_cast(num_layers) * in_frames * embed_dim); - for (int64_t l = 0; l < num_layers; ++l) { - for (int64_t f = 0; f < in_frames; ++f) { - const float* src = stacked.data() + l * embed_dim * in_frames + f * embed_dim; - std::copy_n(src, - static_cast(embed_dim), - layer_first.data() + (static_cast(l) * in_frames + f) * embed_dim); - } - } - sd::wan_audio::BucketPlan plan; - std::vector buckets = sd::wan_audio::build_audio_buckets(layer_first.data(), - static_cast(num_layers), - static_cast(in_frames), - static_cast(embed_dim), - static_cast(batch_frames), - &plan); - if (buckets.empty() || plan.bucket_frames < batch_frames) { - return {}; - } - // Reorder frame-major buckets into sd::Tensor's [dim, frame, layer] layout. - sd::Tensor window({embed_dim, batch_frames, num_layers}); - for (int64_t f = 0; f < batch_frames; ++f) { - for (int64_t l = 0; l < num_layers; ++l) { - const float* src = buckets.data() + (static_cast(f) * num_layers + l) * embed_dim; - float* dst = window.data() + l * embed_dim * batch_frames + f * embed_dim; - std::copy_n(src, static_cast(embed_dim), dst); - } - } - return window; - } - - // ComfyUI-compatible reference sizing: per-axis rounding to 32 px keeps the reference - // divisible by VAE 16 x patch 2 without padding in the H3 graph. Both modes round rather - // than floor: flooring would under-size in-limit references and diverge from the - // upstream node, which rounds in both branches. - static std::pair minimax_h3_reference_size(int source_w, - int source_h, - int target_w, - int target_h, - RefImageSizeMode mode) { - constexpr double kCanvasMultiple = 32.0; - constexpr double kRefImageShortEdge = 2048.0; - double scale = 1.0; - if (mode == RefImageSizeMode::MAX) { - scale = std::min(1.0, kRefImageShortEdge / std::min(source_w, source_h)); - } else { - double source_area = static_cast(source_w) * source_h; - double target_area = static_cast(target_w) * target_h; - scale = std::min(1.0, std::sqrt(target_area / source_area)); - } - auto align32 = [kCanvasMultiple](double value) { - return std::max(32, static_cast(std::round(value / kCanvasMultiple)) * 32); - }; - return {align32(source_w * scale), align32(source_h * scale)}; - } - - static std::optional prepare_video_generation_latents(StableDiffusionGGML* sd, - const sd::VideoConfig* sd_vid_gen_params, - GenerationRequest* request, - const RefImageParams& ref_image_params) { - ImageGenerationLatents latents; - int64_t prepare_start_ms = ggml_time_ms(); - - sd::Tensor start_image; - sd::Tensor end_image; - - if (sd_vid_gen_params->init_image.data) { - start_image = ensure_image_tensor_channels( - sd_image_to_tensor(sd_vid_gen_params->init_image, request->width, request->height), - sd->get_image_channels()); - } - - if (sd_vid_gen_params->end_image.data) { - end_image = ensure_image_tensor_channels( - sd_image_to_tensor(sd_vid_gen_params->end_image, request->width, request->height), - sd->get_image_channels()); - } - - if (sd_version_is_minimax_h3(sd->version)) { - if (sd_vid_gen_params->ref_images_count < 0 || sd_vid_gen_params->ref_videos_count < 0 || - sd_vid_gen_params->ref_audios_count < 0 || - (sd_vid_gen_params->ref_images_count > 0 && sd_vid_gen_params->ref_images == nullptr) || - (sd_vid_gen_params->ref_videos_count > 0 && sd_vid_gen_params->ref_videos == nullptr) || - (sd_vid_gen_params->ref_audios_count > 0 && sd_vid_gen_params->ref_audios == nullptr)) { - LOG_ERROR("invalid MiniMax-H3 Ref2VA input arrays"); - return std::nullopt; - } - - latents.audio_length = get_minimax_h3_num_audio_latents(request->frames, - request->fps); - latents.audio_latent = make_minimax_h3_empty_audio_latent(latents.audio_length); - - bool has_references = sd_vid_gen_params->ref_images_count > 0 || - sd_vid_gen_params->ref_videos_count > 0 || - sd_vid_gen_params->ref_audios_count > 0; - if (has_references && (!start_image.empty() || !end_image.empty())) { - LOG_ERROR("MiniMax-H3 keyframes and Ref2VA references cannot be used together"); - return std::nullopt; - } - - if (sd_vid_gen_params->control_frames_size > 0) { - LOG_ERROR("MiniMax-H3 control_frames are not implemented"); - return std::nullopt; - } - - auto add_visual_noise = [&](sd::Tensor latent) { - auto condition_rng = std::make_shared(); - condition_rng->manual_seed(static_cast(request->seed)); - return latent * MiniMaxH3::VISUAL_COND_TIMESTEP + - sd::Tensor::randn_like(latent, condition_rng) * - (1.f - MiniMaxH3::VISUAL_COND_TIMESTEP); - }; - - auto add_keyframe = [&](const sd::Tensor& image, - int32_t frame_index, - const char* name) -> bool { - if (image.empty()) { - return true; - } - auto video_image = image.reshape({image.shape()[0], - image.shape()[1], - 1, - image.shape()[2], - image.shape()[3]}); - auto latent = sd->encode_first_stage(video_image); - if (latent.empty()) { - LOG_ERROR("failed to encode MiniMax-H3 %s keyframe", name); - return false; - } - latents.ref_images.push_back(image); - latents.ref_latents.push_back(add_visual_noise(std::move(latent))); - latents.keyframe_indices.push_back(frame_index); - return true; - }; - - auto resize_reference = [&](const sd::Tensor& image, - int width, - int height) { - return sd::ops::interpolate( - image, - std::vector{width, height, image.shape()[2], image.shape()[3]}); - }; - - auto encode_reference_audio = [&](const sd::Audio& audio, - int32_t* audio_index) -> bool { - if (sd->audio_vae_model == nullptr) { - LOG_ERROR("MiniMax-H3 Ref2VA audio requires --audio-vae with encoder weights"); - return false; - } - auto waveform = prepare_minimax_h3_reference_waveform( - audio, - sd->audio_vae_model->input_sample_rate()); - if (waveform.empty()) { - LOG_ERROR("invalid MiniMax-H3 reference audio"); - return false; - } - auto encoded = sd->audio_vae_model->encode(sd->n_threads, waveform); - if (encoded.empty()) { - LOG_ERROR("failed to encode MiniMax-H3 reference audio"); - return false; - } - *audio_index = static_cast(latents.reference_audio_latents.size()); - latents.reference_audio_latents.push_back(std::move(encoded)); - return true; - }; - - if (has_references) { - LOG_INFO("MiniMax-H3 Ref2VA: %d image(s), %d video(s), %d audio clip(s)", - sd_vid_gen_params->ref_images_count, - sd_vid_gen_params->ref_videos_count, - sd_vid_gen_params->ref_audios_count); - - int64_t ref_image_tokens = 0; - for (int i = 0; i < sd_vid_gen_params->ref_images_count; ++i) { - auto image = ensure_image_tensor_channels( - sd_image_to_tensor(sd_vid_gen_params->ref_images[i]), - 3); - if (image.empty()) { - LOG_ERROR("failed to load MiniMax-H3 reference image %d", i + 1); - return std::nullopt; - } - int source_w = static_cast(image.shape()[0]); - int source_h = static_cast(image.shape()[1]); - auto [width, height] = - minimax_h3_reference_size(source_w, source_h, request->width, request->height, ref_image_params.ref_image_size); - LOG_INFO("MiniMax-H3 reference image %d: %dx%d -> %dx%d", - i + 1, - source_w, - source_h, - width, - height); - image = resize_reference(image, width, height); - auto latent = sd->encode_first_stage(image); - if (latent.empty()) { - LOG_ERROR("failed to encode MiniMax-H3 reference image %d", i + 1); - return std::nullopt; - } - int32_t video_index = static_cast(latents.ref_latents.size()); - latents.ref_latents.push_back(add_visual_noise(std::move(latent))); - latents.minimax_reference_blocks.push_back({MiniMaxH3ReferenceKind::IMAGE, - video_index, - -1}); - // The DiT patchifies latents 2 x 2, so the token count is a quarter of the - // latent grid. - ref_image_tokens += static_cast(latents.ref_latents.back().shape()[0] / 2) * - (latents.ref_latents.back().shape()[1] / 2); - MiniMaxH3PresentationItem item; - item.kind = MiniMaxH3PresentationKind::IMAGE; - item.frames.push_back(std::move(image)); - latents.minimax_presentation_refs.push_back(std::move(item)); - } - - for (int video_idx = 0; video_idx < sd_vid_gen_params->ref_videos_count; ++video_idx) { - const auto& reference = sd_vid_gen_params->ref_videos[video_idx]; - if (reference.frames == nullptr || reference.frame_count < 1) { - LOG_ERROR("invalid MiniMax-H3 reference video %d", video_idx + 1); - return std::nullopt; - } - int source_fps = reference.fps > 0 ? reference.fps : 24; - int normalized_frames = static_cast(std::lround( - static_cast(reference.frame_count) * 24.0 / source_fps)); - normalized_frames = std::min(normalized_frames, request->frames); - if (normalized_frames < 5) { - LOG_ERROR("MiniMax-H3 reference video %d needs at least 5 frames at 24 fps", - video_idx + 1); - return std::nullopt; - } - while (normalized_frames % 17 != 5) { - --normalized_frames; - } - - auto first = ensure_image_tensor_channels(sd_image_to_tensor(reference.frames[0]), 3); - if (first.empty()) { - LOG_ERROR("invalid first frame in MiniMax-H3 reference video %d", video_idx + 1); - return std::nullopt; - } - int source_w = static_cast(first.shape()[0]); - int source_h = static_cast(first.shape()[1]); - double ratio = static_cast(source_w) / source_h; - double nominal_w = ratio >= 1.0 ? 768.0 * ratio : 768.0; - double nominal_h = ratio >= 1.0 ? 768.0 : 768.0 / ratio; - if (nominal_w * nominal_h > 768.0 * 1344.0) { - double scale = std::sqrt((768.0 * 1344.0) / (nominal_w * nominal_h)); - nominal_w *= scale; - nominal_h *= scale; - } - int width = std::max(32, static_cast(std::round(nominal_w / 32.0)) * 32); - int height = std::max(32, static_cast(std::round(nominal_h / 32.0)) * 32); - if (source_w * source_h < width * height) { - width = std::max(32, static_cast(std::round(source_w / 32.0)) * 32); - height = std::max(32, static_cast(std::round(source_h / 32.0)) * 32); - } - - sd::Tensor video({width, height, normalized_frames, 3, 1}); - for (int frame = 0; frame < normalized_frames; ++frame) { - int source_index = std::min(reference.frame_count - 1, - static_cast(std::floor(frame * source_fps / 24.0))); - auto source = ensure_image_tensor_channels( - sd_image_to_tensor(reference.frames[source_index]), - 3); - if (source.empty()) { - LOG_ERROR("invalid frame %d in MiniMax-H3 reference video %d", - source_index + 1, - video_idx + 1); - return std::nullopt; - } - source = resize_reference(source, width, height); - sd::ops::slice_assign(&video, 2, frame, frame + 1, source.unsqueeze(2)); - } - auto video_latent = sd->encode_first_stage(video); - if (video_latent.empty()) { - LOG_ERROR("failed to encode MiniMax-H3 reference video %d", video_idx + 1); - return std::nullopt; - } - int32_t audio_index = -1; - bool has_audio = reference.audio.data != nullptr && reference.audio.sample_count > 0; - if (has_audio) { - if (!encode_reference_audio(reference.audio, &audio_index)) { - return std::nullopt; - } - MiniMaxH3PresentationItem audio_item; - audio_item.kind = MiniMaxH3PresentationKind::AUDIO; - latents.minimax_presentation_refs.push_back(std::move(audio_item)); - } - - MiniMaxH3PresentationItem video_item; - video_item.kind = MiniMaxH3PresentationKind::VIDEO; - for (int frame = 0; frame < normalized_frames; frame += 12) { - auto sampled = sd::ops::slice(video, 2, frame, frame + 1) - .reshape({width, height, 3, 1}); - video_item.frames.push_back(std::move(sampled)); - video_item.timestamps.push_back(frame / 24.f); - } - latents.minimax_presentation_refs.push_back(std::move(video_item)); - - int32_t video_index = static_cast(latents.ref_latents.size()); - latents.ref_latents.push_back(add_visual_noise(std::move(video_latent))); - latents.minimax_reference_blocks.push_back({has_audio ? MiniMaxH3ReferenceKind::VIDEO_AUDIO - : MiniMaxH3ReferenceKind::VIDEO, - video_index, - audio_index}); - } - - for (int audio_idx = 0; audio_idx < sd_vid_gen_params->ref_audios_count; ++audio_idx) { - int32_t encoded_index = -1; - if (!encode_reference_audio(sd_vid_gen_params->ref_audios[audio_idx], &encoded_index)) { - return std::nullopt; - } - MiniMaxH3PresentationItem item; - item.kind = MiniMaxH3PresentationKind::AUDIO; - latents.minimax_presentation_refs.push_back(std::move(item)); - latents.minimax_reference_blocks.push_back({MiniMaxH3ReferenceKind::AUDIO, - -1, - encoded_index}); - } - - if (ref_image_tokens > 0) { - int64_t target_tokens = sd->get_image_seq_len(request->width, request->height) / 4 * - sd->video_frames_to_latent_frames(request->frames); - if (target_tokens > 0 && ref_image_tokens > target_tokens * 4) { - LOG_WARN("MiniMax-H3 reference images add %" PRId64 - " tokens versus %" PRId64 - " for the generated video; sampling cost scales with every attended token", - ref_image_tokens, - target_tokens); - } - } - } - - if (!has_references && (!start_image.empty() || !end_image.empty())) { - LOG_INFO(!start_image.empty() && !end_image.empty() ? "MiniMax-H3 FL2VA" : !start_image.empty() ? "MiniMax-H3 I2VA" - : "MiniMax-H3 end-frame conditioning"); - } - if (!has_references && - (!add_keyframe(start_image, 0, "start") || - !add_keyframe(end_image, request->frames - 1, "end"))) { - return std::nullopt; - } - } - - if (sd_version_is_ltxav(sd->version)) { - latents.audio_length = get_ltxav_num_audio_latents(request->frames, request->fps); - latents.audio_latent = make_ltxav_empty_audio_latent(latents.audio_length); - } - - if (sd_version_is_ltxav(sd->version)) { - if (sd_vid_gen_params->control_frames_size > 0) { - LOG_ERROR("LTXAV control_frames are not implemented"); - return std::nullopt; - } - - if (!start_image.empty() || !end_image.empty()) { - if (!start_image.empty() && !end_image.empty()) { - LOG_INFO("FLF2V"); - } else if (!start_image.empty()) { - LOG_INFO("IMG2VID"); - } else { - LOG_INFO("END2VID"); - } - - int64_t t1 = ggml_time_ms(); - latents.init_latent = sd->generate_init_latent(request->width, request->height, request->frames, true); - - float conditioning_strength = std::clamp(request->strength, 0.f, 1.f); - float conditioned_mask = 1.0f - conditioning_strength; - latents.denoise_mask = make_ltxav_video_denoise_mask(latents.init_latent, 1.f); - - auto apply_video_condition_by_keyframe_index = [&](const sd::Tensor& keyframes, - int frame_idx, - const char* name) -> bool { - int64_t keyframe_frames = keyframes.shape()[2]; - if (keyframe_frames <= 0 || keyframes.shape()[0] != latents.init_latent.shape()[0] || - keyframes.shape()[1] != latents.init_latent.shape()[1] || - keyframes.shape()[3] != latents.init_latent.shape()[3]) { - LOG_ERROR("invalid LTXAV %s keyframe latent shape", name); - return false; - } - - latents.video_target_frame_count = latents.init_latent.shape()[2]; - latents.video_conditioning_frame_count = keyframe_frames; - latents.init_latent = sd::ops::concat(latents.init_latent, keyframes, 2); - - auto keyframe_mask = sd::full({keyframes.shape()[0], - keyframes.shape()[1], - keyframes.shape()[2], - 1, - 1}, - conditioned_mask); - latents.denoise_mask = sd::ops::concat(latents.denoise_mask, keyframe_mask, 2); - latents.video_positions = build_ltxv_video_positions(latents.init_latent.shape()[0], - latents.init_latent.shape()[1], - latents.video_target_frame_count, - keyframe_frames, - frame_idx, - 1, - request->fps, - request->vae_scale_factor, - 8, - true); - return true; - }; - - if (!start_image.empty()) { - if (!apply_ltxav_condition_image_by_latent_index(sd, - start_image, - &latents.init_latent, - &latents.denoise_mask, - 0, - "init", - conditioning_strength)) { - return std::nullopt; - } - } - - if (!end_image.empty()) { - auto end_image_latent = encode_ltxav_condition_image(sd, end_image, "end"); - if (end_image_latent.empty()) { - return std::nullopt; - } - - int frame_idx = request->frames - 1; - bool ok = frame_idx == 0 ? apply_ltxav_condition_by_latent_index(&latents.init_latent, - &latents.denoise_mask, - end_image_latent, - 0, - "end", - conditioned_mask) - : apply_video_condition_by_keyframe_index(end_image_latent, frame_idx, "end"); - if (!ok) { - return std::nullopt; - } - } - - int64_t t2 = ggml_time_ms(); - LOG_INFO("encode_first_stage completed, taking %" PRId64 " ms", t2 - t1); - } - } - - if (sd_version_is_hunyuan_video(sd->version) && - (!start_image.empty() || !end_image.empty())) { - LOG_INFO("Hunyuan Video IMG2VID"); - - int64_t t1 = ggml_time_ms(); - auto concat_latent = sd->generate_init_latent(request->width, - request->height, - request->frames, - true); - auto encode_condition_frame = [&](const sd::Tensor& image, - int64_t latent_frame, - const char* name) -> bool { - auto encoded = sd->encode_first_stage(image.unsqueeze(2)); - if (encoded.empty()) { - LOG_ERROR("failed to encode Hunyuan Video %s conditioning frame", name); - return false; - } - if (encoded.dim() == 4) { - encoded.unsqueeze_(2); - } - if (encoded.dim() != 5 || - encoded.shape()[0] != concat_latent.shape()[0] || - encoded.shape()[1] != concat_latent.shape()[1] || - encoded.shape()[3] != concat_latent.shape()[3]) { - LOG_ERROR("invalid Hunyuan Video %s conditioning latent shape", name); - return false; - } - sd::ops::slice_assign(&concat_latent, - 2, - latent_frame, - latent_frame + 1, - sd::ops::slice(encoded, 2, 0, 1)); - return true; - }; - - if (!start_image.empty() && !encode_condition_frame(start_image, 0, "start")) { - return std::nullopt; - } - if (!end_image.empty() && - !encode_condition_frame(end_image, concat_latent.shape()[2] - 1, "end")) { - return std::nullopt; - } - - sd::Tensor concat_mask = sd::zeros({concat_latent.shape()[0], - concat_latent.shape()[1], - concat_latent.shape()[2], - 1, - 1}); - if (!start_image.empty()) { - sd::ops::fill_slice(&concat_mask, 2, 0, 1, 1.0f); - } - if (!end_image.empty()) { - sd::ops::fill_slice(&concat_mask, 2, concat_mask.shape()[2] - 1, concat_mask.shape()[2], 1.0f); - } - latents.concat_latent = sd::ops::concat(concat_latent, concat_mask, 3); - - int64_t t2 = ggml_time_ms(); - LOG_INFO("encode_first_stage completed, taking %" PRId64 " ms", t2 - t1); - } - - if (sd->diffusion_model->get_desc() == "Wan2.1-I2V-14B" || - sd->diffusion_model->get_desc() == "Wan2.2-I2V-14B" || - sd->diffusion_model->get_desc() == "Wan2.1-I2V-1.3B" || - sd->diffusion_model->get_desc() == "Wan2.1-FLF2V-14B") { - LOG_INFO("IMG2VID"); - - if (sd->diffusion_model->get_desc() == "Wan2.1-I2V-14B" || - sd->diffusion_model->get_desc() == "Wan2.1-I2V-1.3B" || - sd->diffusion_model->get_desc() == "Wan2.1-FLF2V-14B") { - if (!start_image.empty()) { - auto clip_vision_output = sd->get_clip_vision_output(start_image, false, -2); - if (clip_vision_output.empty()) { - LOG_ERROR("failed to compute clip vision output for init image"); - return std::nullopt; - } - latents.clip_vision_output = std::move(clip_vision_output); - } else { - latents.clip_vision_output = sd->get_clip_vision_output(start_image, false, -2, true); - } - - if (sd->diffusion_model->get_desc() == "Wan2.1-FLF2V-14B") { - sd::Tensor end_image_clip_vision_output; - if (!end_image.empty()) { - end_image_clip_vision_output = sd->get_clip_vision_output(end_image, false, -2); - if (end_image_clip_vision_output.empty()) { - LOG_ERROR("failed to compute clip vision output for end image"); - return std::nullopt; - } - } else { - end_image_clip_vision_output = sd->get_clip_vision_output(end_image, false, -2, true); - } - latents.clip_vision_output = sd::ops::concat(latents.clip_vision_output, end_image_clip_vision_output, 1); - } - - int64_t t1 = ggml_time_ms(); - LOG_INFO("get_clip_vision_output completed, taking %" PRId64 " ms", t1 - prepare_start_ms); - } - - int64_t t1 = ggml_time_ms(); - sd::Tensor image = sd::full({request->width, request->height, request->frames, 3, 1}, 0.5f); - if (!start_image.empty()) { - sd::ops::slice_assign(&image, 2, 0, 1, start_image.unsqueeze(2)); - } - if (!end_image.empty()) { - sd::ops::slice_assign(&image, 2, request->frames - 1, request->frames, end_image.unsqueeze(2)); - } - - auto concat_latent = sd->encode_first_stage(image); // [b, c, t, h/vae_scale_factor, w/vae_scale_factor] - if (concat_latent.empty()) { - LOG_ERROR("failed to encode video conditioning frames"); - return std::nullopt; - } - latents.concat_latent = std::move(concat_latent); - - int64_t t2 = ggml_time_ms(); - LOG_INFO("encode_first_stage completed, taking %" PRId64 " ms", t2 - t1); - - sd::Tensor concat_mask = sd::zeros({latents.concat_latent.shape()[0], - latents.concat_latent.shape()[1], - latents.concat_latent.shape()[2], - 4, - 1}); // [b, 4, t, h/vae_scale_factor, w/vae_scale_factor] - if (!start_image.empty()) { - sd::ops::fill_slice(&concat_mask, 2, 0, 1, 1.0f); - } - if (!end_image.empty()) { - auto last_channel = sd::ops::slice(concat_mask, 3, 3, 4); - sd::ops::fill_slice(&last_channel, 2, last_channel.shape()[2] - 1, last_channel.shape()[2], 1.0f); - sd::ops::slice_assign(&concat_mask, 3, 3, 4, last_channel); - } - latents.concat_latent = sd::ops::concat(concat_mask, latents.concat_latent, 3); // [b, 4+c, t, h/vae_scale_factor, w/vae_scale_factor] - } else if (sd->diffusion_model->get_desc() == "Wan2.2-TI2V-5B" && !start_image.empty()) { - LOG_INFO("IMG2VID"); - - int64_t t1 = ggml_time_ms(); - auto init_img = start_image.reshape({start_image.shape()[0], start_image.shape()[1], 1, start_image.shape()[2], 1}); - auto init_image_latent = sd->encode_first_stage(init_img); // [b, c, 1, h/vae_scale_factor, w/vae_scale_factor] - if (init_image_latent.empty()) { - LOG_ERROR("failed to encode init video frame"); - return std::nullopt; - } - - latents.init_latent = sd->generate_init_latent(request->width, request->height, request->frames, true); // [b, c, t, h/vae_scale_factor, w/vae_scale_factor] - sd::ops::slice_assign(&latents.init_latent, 2, 0, init_image_latent.shape()[2], init_image_latent); - - latents.denoise_mask = sd::full({latents.init_latent.shape()[0], latents.init_latent.shape()[1], latents.init_latent.shape()[2], 1, 1}, 1.f); - sd::ops::fill_slice(&latents.denoise_mask, 2, 0, init_image_latent.shape()[2], 0.0f); - - if (!end_image.empty()) { - auto end_img = end_image.reshape({end_image.shape()[0], end_image.shape()[1], 1, end_image.shape()[2], 1}); - auto end_image_latent = sd->encode_first_stage(end_img); // [b, c, 1, h/vae_scale_factor, w/vae_scale_factor] - if (end_image_latent.empty()) { - LOG_ERROR("failed to encode end video frame"); - return std::nullopt; - } - sd::ops::slice_assign(&latents.init_latent, 2, latents.init_latent.shape()[2] - 1, latents.init_latent.shape()[2], end_image_latent); - sd::ops::fill_slice(&latents.denoise_mask, 2, latents.init_latent.shape()[2] - 1, latents.init_latent.shape()[2], 0.0f); - } - - int64_t t2 = ggml_time_ms(); - LOG_INFO("encode_first_stage completed, taking %" PRId64 " ms", t2 - t1); - } else if (sd_version_is_lingbot_video(sd->version) && !start_image.empty()) { - LOG_INFO("LingBot Video IMG2VID"); - - int64_t t1 = ggml_time_ms(); - auto init_img = start_image.reshape({start_image.shape()[0], start_image.shape()[1], 1, start_image.shape()[2], 1}); - auto init_image_latent = sd->encode_first_stage(init_img); - if (init_image_latent.empty()) { - LOG_ERROR("failed to encode init video frame"); - return std::nullopt; - } - - latents.init_latent = sd->generate_init_latent(request->width, request->height, request->frames, true); - sd::ops::slice_assign(&latents.init_latent, 2, 0, init_image_latent.shape()[2], init_image_latent); - - latents.denoise_mask = sd::full({latents.init_latent.shape()[0], latents.init_latent.shape()[1], latents.init_latent.shape()[2], 1, 1}, 1.f); - sd::ops::fill_slice(&latents.denoise_mask, 2, 0, init_image_latent.shape()[2], 0.0f); - - latents.ref_images.push_back(start_image); - - int64_t t2 = ggml_time_ms(); - LOG_INFO("encode_first_stage completed, taking %" PRId64 " ms", t2 - t1); - } else if (sd->diffusion_model->get_desc() == "Wan2.1-VACE-1.3B" || - sd->diffusion_model->get_desc() == "Wan2.x-VACE-14B") { - LOG_INFO("VACE"); - int64_t t1 = ggml_time_ms(); - sd::Tensor ref_image_latent; - if (!start_image.empty()) { - auto ref_img = start_image.reshape({start_image.shape()[0], start_image.shape()[1], 1, start_image.shape()[2], 1}); - auto encoded_ref = sd->encode_first_stage(ref_img); // [b, c, 1, h/vae_scale_factor, w/vae_scale_factor] - if (encoded_ref.empty()) { - LOG_ERROR("failed to encode VACE reference image"); - return std::nullopt; - } - ref_image_latent = sd::ops::concat(encoded_ref, sd::zeros(encoded_ref.shape()), 3); // [b, 2*c, 1, h/vae_scale_factor, w/vae_scale_factor] - } - - sd::Tensor control_video = sd::full({request->width, request->height, request->frames, 3, 1}, 0.5f); - int64_t control_frame_count = std::min(request->frames, sd_vid_gen_params->control_frames_size); - for (int64_t i = 0; i < control_frame_count; ++i) { - auto control_frame = sd_image_to_tensor(sd_vid_gen_params->control_frames[i], request->width, request->height); - sd::ops::slice_assign(&control_video, 2, i, i + 1, control_frame.unsqueeze(2)); - } - - sd::Tensor mask = sd::full({request->width, request->height, request->frames, 1, 1}, 1.0f); - - control_video = control_video - 0.5f; - sd::Tensor inactive = control_video * (1.0f - mask) + 0.5f; - sd::Tensor reactive = control_video * mask + 0.5f; - - inactive = sd->encode_first_stage(inactive); // [b, c, t, h/vae_scale_factor, w/vae_scale_factor] - if (inactive.empty()) { - LOG_ERROR("failed to encode VACE inactive context"); - return std::nullopt; - } - - reactive = sd->encode_first_stage(reactive); // [b, c, t, h/vae_scale_factor, w/vae_scale_factor] - if (reactive.empty()) { - LOG_ERROR("failed to encode VACE reactive context"); - return std::nullopt; - } - - int64_t length = inactive.shape()[2]; - if (!ref_image_latent.empty()) { - length += 1; - request->frames = static_cast((length - 1) * 4 + 1); - latents.ref_image_num = 1; - } - auto vace_context = sd::ops::concat(inactive, reactive, 3); // [b, 2*c, t, h/vae_scale_factor, w/vae_scale_factor] - - mask = sd::full({request->width, request->height, inactive.shape()[2], 1, 1}, 1.0f); - auto mask_context = mask.reshape({request->vae_scale_factor, - inactive.shape()[0], - request->vae_scale_factor, - inactive.shape()[1], - inactive.shape()[2]}); // [t, h/vae_scale_factor, vae_scale_factor, w/vae_scale_factor, vae_scale_factor] - mask_context = mask_context.permute({1, 3, 4, 0, 2}) // [vae_scale_factor, vae_scale_factor, t, h/vae_scale_factor, w/vae_scale_factor] - .reshape({inactive.shape()[0], - inactive.shape()[1], - inactive.shape()[2], - request->vae_scale_factor * request->vae_scale_factor}); // [vae_scale_factor*vae_scale_factor, t, h/vae_scale_factor, w/vae_scale_factor] - - if (!ref_image_latent.empty()) { - vace_context = sd::ops::concat(ref_image_latent, vace_context, 2); // [b, 2*c, t+1, h/vae_scale_factor, w/vae_scale_factor] - auto mask_pad = sd::zeros({mask_context.shape()[0], - mask_context.shape()[1], - 1, - mask_context.shape()[3]}); // [vae_scale_factor*vae_scale_factor, 1, h/vae_scale_factor, w/vae_scale_factor] - mask_context = sd::ops::concat(mask_pad, mask_context, 2); // [vae_scale_factor*vae_scale_factor, t + 1, h/vae_scale_factor, w/vae_scale_factor] - } - - mask_context.unsqueeze_(mask_context.dim()); // [b, vae_scale_factor*vae_scale_factor, t + 1 or t, h/vae_scale_factor, w/vae_scale_factor] - - latents.vace_context = sd::ops::concat(vace_context, mask_context, 3); // [b, 2*c + vae_scale_factor*vae_scale_factor, t + 1 or t, h/vae_scale_factor, w/vae_scale_factor] - int64_t t2 = ggml_time_ms(); - LOG_INFO("encode_first_stage completed, taking %" PRId64 " ms", t2 - t1); - } else if (sd->diffusion_model->get_desc() == "Wan2.2-S2V-14B") { - LOG_INFO("S2V"); - if (!end_image.empty()) { - LOG_WARN("Wan2.2 S2V ignores end_image"); - } - if (sd_vid_gen_params->ref_audios_count > 1) { - LOG_ERROR("Wan2.2 S2V supports a single driving audio track"); - return std::nullopt; - } - int64_t t1 = ggml_time_ms(); - if (!start_image.empty()) { - auto ref_img = start_image.reshape({start_image.shape()[0], - start_image.shape()[1], - 1, - start_image.shape()[2], - 1}); - auto encoded_ref = sd->encode_first_stage(ref_img); - if (encoded_ref.empty()) { - LOG_ERROR("failed to encode S2V reference image"); - return std::nullopt; - } - // Wan consumes reference latents in 4D. - latents.ref_latents.push_back(encoded_ref.reshape({encoded_ref.shape()[0], - encoded_ref.shape()[1], - encoded_ref.shape()[2], - encoded_ref.shape()[3]})); - } - if (sd_vid_gen_params->ref_audios_count == 1) { - if (sd->audio_encoder == nullptr) { - LOG_ERROR("S2V audio conditioning requires --audio-encoder (wav2vec2)"); - return std::nullopt; - } - auto stacked = sd->get_audio_embedding(sd_vid_gen_params->ref_audios[0]); - if (stacked.empty()) { - LOG_ERROR("failed to compute wav2vec2 embedding for driving audio"); - return std::nullopt; - } - int64_t latent_t = sd->video_frames_to_latent_frames(request->frames); - int64_t batch_frames = latent_t * 4; - latents.s2v_audio_embed = build_s2v_audio_window(stacked, batch_frames); - if (latents.s2v_audio_embed.empty()) { - LOG_ERROR("failed to build S2V audio window"); - return std::nullopt; - } - } - int64_t t2 = ggml_time_ms(); - LOG_INFO("s2v conditioning prepared, taking %" PRId64 " ms", t2 - t1); - } - - if (latents.init_latent.empty()) { - latents.init_latent = sd->generate_init_latent(request->width, request->height, request->frames, true); - } - - if ((sd_version_is_ltxav(sd->version) || sd_version_is_minimax_h3(sd->version)) && - !latents.audio_latent.empty()) { - if (!latents.denoise_mask.empty()) { - latents.denoise_mask = pack_ltxav_audio_and_video_denoise_mask(latents.denoise_mask, - latents.init_latent, - latents.audio_latent); - } - latents.init_latent = pack_ltxav_audio_and_video_latents(latents.init_latent, latents.audio_latent); - } - - return latents; - } - - static std::optional prepare_video_generation_embeds(StableDiffusionGGML* sd, - const sd::VideoConfig* sd_vid_gen_params, - const GenerationRequest& request, - const ImageGenerationLatents& latents, - const RefImageParams& ref_image_params) { - ConditionerRunnerEndOnExit conditioner_runner_end{sd->cond_stage_model.get()}; - - ImageGenerationEmbeds embeds; - ConditionerParams condition_params; - condition_params.clip_skip = request.clip_skip; - condition_params.text = request.prompt; - condition_params.zero_out_masked = true; - condition_params.ref_images = &latents.ref_images; - condition_params.minimax_h3_references = &latents.minimax_presentation_refs; - condition_params.ref_image_params = ref_image_params; - - int64_t prepare_start_ms = ggml_time_ms(); - sd->generation_progress.report("conditioning", "positive_prompt"); - embeds.cond = sd->get_learned_condition(condition_params); - if (embeds.cond.empty()) { - LOG_ERROR("failed to encode video prompt"); - return std::nullopt; - } - embeds.cond.c_concat = latents.concat_latent; - embeds.cond.c_vector = latents.clip_vision_output; - if (sd_version_is_minimax_h3(sd->version)) { - embeds.cond.c_ref_images = latents.ref_latents; - embeds.cond.c_ref_audios = latents.reference_audio_latents; - embeds.cond.c_reference_blocks = latents.minimax_reference_blocks; - if (!latents.keyframe_indices.empty()) { - embeds.cond.c_position_ids = sd::Tensor( - {static_cast(latents.keyframe_indices.size())}, - latents.keyframe_indices); - } - } - if (sd->version == VERSION_WAN2_2_S2V) { - embeds.cond.c_ref_images = latents.ref_latents; - if (!latents.s2v_audio_embed.empty()) { - embeds.cond.c_ref_audios = {latents.s2v_audio_embed}; - } - } - if (request.use_uncond) { - condition_params.text = request.negative_prompt; - sd->generation_progress.report("conditioning", "negative_prompt"); - embeds.uncond = sd->get_learned_condition(condition_params); - if (embeds.uncond.empty()) { - LOG_ERROR("failed to encode negative video prompt"); - return std::nullopt; - } - embeds.uncond.c_concat = latents.concat_latent; - embeds.uncond.c_vector = latents.clip_vision_output; - if (sd_version_is_minimax_h3(sd->version)) { - embeds.uncond.c_ref_images = latents.ref_latents; - embeds.uncond.c_ref_audios = latents.reference_audio_latents; - embeds.uncond.c_reference_blocks = latents.minimax_reference_blocks; - embeds.uncond.c_position_ids = embeds.cond.c_position_ids; - } - if (sd->version == VERSION_WAN2_2_S2V) { - embeds.uncond.c_ref_images = latents.ref_latents; - if (!latents.s2v_audio_embed.empty()) { - embeds.uncond.c_ref_audios = {sd::Tensor::zeros_like(latents.s2v_audio_embed)}; - } - } - } - - int64_t t1 = ggml_time_ms(); - LOG_INFO("get_learned_condition completed, taking %.2fs", (t1 - prepare_start_ms) * 1.0f / 1000); - - return embeds; - } - - static sd::Image* decode_video_outputs(StableDiffusionGGML* sd, - const GenerationRequest& request, - const sd::Tensor& final_latent, - int* num_frames_out) { - if (final_latent.empty()) { - LOG_ERROR("no latent video to decode"); - return nullptr; - } - if (sd->get_cancel_flag() == SD_CANCEL_ALL) { - LOG_ERROR("cancelling video decode"); - return nullptr; - } - sd::Tensor video_latent = final_latent; - if ((sd_version_is_ltxav(sd->version) || sd_version_is_minimax_h3(sd->version)) && - video_latent.shape()[3] > sd->get_latent_channel()) { - video_latent = sd::ops::slice(video_latent, 3, 0, sd->get_latent_channel()); - } - LOG_VERBOSE("decode_video_outputs latent %dx%dx%dx%d", - (int)video_latent.shape()[0], - (int)video_latent.shape()[1], - (int)video_latent.shape()[2], - (int)video_latent.shape()[3]); - // auto z = sd::load_tensor_from_file_as_tensor("ltx_vae_z.bin"); - int64_t t4 = ggml_time_ms(); - sd::Tensor vid = sd->decode_first_stage(video_latent, true); - int64_t t5 = ggml_time_ms(); - LOG_INFO("decode_first_stage completed, taking %.2fs", (t5 - t4) * 1.0f / 1000); - if (vid.empty()) { - LOG_ERROR("decode_first_stage failed for video"); - return nullptr; - } - LOG_VERBOSE("decode_video_outputs decoded %dx%dx%dx%d", - (int)vid.shape()[0], - (int)vid.shape()[1], - (int)vid.shape()[2], - (int)vid.shape()[3]); - if (request.frames > 0 && - vid.shape()[2] > request.frames) { - vid = sd::ops::slice(vid, 2, 0, request.frames); - } - - sd::Image* result_images = (sd::Image*)calloc(vid.shape()[2], sizeof(sd::Image)); - if (result_images == nullptr) { - return nullptr; - } - if (num_frames_out != nullptr) { - *num_frames_out = static_cast(vid.shape()[2]); - } - - for (int64_t i = 0; i < vid.shape()[2]; i++) { - result_images[i] = tensor_to_sd_image(vid, static_cast(i)); - } - - return result_images; - } - - static bool hires_upscaler_is_latent_interpolation(enum sd_hires_upscaler_t upscaler) { - switch (upscaler) { - case SD_HIRES_UPSCALER_LATENT: - case SD_HIRES_UPSCALER_LATENT_NEAREST: - case SD_HIRES_UPSCALER_LATENT_NEAREST_EXACT: - case SD_HIRES_UPSCALER_LATENT_ANTIALIASED: - case SD_HIRES_UPSCALER_LATENT_BICUBIC: - case SD_HIRES_UPSCALER_LATENT_BICUBIC_ANTIALIASED: - return true; - default: - return false; - } - } - - static sd::ops::InterpolateMode hires_latent_interpolate_mode(enum sd_hires_upscaler_t upscaler, - bool* antialias) { - if (antialias != nullptr) { - *antialias = false; - } - switch (upscaler) { - case SD_HIRES_UPSCALER_LATENT_NEAREST: - return sd::ops::InterpolateMode::Nearest; - case SD_HIRES_UPSCALER_LATENT_NEAREST_EXACT: - return sd::ops::InterpolateMode::NearestExact; - case SD_HIRES_UPSCALER_LATENT_BICUBIC: - return sd::ops::InterpolateMode::Bicubic; - case SD_HIRES_UPSCALER_LATENT_BICUBIC_ANTIALIASED: - if (antialias != nullptr) { - *antialias = true; - } - return sd::ops::InterpolateMode::Bicubic; - case SD_HIRES_UPSCALER_LATENT_ANTIALIASED: - if (antialias != nullptr) { - *antialias = true; - } - return sd::ops::InterpolateMode::Bilinear; - default: - return sd::ops::InterpolateMode::Bilinear; - } - } - - static sd::Tensor upscale_spatial_video_latent(StableDiffusionGGML* sd, - const GenerationRequest& request, - const sd::Tensor& packed_latent, - int audio_length) { - if (sd == nullptr || packed_latent.empty()) { - return {}; - } - if (packed_latent.dim() != 4 && packed_latent.dim() != 5) { - LOG_ERROR("video latent spatial upscale expects a 4D or 5D latent"); - return {}; - } - int64_t target_width = request.hires.target_width / request.vae_scale_factor; - int64_t target_height = request.hires.target_height / request.vae_scale_factor; - if (target_width <= 0 || target_height <= 0) { - LOG_ERROR("video latent spatial upscale target must be positive: %dx%d", - request.hires.target_width, - request.hires.target_height); - return {}; - } - if (packed_latent.shape()[0] == target_width && packed_latent.shape()[1] == target_height) { - LOG_DEBUG("video latent spatial upscale: target equals the draft latent size, skipping"); - return packed_latent; - } - - int latent_channels = sd->get_latent_channel(); - sd::Tensor video_latent = packed_latent; - sd::Tensor audio_latent; - if (packed_latent.shape()[3] > latent_channels) { - video_latent = sd::ops::slice(packed_latent, 3, 0, latent_channels); - audio_latent = sd_version_is_minimax_h3(sd->version) - ? unpack_minimax_h3_audio_latent(packed_latent, audio_length, latent_channels) - : unpack_ltxav_audio_latent(packed_latent, audio_length, latent_channels); - if (audio_latent.empty()) { - LOG_ERROR("failed to unpack audio latent before spatial latent upscale"); - return {}; - } - } - - bool antialias = false; - auto mode = hires_latent_interpolate_mode(request.hires.upscaler, &antialias); - std::vector target_shape = video_latent.shape(); - target_shape[0] = target_width; - target_shape[1] = target_height; - - LOG_INFO("video latent %s spatial upscale: %" PRId64 "x%" PRId64 "x%" PRId64 "x%" PRId64 " -> %" PRId64 "x%" PRId64 "x%" PRId64 "x%" PRId64, - sd_hires_upscaler_name(request.hires.upscaler), - (int64_t)video_latent.shape()[0], - (int64_t)video_latent.shape()[1], - (int64_t)video_latent.shape()[2], - (int64_t)video_latent.shape()[3], - target_shape[0], - target_shape[1], - target_shape[2], - target_shape[3]); - - sd::Tensor upscaled = sd::ops::interpolate(video_latent, target_shape, mode, false, antialias); - if (upscaled.empty()) { - LOG_ERROR("video latent spatial upscale failed"); - return {}; - } - if (audio_latent.empty()) { - return upscaled; - } - return pack_ltxav_audio_and_video_latents(upscaled, audio_latent); - } - - sd::Tensor upscale_h3_learned_video_latent(StableDiffusionGGML* sd, - const char* model_path, - const sd::Tensor& packed_latent, - int audio_length, - int64_t target_width, - int64_t target_height) { - if (sd == nullptr || sd->model_manager == nullptr || packed_latent.empty()) { - return {}; - } - if (strlen(SAFE_STR(model_path)) == 0) { - LOG_ERROR("H3 learned latent upscale requires a hires model path"); - return {}; - } - // The learned network is not an identity mapping at scale 1. - if (packed_latent.shape()[0] == target_width && packed_latent.shape()[1] == target_height) { - LOG_DEBUG("H3 learned latent upscale: target equals the draft latent size, skipping"); - return packed_latent; - } - if (!sd->ensure_backend_pair(SDBackendModule::UPSCALER)) { - return {}; - } - - int latent_channels = sd->get_latent_channel(); - sd::Tensor video_latent = packed_latent; - sd::Tensor audio_latent; - if (packed_latent.shape()[3] > latent_channels) { - video_latent = sd::ops::slice(packed_latent, 3, 0, latent_channels); - audio_latent = unpack_minimax_h3_audio_latent(packed_latent, audio_length, latent_channels); - if (audio_latent.empty()) { - LOG_ERROR("failed to unpack H3 audio latent before learned latent upscale"); - return {}; - } - } - - LOG_INFO("H3 learned latent spatial upscale: latent %dx%dx%dx%d -> %" PRId64 "x%" PRId64 " model output", - (int)video_latent.shape()[0], - (int)video_latent.shape()[1], - (int)video_latent.shape()[2], - (int)video_latent.shape()[3], - target_width, - target_height); - - if (sd->first_stage_model) { - sd->first_stage_model->runner_end(); - } - - auto model_manager = sd->model_manager; - struct UpsamplerScope { - ModelManager& manager; - ModelLoader::FileId owned_source = 0; - std::unique_ptr runner; - std::vector params; - - ~UpsamplerScope() { - if (runner) { - runner->runner_end(); - } - GGML_ASSERT(manager.unregister_param_tensors(params)); - if (owned_source != 0) { - GGML_ASSERT(manager.del_file(owned_source)); - } - } - } scope{*model_manager}; - - const std::string prefix = "h3_latent_upscaler"; - ModelLoader candidate = model_manager->loader(); - ModelLoader::FileId source_file = 0; - if (!candidate.add_file(model_path, prefix + ".", &source_file)) { - LOG_ERROR("init H3 latent upsampler model loader from file failed: '%s'", model_path); - return {}; - } - const bool owns_source = model_manager->loader().file_revision(source_file) == 0; - if (!model_manager->set_loader(std::move(candidate))) { - return {}; - } - scope.owned_source = owns_source ? source_file : 0; - - auto& upsampler = scope.runner; - upsampler = std::make_unique(sd->backend_for(SDBackendModule::UPSCALER), - model_manager->loader().get_tensor_storage_map(), - prefix, - model_manager); - const size_t max_graph_vram_bytes = sd->max_graph_vram_bytes_for_module(SDBackendModule::UPSCALER); - upsampler->set_max_graph_vram_bytes(max_graph_vram_bytes); - if (upsampler->model == nullptr) { - LOG_ERROR("init H3 latent upsampler from metadata failed"); - return {}; - } - - std::map tensors; - upsampler->get_param_tensors(tensors); - for (const auto& entry : tensors) { - scope.params.push_back(entry.second); - } - if (!model_manager->register_param_tensors(ModelComponent::LatentUpsampler, - std::move(tensors), - ModelManager::ResidencyMode::ParamBackend, - sd->backend_for(SDBackendModule::UPSCALER), - sd->params_backend_for(SDBackendModule::UPSCALER)) || - !model_manager->validate_registered_tensors()) { - LOG_ERROR("register H3 latent upsampler tensors with model manager failed"); - return {}; - } - - sd::Tensor upscaled = upsampler->compute(sd->n_threads, video_latent, target_width, target_height); - upsampler->runner_end(); - if (upscaled.empty()) { - LOG_ERROR("H3 learned latent spatial upscale failed"); - return {}; - } - - if (!audio_latent.empty()) { - upscaled = pack_ltxav_audio_and_video_latents(upscaled, audio_latent); - } - return upscaled; - } - - sd::Tensor upscale_ltx_spatial_video_latent(StableDiffusionGGML* sd, - const char* model_path, - const sd::Tensor& packed_latent, - int audio_length) { - if (sd == nullptr || sd->model_manager == nullptr || packed_latent.empty()) { - return {}; - } - if (strlen(SAFE_STR(model_path)) == 0) { - LOG_ERROR("LTX latent spatial upscale requires a model path"); - return {}; - } - if (!sd->ensure_backend_pair(SDBackendModule::UPSCALER)) { - return {}; - } - - int latent_channels = sd->get_latent_channel(); - sd::Tensor video_latent = packed_latent; - sd::Tensor audio_latent; - if (packed_latent.shape()[3] > latent_channels) { - video_latent = sd::ops::slice(packed_latent, 3, 0, latent_channels); - audio_latent = unpack_ltxav_audio_latent(packed_latent, audio_length, latent_channels); - } - - LOG_INFO("LTX latent spatial upscale: latent %dx%dx%dx%d -> model output", - (int)video_latent.shape()[0], - (int)video_latent.shape()[1], - (int)video_latent.shape()[2], - (int)video_latent.shape()[3]); - - sd::Tensor unnormalized = sd->un_normalize_ltx_video_latents(video_latent); - if (sd->first_stage_model) { - sd->first_stage_model->runner_end(); - } - if (unnormalized.empty()) { - LOG_ERROR("LTX latent un-normalization failed before spatial upscale"); - return {}; - } - - auto model_manager = sd->model_manager; - struct UpsamplerScope { - ModelManager& manager; - ModelLoader::FileId owned_source = 0; - std::unique_ptr runner; - std::vector params; - - ~UpsamplerScope() { - if (runner) { - runner->runner_end(); - } - GGML_ASSERT(manager.unregister_param_tensors(params)); - if (owned_source != 0) { - GGML_ASSERT(manager.del_file(owned_source)); - } - } - } scope{*model_manager}; - - const std::string prefix = "ltx_latent_upsampler"; - ModelLoader candidate = model_manager->loader(); - ModelLoader::FileId source_file = 0; - if (!candidate.add_file(model_path, prefix + ".", &source_file)) { - LOG_ERROR("init LTX latent upsampler model loader from file failed: '%s'", model_path); - return {}; - } - const bool owns_source = model_manager->loader().file_revision(source_file) == 0; - if (!model_manager->set_loader(std::move(candidate))) { - return {}; - } - scope.owned_source = owns_source ? source_file : 0; - - auto& upsampler = scope.runner; - upsampler = std::make_unique(sd->backend_for(SDBackendModule::UPSCALER), - model_manager->loader().get_tensor_storage_map(), - prefix, - model_manager); - const size_t max_graph_vram_bytes = sd->max_graph_vram_bytes_for_module(SDBackendModule::UPSCALER); - upsampler->set_max_graph_vram_bytes(max_graph_vram_bytes); - if (upsampler->model == nullptr) { - LOG_ERROR("init LTX latent upsampler from metadata failed"); - return {}; - } - - std::map tensors; - upsampler->get_param_tensors(tensors); - for (const auto& entry : tensors) { - scope.params.push_back(entry.second); - } - if (!model_manager->register_param_tensors(ModelComponent::LatentUpsampler, - std::move(tensors), - ModelManager::ResidencyMode::ParamBackend, - sd->backend_for(SDBackendModule::UPSCALER), - sd->params_backend_for(SDBackendModule::UPSCALER)) || - !model_manager->validate_registered_tensors()) { - LOG_ERROR("register LTX latent upsampler tensors with model manager failed"); - return {}; - } - - sd::Tensor upscaled = upsampler->compute(sd->n_threads, unnormalized); - upsampler->runner_end(); - if (upscaled.empty()) { - LOG_ERROR("LTX latent spatial upscale failed"); - return {}; - } - - upscaled = sd->normalize_ltx_video_latents(upscaled); - sd->first_stage_model->runner_end(); - if (upscaled.empty()) { - LOG_ERROR("LTX latent normalization failed after spatial upscale"); - return {}; - } - - if (!audio_latent.empty()) { - upscaled = pack_ltxav_audio_and_video_latents(upscaled, audio_latent); - } - return upscaled; - } - - static bool apply_ltxv_refine_image_conditioning(StableDiffusionGGML* sd, - const sd::VideoConfig* sd_vid_gen_params, - const GenerationRequest& request, - const ImageGenerationLatents& latents, - sd::Tensor* latent, - sd::Tensor* denoise_mask, - sd::Tensor* video_positions) { - if (sd == nullptr || sd_vid_gen_params == nullptr || - latent == nullptr || latent->empty() || denoise_mask == nullptr || video_positions == nullptr) { - return true; - } - if (sd_vid_gen_params->init_image.data == nullptr && - sd_vid_gen_params->end_image.data == nullptr) { - return true; - } - constexpr float conditioning_strength = 1.f; - int latent_channels = sd->get_latent_channel(); - sd::Tensor video_latent = *latent; - sd::Tensor audio_latent; - if (latent->shape()[3] > latent_channels) { - video_latent = sd::ops::slice(*latent, 3, 0, latent_channels); - audio_latent = unpack_ltxav_audio_latent(*latent, latents.audio_length, latent_channels); - if (audio_latent.empty()) { - LOG_ERROR("failed to unpack LTXAV audio latent before image-to-video inplace conditioning"); - return false; - } - } - - int image_width = static_cast(video_latent.shape()[0]) * request.vae_scale_factor; - int image_height = static_cast(video_latent.shape()[1]) * request.vae_scale_factor; - sd::Tensor video_mask = make_ltxav_video_denoise_mask(video_latent, 1.f); - - if (sd_vid_gen_params->init_image.data != nullptr) { - sd::Tensor start_image = ensure_image_tensor_channels( - sd_image_to_tensor(sd_vid_gen_params->init_image, image_width, image_height), - sd->get_image_channels()); - if (!apply_ltxav_condition_image_by_latent_index(sd, - start_image, - &video_latent, - &video_mask, - 0, - "init", - conditioning_strength)) { - return false; - } - } - - if (sd_vid_gen_params->end_image.data != nullptr) { - sd::Tensor end_image = ensure_image_tensor_channels( - sd_image_to_tensor(sd_vid_gen_params->end_image, image_width, image_height), - sd->get_image_channels()); - sd::Tensor end_image_latent = encode_ltxav_condition_image(sd, end_image, "end"); - if (end_image_latent.empty()) { - return false; - } - - int frame_idx = request.frames - 1; - if (frame_idx == 0) { - if (!apply_ltxav_condition_by_latent_index(&video_latent, - &video_mask, - end_image_latent, - 0, - "end", - 1.f - conditioning_strength)) { - return false; - } - } else { - if (latents.video_conditioning_frame_count <= 0 || latents.video_target_frame_count <= 0) { - LOG_ERROR("LTXV FLF2V refine conditioning requires low-resolution keyframe conditioning metadata"); - return false; - } - int64_t target_latent_frames = latents.video_target_frame_count; - if (!apply_ltxav_condition_by_latent_index(&video_latent, - &video_mask, - end_image_latent, - target_latent_frames, - "end", - 1.f - conditioning_strength)) { - return false; - } - *video_positions = build_ltxv_video_positions(video_latent.shape()[0], - video_latent.shape()[1], - target_latent_frames, - end_image_latent.shape()[2], - frame_idx, - 1, - request.fps, - request.vae_scale_factor, - 8, - true); - } - } - - if (!audio_latent.empty()) { - *latent = pack_ltxav_audio_and_video_latents(video_latent, audio_latent); - *denoise_mask = pack_ltxav_audio_and_video_denoise_mask(video_mask, video_latent, audio_latent); - } else { - *latent = std::move(video_latent); - *denoise_mask = std::move(video_mask); - } - LOG_INFO("LTXV refine image conditioning applied at %dx%d", image_width, image_height); - return true; - } - - static bool generate_animatediff_video(StableDiffusionGGML* sd, - const sd::VideoConfig* sd_vid_gen_params, - sd::Image** frames_out, - int* num_frames_out) { - int n_frames = sd_vid_gen_params->video_frames; - if (n_frames < 1) { - LOG_ERROR("AnimateDiff: --video-frames must be >= 1"); - return false; - } - if (n_frames > 32) { - LOG_WARN("AnimateDiff motion modules have a 32-frame positional-encoding context; capping to 32"); - n_frames = 32; - } - - sd::ImageConfig img_gen_params; - - img_gen_params.loras = sd_vid_gen_params->loras; - img_gen_params.lora_count = sd_vid_gen_params->lora_count; - img_gen_params.prompt = sd_vid_gen_params->prompt; - img_gen_params.negative_prompt = sd_vid_gen_params->negative_prompt; - img_gen_params.clip_skip = sd_vid_gen_params->clip_skip; - img_gen_params.width = sd_vid_gen_params->width; - img_gen_params.height = sd_vid_gen_params->height; - img_gen_params.sample_params = sd_vid_gen_params->sample_params; - img_gen_params.strength = sd_vid_gen_params->strength; - img_gen_params.init_image = sd_vid_gen_params->init_image; - img_gen_params.seed = sd_vid_gen_params->seed; - img_gen_params.batch_count = 1; - img_gen_params.control_strength = 1.0f; - img_gen_params.vae_tiling_params = sd_vid_gen_params->vae_tiling_params; - img_gen_params.cache = sd_vid_gen_params->cache; - img_gen_params.hires = sd_vid_gen_params->hires; - img_gen_params.qwen_image_layers = 0; - img_gen_params.circular_x = sd_vid_gen_params->circular_x; - img_gen_params.circular_y = sd_vid_gen_params->circular_y; - img_gen_params.image_preprocess = sd_vid_gen_params->image_preprocess; - img_gen_params.ref_image_args = sd_vid_gen_params->ref_image_args; - - sd->animatediff_num_frames = n_frames; - bool ok = false; - try { - ok = generate_image(sd, &img_gen_params, frames_out, num_frames_out); - } catch (...) { - sd->animatediff_num_frames = 0; - throw; - } - sd->animatediff_num_frames = 0; - return ok; - } - - bool generate_video(StableDiffusionGGML* sd, - const sd::VideoConfig* sd_vid_gen_params, - sd::Image** frames_out, - int* num_frames_out, - sd::Audio** audio_out, - int* fps_out, - nlohmann::json* info_out) { - if (info_out) - *info_out = nlohmann::json(); - GenerationRequest request(sd, sd_vid_gen_params); - const auto info = sd::generation_info(request, *sd_vid_gen_params); - if (sd->config_->animatediff_loaded && sd_version_supports_animatediff(sd->version)) { - LOG_INFO("AnimateDiff dispatch: %d frames, %dx%d", - sd_vid_gen_params->video_frames, sd_vid_gen_params->width, sd_vid_gen_params->height); - if (fps_out != nullptr) { - *fps_out = std::max(1, sd_vid_gen_params->fps); - } - auto params = *sd_vid_gen_params; - params.seed = request.seed; - const bool ok = generate_animatediff_video(sd, ¶ms, frames_out, num_frames_out); - if (ok && info_out) - *info_out = info; - return ok; - } - - sd->reset_cancel_flag(); - - const RefImageParams ref_image_params = sd->resolve_ref_image_params(sd_vid_gen_params->ref_image_args); - - int64_t t0 = ggml_time_ms(); - sd->vae_tiling_params = sd_vid_gen_params->vae_tiling_params; - sd->apply_circular_axes(sd_vid_gen_params->circular_x, sd_vid_gen_params->circular_y); - sd::ImagePreprocessor preprocessing(sd_vid_gen_params->image_preprocess.rules); - sd::VideoConfig processed_params = *sd_vid_gen_params; - if (!preprocessing.prepare_inputs(processed_params, request.width, request.height)) - return false; - sd_vid_gen_params = &processed_params; - if (fps_out != nullptr) { - *fps_out = request.fps; - } - bool latent_upscale_enabled = request.hires.enabled; - GenerationRequest hires_request = request; - if (latent_upscale_enabled) { - const bool is_ltxav = sd_version_is_ltxav(sd->version); - const bool is_h3 = sd_version_is_minimax_h3(sd->version); - if (!is_ltxav && !is_h3) { - LOG_ERROR("video latent spatial upscale is only supported for LTX and MiniMax-H3 video models"); - return false; - } - if (is_ltxav) { - if (request.hires.upscaler != SD_HIRES_UPSCALER_MODEL) { - LOG_ERROR("LTX latent spatial upscale currently requires hires upscaler MODEL"); - return false; - } - if (strlen(SAFE_STR(request.hires.model_path)) == 0) { - LOG_ERROR("LTX latent spatial upscale is enabled but hires model path was not provided"); - return false; - } - } else { - const bool model_upscaler = request.hires.upscaler == SD_HIRES_UPSCALER_MODEL; - if (model_upscaler) { - if (strlen(SAFE_STR(request.hires.model_path)) == 0) { - LOG_ERROR("MiniMax-H3 learned hires upscaler is enabled but hires model path was not provided"); - return false; - } - } else if (!hires_upscaler_is_latent_interpolation(request.hires.upscaler)) { - LOG_ERROR("MiniMax-H3 hires requires an interpolating latent upscaler (e.g. \"Latent\" or \"Latent (bicubic)\") or a MODEL upscaler checkpoint"); - return false; - } - if (sd_vid_gen_params->init_image.data != nullptr || - sd_vid_gen_params->end_image.data != nullptr) { - LOG_ERROR("MiniMax-H3 hires does not support --init-img/--end-img keyframes yet; use T2VA or Ref2VA"); - return false; - } - if (request.hires.target_width <= 0 || request.hires.target_height <= 0) { - LOG_ERROR("MiniMax-H3 hires requires a positive hires target size"); - return false; - } - } - } - - sd->rng->manual_seed(request.seed); - sd->sampler_rng->manual_seed(request.seed); - if (!sd->apply_loras(sd_vid_gen_params->loras, sd_vid_gen_params->lora_count)) - return false; - sd->reset_generation_extensions(); - - SamplePlan plan(sd, sd_vid_gen_params, request); - sd->generation_progress.report("preparing", "inputs"); - auto latent_inputs_opt = prepare_video_generation_latents(sd, sd_vid_gen_params, &request, ref_image_params); - if (!latent_inputs_opt.has_value()) { - return false; - } - ImageGenerationLatents latents = std::move(*latent_inputs_opt); - - auto embeds_opt = prepare_video_generation_embeds(sd, - sd_vid_gen_params, - request, - latents, - ref_image_params); - if (!embeds_opt) { - return false; - } - ImageGenerationEmbeds embeds = std::move(*embeds_opt); - if (latent_upscale_enabled) { - LOG_INFO("generate_video %dx%dx%d -> video latent spatial upscale", - request.width, - request.height, - request.frames); - } else { - LOG_INFO("generate_video %dx%dx%d", - request.width, - request.height, - request.frames); - } - - int64_t latent_start = ggml_time_ms(); - int W = request.width / request.vae_scale_factor; - int H = request.height / request.vae_scale_factor; - int T = static_cast(latents.init_latent.shape()[2]); - - sd::Tensor x_t = latents.init_latent; - sd::Tensor noise = sd::Tensor::randn_like(x_t, sd->rng); - - if (plan.high_noise_sample_steps > 0) { - if (sd->get_cancel_flag() == SD_CANCEL_ALL) { - LOG_ERROR("cancelling generation before high-noise sampling"); - return false; - } - LOG_VERBOSE("sample(high noise) %dx%dx%d", W, H, T); - - int64_t sampling_start = ggml_time_ms(); - std::vector high_noise_sigmas(plan.sigmas.begin(), plan.sigmas.begin() + plan.high_noise_sample_steps + 1); - plan.sigmas = std::vector(plan.sigmas.begin() + plan.high_noise_sample_steps, plan.sigmas.end()); - - sd::Tensor x_t_sampled = sd->sample(sd->high_noise_diffusion_model, - false, - x_t, - std::move(noise), - embeds.cond, - request.use_high_noise_uncond ? embeds.uncond : SDCondition(), - embeds.img_uncond, - sd::Tensor(), - 0.f, - request.high_noise_guidance, - plan.high_noise_eta, - request.shifted_timestep, - plan.high_noise_sample_method, - sd->is_flow_denoiser(), - plan.high_noise_extra_sample_args, - high_noise_sigmas, - std::vector>{}, - ref_image_params, - latents.denoise_mask, - latents.vace_context, - request.vace_strength, - latents.audio_length, - static_cast(request.fps), - request.cache_params, - true, - latents.video_positions); - int64_t sampling_end = ggml_time_ms(); - if (x_t_sampled.empty()) { - LOG_ERROR("sampling(high noise) failed after %.2fs", (sampling_end - sampling_start) * 1.0f / 1000); - return false; - } - - x_t = std::move(x_t_sampled); - noise = {}; - LOG_INFO("sampling(high noise) completed, taking %.2fs", (sampling_end - sampling_start) * 1.0f / 1000); - } - - if (sd->get_cancel_flag() == SD_CANCEL_ALL) { - LOG_ERROR("cancelling generation before sampling"); - return false; - } - LOG_VERBOSE("sample %dx%dx%d", W, H, T); - int64_t sampling_start = ggml_time_ms(); - sd::Tensor final_latent = sd->sample(sd->diffusion_model, - true, - x_t, - std::move(noise), - embeds.cond, - request.use_uncond ? embeds.uncond : SDCondition(), - embeds.img_uncond, - sd::Tensor(), - 0.f, - request.guidance, - plan.eta, - request.shifted_timestep, - plan.sample_method, - sd->is_flow_denoiser(), - plan.extra_sample_args, - plan.sigmas, - std::vector>{}, - ref_image_params, - latents.denoise_mask, - latents.vace_context, - request.vace_strength, - latents.audio_length, - static_cast(request.fps), - request.cache_params, - plan.high_noise_sample_steps <= 0, - latents.video_positions); - - int64_t sampling_end = ggml_time_ms(); - if (final_latent.empty()) { - LOG_ERROR("sampling failed after %.2fs", (sampling_end - sampling_start) * 1.0f / 1000); - return false; - } - LOG_INFO("sampling completed, taking %.2fs", (sampling_end - sampling_start) * 1.0f / 1000); - - if (latent_upscale_enabled) { - if (sd->get_cancel_flag() == SD_CANCEL_ALL) { - LOG_ERROR("cancelling generation before latent upscale"); - return false; - } - sd->generation_progress.report("upscaling", "hires"); - int64_t upscale_start = ggml_time_ms(); - sd::Tensor upscaled_latent; - if (sd_version_is_ltxav(sd->version)) { - upscaled_latent = upscale_ltx_spatial_video_latent(sd, - request.hires.model_path, - final_latent, - latents.audio_length); - } else if (request.hires.upscaler == SD_HIRES_UPSCALER_MODEL) { - upscaled_latent = upscale_h3_learned_video_latent(sd, - request.hires.model_path, - final_latent, - latents.audio_length, - request.hires.target_width / request.vae_scale_factor, - request.hires.target_height / request.vae_scale_factor); - } else { - upscaled_latent = upscale_spatial_video_latent(sd, - request, - final_latent, - latents.audio_length); - } - int64_t upscale_end = ggml_time_ms(); - if (upscaled_latent.empty()) { - return false; - } - LOG_INFO("video latent spatial upscale completed, taking %.2fs", - (upscale_end - upscale_start) * 1.0f / 1000); - - x_t = std::move(upscaled_latent); - hires_request.width = static_cast(x_t.shape()[0]) * hires_request.vae_scale_factor; - hires_request.height = static_cast(x_t.shape()[1]) * hires_request.vae_scale_factor; - int upscaled_latent_frames = static_cast(x_t.shape()[2]); - int upscaled_frames = sd->latent_frames_to_video_frames(upscaled_latent_frames); - if (upscaled_frames != hires_request.frames) { - LOG_INFO("video latent upsampler output latent frames %d, frames %d -> %d", - upscaled_latent_frames, - hires_request.frames, - upscaled_frames); - hires_request.frames = upscaled_frames; - } - if (sd_version_is_ltxav(sd->version) && latents.audio_length > 0) { - int target_audio_length = get_ltxav_num_audio_latents(hires_request.frames, hires_request.fps); - if (target_audio_length != latents.audio_length) { - int latent_channels = sd->get_latent_channel(); - sd::Tensor video_latent = x_t; - sd::Tensor audio_latent = latents.audio_latent; - if (x_t.shape()[3] > latent_channels) { - video_latent = sd::ops::slice(x_t, 3, 0, latent_channels); - audio_latent = unpack_ltxav_audio_latent(x_t, latents.audio_length, latent_channels); - } - audio_latent = resize_ltxav_audio_latent(audio_latent, target_audio_length); - if (audio_latent.empty()) { - LOG_ERROR("failed to resize LTX audio latent for latent upscale: %d -> %d", - latents.audio_length, - target_audio_length); - return false; - } - x_t = pack_ltxav_audio_and_video_latents(video_latent, audio_latent); - latents.audio_latent = std::move(audio_latent); - LOG_INFO("LTX audio latent length adjusted for latent upscale: %d -> %d", - latents.audio_length, - target_audio_length); - latents.audio_length = target_audio_length; - } - } - if (sd_version_is_ltxav(sd->version) && - (request.hires.target_width > 0 || request.hires.target_height > 0) && - (request.hires.target_width != hires_request.width || request.hires.target_height != hires_request.height)) { - LOG_WARN("LTX latent spatial upsampler output is %dx%d; ignoring hires target %dx%d", - hires_request.width, - hires_request.height, - request.hires.target_width, - request.hires.target_height); - } - sd::Tensor hires_denoise_mask; - sd::Tensor hires_video_positions; - if (sd->get_cancel_flag() == SD_CANCEL_ALL) { - LOG_ERROR("cancelling generation before latent upscale refine"); - return false; - } - if (sd_version_is_ltxav(sd->version) && - !apply_ltxv_refine_image_conditioning(sd, - sd_vid_gen_params, - hires_request, - latents, - &x_t, - &hires_denoise_mask, - &hires_video_positions)) { - return false; - } - // H3 keyframe conditioning must be re-encoded at the hires resolution. - if (sd_version_is_minimax_h3(sd->version) && - !latents.denoise_mask.empty() && - (latents.denoise_mask.shape()[0] != x_t.shape()[0] || - latents.denoise_mask.shape()[1] != x_t.shape()[1])) { - LOG_ERROR("MiniMax-H3 hires cannot rescale an existing video denoise mask"); - return false; - } - noise = sd::Tensor::randn_like(x_t, sd->rng); - - W = hires_request.width / hires_request.vae_scale_factor; - H = hires_request.height / hires_request.vae_scale_factor; - T = static_cast(x_t.shape()[2]); - sample_method_t hires_sample_method = plan.sample_method; - int hires_scheduler_steps = 0; - std::vector hires_sigma_sched = - make_hires_sigma_schedule(sd, - request.hires, - request.sample_params, - plan.sample_steps, - sd->get_image_seq_len(hires_request.height, hires_request.width) * T, - &hires_scheduler_steps); - float hires_eta = plan.eta; - - LOG_VERBOSE("sample(latent upscale) %dx%dx%d", W, H, T); - LOG_INFO("video latent spatial upscale refine: scheduler_steps=%d, denoising_strength=%.2f, sampler=%s, sigma_sched_size=%zu%s", - hires_scheduler_steps, - request.hires.denoising_strength, - sampling_methods_str[hires_sample_method], - hires_sigma_sched.size(), - request.hires.custom_sigmas_count > 0 ? ", custom_sigmas=true" : ""); - - sampling_start = ggml_time_ms(); - final_latent = sd->sample(sd->diffusion_model, - true, - x_t, - std::move(noise), - embeds.cond, - hires_request.use_uncond ? embeds.uncond : SDCondition(), - embeds.img_uncond, - sd::Tensor(), - 0.f, - request.guidance, - hires_eta, - request.shifted_timestep, - hires_sample_method, - sd->is_flow_denoiser(), - plan.extra_sample_args, - hires_sigma_sched, - std::vector>{}, - ref_image_params, - hires_denoise_mask, - sd::Tensor(), - hires_request.vace_strength, - latents.audio_length, - static_cast(hires_request.fps), - hires_request.cache_params, - false, - hires_video_positions); - sampling_end = ggml_time_ms(); - if (final_latent.empty()) { - LOG_ERROR("sampling(latent upscale) failed after %.2fs", - (sampling_end - sampling_start) * 1.0f / 1000); - return false; - } - LOG_INFO("sampling(latent upscale) completed, taking %.2fs", - (sampling_end - sampling_start) * 1.0f / 1000); - } - - int64_t latent_end = ggml_time_ms(); - LOG_INFO("generating latent video completed, taking %.2fs", (latent_end - latent_start) * 1.0f / 1000); - - sd::Audio* generated_audio = nullptr; - if (sd->version == VERSION_WAN2_2_S2V && sd_vid_gen_params->ref_audios_count > 0) { - // Return the driving track for muxing with the generated video. - const sd::Audio& driving = sd_vid_gen_params->ref_audios[0]; - generated_audio = (sd::Audio*)malloc(sizeof(sd::Audio)); - if (generated_audio != nullptr) { - generated_audio->sample_rate = driving.sample_rate; - generated_audio->channels = driving.channels; - generated_audio->sample_count = driving.sample_count; - generated_audio->data = (float*)malloc(sizeof(float) * driving.sample_count * driving.channels); - if (generated_audio->data == nullptr) { - free(generated_audio); - generated_audio = nullptr; - } else { - memcpy(generated_audio->data, - driving.data, - sizeof(float) * driving.sample_count * driving.channels); - } - } - if (generated_audio != nullptr) { - LOG_DEBUG("s2v output audio: %u Hz, %u channels, %llu samples", - generated_audio->sample_rate, - generated_audio->channels, - (unsigned long long)generated_audio->sample_count); - } else { - LOG_DEBUG("s2v output audio copy failed (out of memory)"); - } - } - if ((sd_version_is_ltxav(sd->version) || sd_version_is_minimax_h3(sd->version)) && - latents.audio_length > 0 && - sd->audio_vae_model != nullptr) { - if (sd->get_cancel_flag() == SD_CANCEL_ALL) { - LOG_ERROR("cancelling generation before audio decode"); - return false; - } - int64_t audio_latent_decode_start = ggml_time_ms(); - - auto audio_latent = sd_version_is_minimax_h3(sd->version) - ? unpack_minimax_h3_audio_latent(final_latent, - latents.audio_length, - sd->get_latent_channel()) - : unpack_ltxav_audio_latent(final_latent, - latents.audio_length, - sd->get_latent_channel()); - if (!audio_latent.empty()) { - LOG_VERBOSE("decode audio latent %dx%dx%dx%d", - (int)audio_latent.shape()[0], - (int)audio_latent.shape()[1], - (int)audio_latent.shape()[2], - (int)audio_latent.shape()[3]); - auto waveform = sd->decode_ltx_audio_latent(audio_latent); - if (!waveform.empty()) { - generated_audio = waveform_to_sd_audio(sd, waveform); - } else { - LOG_WARN("audio latent decode failed; continuing with silent video output"); - } - } - int64_t audio_latent_decode_end = ggml_time_ms(); - LOG_INFO("decoding audio latent completed, taking %.2fs", (audio_latent_decode_end - audio_latent_decode_start) * 1.0f / 1000); - } - - if (latents.video_conditioning_frame_count > 0) { - int64_t target_frames = latents.video_target_frame_count > 0 ? latents.video_target_frame_count - : final_latent.shape()[2] - latents.video_conditioning_frame_count; - final_latent = sd::ops::slice(final_latent, 2, 0, target_frames); - } - - if (latents.ref_image_num > 0) { - final_latent = sd::ops::slice(final_latent, 2, latents.ref_image_num, final_latent.shape()[2]); - } - - if (sd->get_cancel_flag() == SD_CANCEL_ALL) { - LOG_ERROR("cancelling generation before video decode"); - sd::free_audio(generated_audio); - return false; - } - auto result = decode_video_outputs(sd, latent_upscale_enabled ? hires_request : request, final_latent, num_frames_out); - LOG_DEBUG("decode_video_outputs returned %s", result == nullptr ? "nullptr (failed)" : "frames"); - if (result == nullptr) { - sd::free_audio(generated_audio); - return false; - } - - sd->lora_stat(); - - int64_t t1 = ggml_time_ms(); - LOG_INFO("generate_video completed in %.2fs", (t1 - t0) * 1.0f / 1000); - if (frames_out != nullptr) { - *frames_out = result; - } - if ((sd->version == VERSION_WAN2_2_S2V || sd_version_is_minimax_h3(sd->version)) && generated_audio != nullptr) { - // Limit the audio track to the generated video's duration. - int fps = request.fps; - uint64_t video_frames = num_frames_out != nullptr ? (uint64_t)*num_frames_out : 0; - uint64_t want_samples = (uint64_t)((double)video_frames / fps * generated_audio->sample_rate); - LOG_DEBUG("output audio truncate: %llu samples -> %llu (video %llu frames @ %d fps)", - (unsigned long long)generated_audio->sample_count, - (unsigned long long)want_samples, - (unsigned long long)video_frames, - fps); - if (want_samples > 0 && want_samples < generated_audio->sample_count) { - generated_audio->sample_count = want_samples; - } - } - if (info_out) { - try { - *info_out = info; - } catch (...) { - sd::free_audio(generated_audio); - throw; - } - } - if (audio_out != nullptr) { - *audio_out = generated_audio; - } else { - sd::free_audio(generated_audio); - } - return true; - } - -} // namespace sd::pipeline