diff --git a/README.md b/README.md index f36a435e8d..40f09e4ca7 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ API and command-line option may change frequently.*** - [Textual inversion embeddings](./docs/embeddings.md) for SD 1.x/2.x/SDXL via `--embd-dir` and `` tags - Latent Consistency Models support (LCM/LCM-LoRA) - Faster and memory efficient latent decoding with [TAESD](./docs/models/taesd.md) - - Upscale images generated with [ESRGAN](./docs/models/esrgan.md) + - Upscale images with [ESRGAN or MoSR](./docs/models/esrgan.md) and [Kandinsky ImageSR 2.0](./docs/models/kandinsky_imagesr.md) - Supported backends - CPU (AVX, AVX2 and AVX512 support for x86 architectures) - CUDA diff --git a/docs/dgl/kandinsky_imagesr/upscale.dgl b/docs/dgl/kandinsky_imagesr/upscale.dgl new file mode 100644 index 0000000000..14806c367b --- /dev/null +++ b/docs/dgl/kandinsky_imagesr/upscale.dgl @@ -0,0 +1,17 @@ +# version: 0.0.0 +# docs/models/kandinsky_imagesr.md — standalone image upscaling + +var { + upscaler_path = "../models/Kandinsky-ImageSR-2.0" + + input_path = "input.png" + output_path = "upscaled.png" +} + +fn main() { + upscaler = load_upscaler(upscaler_path) + image = image::load(input_path) + output = upscale(upscaler, image, factor = 2) + image::save(output_path, output) + return output +} diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index e456c0050d..604ffb742c 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -117,9 +117,9 @@ are required and set to `NULL` on failure. All outputs use `sd_result_t`. Image upscaling loads `model_path` with optional `n_threads`, `backend`, `params_backend`, `conv_direct` and `tile_size` (default 128). Execution takes -an RGB `image`. Its scale is fixed by the loaded model and can be queried with -`sd_upscaler_get_scale()`; metadata records that actual scale. The former -image-upscale factor argument was unused and has been removed. +an RGB `image`. Query the model's default scale with `sd_upscaler_get_scale()`. +Kandinsky ImageSR supports a per-run integer `factor` of 2 or 4 (default 4). +ESRGAN and MoSR use the scale encoded in their weights. ```c sd_upscaler_opt_t* load = sd_upscaler_opt_create(); @@ -424,6 +424,7 @@ For SDXL's bundled VAE (no `vae_path`), generation emits | `fps` | `int` | video | | `height` | `int` | image, video | | `high_noise_diffusion_model_path` | `string` | context | +| `factor` | `int` | upscale. Selects 2× or 4× for Kandinsky ImageSR | | `image` | `tensor` | upscale | | `init_image` | `tensor` | image, video | | `linear_scale` | `float` | context | diff --git a/docs/models/README.md b/docs/models/README.md index 06820fac5b..16ac26df95 100644 --- a/docs/models/README.md +++ b/docs/models/README.md @@ -111,6 +111,7 @@ model guide. ## Image and video super-resolution - [ESRGAN and MoSR](esrgan.md) +- [Kandinsky ImageSR 2.0](kandinsky_imagesr.md) - [RelayVSR](relay_vsr.md) - [SeedVR2](seedvr2.md) diff --git a/docs/models/kandinsky_imagesr.md b/docs/models/kandinsky_imagesr.md new file mode 100644 index 0000000000..a3d4596979 --- /dev/null +++ b/docs/models/kandinsky_imagesr.md @@ -0,0 +1,66 @@ +# Kandinsky ImageSR 2.0 + +Kandinsky ImageSR performs 2× and 4× super-resolution on RGB images. Both scales use the same weights. The default is 4×. + +## Model files + +| Component | Weights and downloads | CLI option | Requirement | +| --- | --- | --- | --- | +| ImageSR transformer | [Transformer files](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0/tree/main/transformer) | `--upscale-model` | Keep the configuration, shard index and all shards under `transformer/`. | +| FLUX VAE | [VAE files](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0/tree/main/vae) | Same bundle directory | Keep the supplied VAE under `vae/`. | + +From the repository root, download both components with the Hugging Face CLI. + +```sh +hf download kandinskylab/Kandinsky-ImageSR-2.0 --include 'transformer/*' 'vae/*' --local-dir models/Kandinsky-ImageSR-2.0 +``` + +## Usage + +Run the following examples from the build directory with an RGB image named `input.png`. + +### DGL + +| Task | Script | +| --- | --- | +| Upscale an image at 2× | [Kandinsky ImageSR upscaling](../dgl/kandinsky_imagesr/upscale.dgl) | + +Set `factor = 4` in the script for 4× output. + +**Windows PowerShell** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\kandinsky_imagesr\upscale.dgl +``` + +**Linux / macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/kandinsky_imagesr/upscale.dgl +``` + +### Legacy CLI + +**Windows PowerShell** + +```powershell +.\bin\Release\sd-cli.exe -M upscale --upscale-model ..\models\Kandinsky-ImageSR-2.0 ` + -i input.png --upscale-factor 2 -o output.png +``` + +**Linux / macOS** + +```sh +./bin/sd-cli -M upscale --upscale-model ../models/Kandinsky-ImageSR-2.0 \ + -i input.png --upscale-factor 2 -o output.png +``` + +### API + +For the [C API](../guides/c_api.md), pass the bundle directory as `model_path` and set the integer `factor` on the per-run options before calling `sd_upscale`. + +For [server hires upscaling](../../examples/server/api.md), place the bundle directly under `--hires-upscalers-dir` and use its directory name in `hires.upscaler`. The hires pass selects 2× when it covers both target dimensions and 4× for larger targets. + +## Notes and limitations + +ImageSR processes overlapping tiles with a fixed output tile size of 1024×1024. Standalone output dimensions are exactly the input dimensions multiplied by the selected scale, including for small and non-square inputs. diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index e3b7202f45..fbcdc44e18 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -827,7 +827,9 @@ int main(int argc, const char* argv[]) { ctx_params.linear_type)); if (upscaler_ctx == nullptr) { - LOG_ERROR("sd_upscaler_create failed"); + LOG_ERROR("sd_upscaler_create failed: %s", sd_get_last_error()); + if (cli_params.mode == UPSCALE) + return 1; } else { for (int i = 0; i < num_results; i++) { if (results[i].data == nullptr) { @@ -836,7 +838,7 @@ int main(int argc, const char* argv[]) { SDImageOwner current_image(results[i]); results[i] = {0, 0, 0, nullptr}; sd_result_t* upscaled = nullptr; - if (!upscale_sd_image(upscaler_ctx.get(), current_image.get(), &upscaled, gen_params.upscale_repeats) || !upscaled) { + if (!upscale_sd_image(upscaler_ctx.get(), current_image.get(), &upscaled, gen_params.upscale_repeats, gen_params.upscale_factor.value_or(0)) || !upscaled) { LOG_ERROR("upscale failed: %s", sd_get_last_error()); sd_result_free(upscaled); return 1; diff --git a/examples/common/common.cpp b/examples/common/common.cpp index c66502fdcb..efd342f27e 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -512,7 +512,7 @@ ArgOptions SDContextParams::get_options() { &model_args}, {"", "--upscale-model", - "path to esrgan model.", + "path to ESRGAN or MoSR weights, or a Kandinsky ImageSR bundle directory", 0, &esrgan_path}, {"", @@ -1174,6 +1174,10 @@ ArgOptions SDGenerationParams::get_options() { "--fps", "fps (default: 24)", &fps}, + {"", + "--upscale-factor", + "Kandinsky ImageSR scale factor: 2 or 4 (default: 4)", + &upscale_factor}, {"", "--upscale-repeats", "Run the ESRGAN upscaler this many times (default: 1)", @@ -1926,16 +1930,19 @@ static bool resolve_model_file_from_dir(const std::string& model_name, 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() || + const auto name = fs::u8path(model_name); + if (name.empty() || name == "." || name == ".." || name.has_parent_path() || 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); + const auto bundle = model_dir_path / name; + if (fs::is_regular_file(bundle / "transformer" / "config.json")) { + resolved_path = bundle.lexically_normal().u8string(); + return true; + } 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)) { @@ -2041,6 +2048,7 @@ bool SDGenerationParams::from_json_str( 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_factor", upscale_factor); load_if_exists("upscale_repeats", upscale_repeats); load_if_exists("seed", seed); @@ -2405,6 +2413,10 @@ bool SDGenerationParams::validate(SDMode mode) { return false; } + if (upscale_factor && upscale_factor != 2 && upscale_factor != 4) { + LOG_ERROR("upscale factor must be 2 or 4"); + return false; + } if (upscale_repeats < 1) { return false; } diff --git a/examples/common/common.h b/examples/common/common.h index cddfaf0c88..239b399ffb 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -257,6 +257,7 @@ struct SDGenerationParams { SDTilingParams vae_tiling_params; std::string extra_tiling_args; + std::optional upscale_factor; int upscale_repeats = 1; std::optional upscale_tile_size; diff --git a/examples/common/resource_owners.hpp b/examples/common/resource_owners.hpp index 83f2dca503..f5cdf3648e 100644 --- a/examples/common/resource_owners.hpp +++ b/examples/common/resource_owners.hpp @@ -339,12 +339,13 @@ static inline sd_upscaler_t* create_sd_upscaler(const char* path, std::optional< return result; } -static inline bool upscale_sd_image(sd_upscaler_t* ctx, SDImage image, sd_result_t** result, int repeats = 1) { +static inline bool upscale_sd_image(sd_upscaler_t* ctx, SDImage image, sd_result_t** result, int repeats = 1, int factor = 0) { if (result) *result = nullptr; SDOptPtr opt(sd_upscale_opt_create()); auto tensor = image_tensor(image); return opt && tensor && sd_opt_set_tensor(opt.get(), "image", tensor.get()) == SD_STATUS_OK && + (!factor || sd_opt_set_int(opt.get(), "factor", factor) == SD_STATUS_OK) && sd_opt_set_int(opt.get(), "repeats", repeats) == SD_STATUS_OK && sd_upscale(ctx, opt.get(), result) == SD_STATUS_OK; } diff --git a/examples/server/api.md b/examples/server/api.md index ae61d0598f..581bb09462 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -659,7 +659,7 @@ Response fields: | `[].model_url` | `string \| null` | Currently always null | | `[].scale` | `integer` | Currently `4` | -Built-in entries include `None`, `Lanczos`, and `Nearest`. Model-backed entries are scanned from the top level of `--hires-upscalers-dir`; subdirectories are not scanned. +Built-in entries include `None`, `Lanczos`, and `Nearest`. Model-backed entries include weight files and Kandinsky ImageSR bundle directories directly under `--hires-upscalers-dir`. Use the bundle directory name to select Kandinsky. `GET /sdapi/v1/latent-upscale-modes` @@ -904,7 +904,7 @@ Shared nested fields: | `upscalers[].name` | `string` | Built-in name or model stem; use this value in `hires.upscaler` | | `upscalers[].model` | `boolean` | True for a model-backed upscaler, false for a built-in scaling filter | -Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, and `Latent (bicubic antialiased)`. Model-backed entries are scanned from the top level of `--hires-upscalers-dir`; subdirectories are not scanned. +Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, and `Latent (bicubic antialiased)`. Model-backed entries include weight files and Kandinsky ImageSR bundle directories directly under `--hires-upscalers-dir`. Use the bundle directory name to select Kandinsky. `limits` @@ -1293,7 +1293,7 @@ Other native fields: | `scm_mask` | `string` | | `scm_policy_dynamic` | `boolean` | -For `hires.upscaler`, use `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, `Latent (bicubic antialiased)`, or an `upscalers[].name` value from `GET /sdcpp/v1/capabilities`. Model-backed upscalers are resolved as `--hires-upscalers-dir / (name + ext)` and must live directly in that directory. `hires.custom_sigmas`, when present, overrides the generated second-pass hires sigma schedule; otherwise the hires schedule is trimmed by `hires.denoising_strength`. +For `hires.upscaler`, use `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, `Latent (bicubic antialiased)`, or an `upscalers[].name` value from `GET /sdcpp/v1/capabilities`. Use the stem of a weight file or the name of a Kandinsky ImageSR bundle directly under `--hires-upscalers-dir`. `hires.custom_sigmas`, when present, overrides the generated second-pass hires sigma schedule; otherwise the hires schedule is trimmed by `hires.denoising_strength`. HTTP-only output fields: diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 6853acd33b..ae6a8c84f3 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -504,6 +504,21 @@ void refresh_upscaler_cache(ServerRuntime& rt) { auto end = fs::directory_iterator(); while (!ec && it != end) { std::error_code entry_ec; + const auto& path = it->path(); + if (it->is_directory(entry_ec)) { + if (fs::is_regular_file(path / "transformer" / "config.json", entry_ec)) { + UpscalerEntry entry{}; + entry.path = entry.name = path.filename().u8string(); + entry.fullpath = fs::absolute(path).lexically_normal().u8string(); + entry.scale = sd_upscaler_probe_scale(entry.fullpath.c_str()); + if (entry.scale > 0) { + entry.model_name = "Kandinsky ImageSR 2.0"; + new_cache.push_back(std::move(entry)); + } + } + it.increment(ec); + continue; + } bool is_reg = it->is_regular_file(entry_ec); if (entry_ec || !is_reg) { it.increment(ec); diff --git a/src/api/generation_hires.cpp b/src/api/generation_hires.cpp index 7c11b21dc8..1635f31d5a 100644 --- a/src/api/generation_hires.cpp +++ b/src/api/generation_hires.cpp @@ -61,6 +61,11 @@ namespace sd::api { if (hires.custom_sigmas_count) request.values["hires_custom_sigmas"] = std::vector(hires.custom_sigmas, hires.custom_sigmas + hires.custom_sigmas_count); if (model) { + if (pixels) { + const auto fits_x2 = request.values.at("hires_target_width").get() <= 2 * request.values.at("width").get() && + request.values.at("hires_target_height").get() <= 2 * request.values.at("height").get(); + request.fields["hires_upscale_factor"] = fits_x2 ? "2" : "4"; + } request.values["hires_model_path"] = text(hires.model_path); auto options = loader_options(settings, request.video ? SDBackendModule::DIFFUSION : SDBackendModule::UPSCALER, request.definition); if (!request.video) { diff --git a/src/api/options.cpp b/src/api/options.cpp index 4f1970a25e..e0f697bdcf 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -475,6 +475,7 @@ static void add_postprocess_specs(std::vector& specs) { ParamGroup input(specs, Upscale, [](sd::OptConfig& config) { return std::tie(config.post); }); ParamGroup upscaler(specs, Upscaler, [](sd::OptConfig& config) { return std::tie(config.post); }); input.image("image", &sd::PostprocessConfig::image); + input.integer("factor", &sd::PostprocessConfig::factor, 1, 16); 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); diff --git a/src/api/templates/image_helpers.dgl b/src/api/templates/image_helpers.dgl index bb16609e55..44ff08c8c6 100644 --- a/src/api/templates/image_helpers.dgl +++ b/src/api/templates/image_helpers.dgl @@ -33,7 +33,7 @@ fn upscale_layer(index, args) { latent = args.latent[:, :, index] image = vae_decode(args.vae, dit_to_vae_latents(args.vae, latent), dtype = "f32"{{vae_run_options}}) {% if flags.hires_model %} - upscaled = upscale(args.upscaler, image::to_u8(image)) + upscaled = upscale(args.upscaler, image::to_u8(image), factor = {{hires_upscale_factor}}) pixels = image::to_f32(tensor::interpolate(upscaled, size = args.size, axes = [1, 2], mode = args.mode)) {% else %} pixels = tensor::interpolate(image, size = args.size, mode = args.mode) diff --git a/src/api/templates/image_hires.dgl b/src/api/templates/image_hires.dgl index 14c09a5445..f13ed898ae 100644 --- a/src/api/templates/image_hires.dgl +++ b/src/api/templates/image_hires.dgl @@ -28,7 +28,7 @@ {% endif %} {% if flags.hires_model %} hires_upscaler = load_upscaler(hires_model_path{{hires_model_options}}) - hires_upscaled = upscale(hires_upscaler, image::to_u8(hires_pixels)) + hires_upscaled = upscale(hires_upscaler, image::to_u8(hires_pixels), factor = {{hires_upscale_factor}}) hires_resized = image::to_f32(tensor::interpolate(hires_upscaled, size = [hires_target_width, hires_target_height], axes = [1, 2], mode = hires_mode), channels = {{channels}}) {% else %} hires_resized = tensor::interpolate(hires_pixels, size = [hires_target_width, hires_target_height], mode = hires_mode) diff --git a/src/api/templates/upscale.dgl b/src/api/templates/upscale.dgl index daa4649de0..40995a56ed 100644 --- a/src/api/templates/upscale.dgl +++ b/src/api/templates/upscale.dgl @@ -7,7 +7,7 @@ var { } fn enlarge(image, index, model) { - return upscale(model, image) + return upscale(model, image{{factor_option}}) } fn main(input_image) { diff --git a/src/api/upscaler.cpp b/src/api/upscaler.cpp index 2e2aa051e0..2764d4bebe 100644 --- a/src/api/upscaler.cpp +++ b/src/api/upscaler.cpp @@ -17,7 +17,7 @@ struct sd_upscaler { }; namespace sd::api { - static std::string upscale_source(const OptConfig& config, int repeats) { + static std::string upscale_source(const OptConfig& config, int repeats, int factor = 0) { const auto& settings = config.context; std::string options; for (const auto& [name, spec] : std::map{{"backend", settings.backend}, {"params_backend", settings.params_backend}}) { @@ -34,6 +34,7 @@ namespace sd::api { return render_template("upscale", {{"model_path", nlohmann::json(settings.model_path).dump()}, {"tile_size", std::to_string(config.post.tile_size)}, {"repeats", std::to_string(repeats)}, + {"factor_option", factor ? ", factor = " + std::to_string(factor) : ""}, {"loader_options", options}}); } } @@ -100,7 +101,9 @@ sd_status_t sd_upscale(sd_upscaler_t* upscaler, const sd_upscale_opt_t* options, if (status != SD_STATUS_OK) return status; int64_t width = config.post.image.width, height = config.post.image.height; - const auto scale = upscaler->model->get_scale(); + const auto scale = upscaler->model->get_scale(config.post.factor); + if (!scale) + return sd::api::error(SD_STATUS_INVALID_ARGUMENT, "factor", "Kandinsky ImageSR supports factors 2 and 4"); for (int i = 0; i < config.post.repeats; ++i) { width *= scale; height *= scale; @@ -109,9 +112,10 @@ sd_status_t sd_upscale(sd_upscaler_t* upscaler, const sd_upscale_opt_t* options, } const auto* input = sd::api::bound_tensor(snapshot.get(), "image"); sd::api::GenerationProgram program; - program.source = config.post.repeats == 1 ? upscaler->source : sd::api::upscale_source(upscaler->context.model.config, config.post.repeats); + const bool use_cached = config.post.repeats == 1 && config.post.factor == 0; + program.source = use_cached ? upscaler->source : sd::api::upscale_source(upscaler->context.model.config, config.post.repeats, config.post.factor); program.inputs.emplace("input_image", sd::dgl::Value::object(std::shared_ptr(sd_tensor_retain(input), sd_tensor_free))); - auto value = sd::api::execute_program(upscaler->context, program, config.post.repeats == 1 ? &upscaler->program : nullptr); + auto value = sd::api::execute_program(upscaler->context, program, use_cached ? &upscaler->program : nullptr); auto result = std::make_unique(); sd::api::append_program_image(*result, value, program.source); *out = result.release(); diff --git a/src/config.h b/src/config.h index c93e84ad19..a9476e8887 100644 --- a/src/config.h +++ b/src/config.h @@ -210,6 +210,7 @@ namespace sd { bool conv_direct = false; int tile_size = 128; int repeats = 1; + int factor = 0; }; struct OptConfig { diff --git a/src/dgl/bindings/model.cpp b/src/dgl/bindings/model.cpp index 8e4af3a97c..348b1be56a 100644 --- a/src/dgl/bindings/model.cpp +++ b/src/dgl/bindings/model.cpp @@ -35,13 +35,16 @@ namespace sd::dgl { Value execute_upscale(Values& args, RunState&) { auto image = image_view(args.at("image")); auto model = object(args, "upscaler"); - const int64_t factor = model->get_scale(); + const auto requested = args.count("factor") ? int(get_int(args, "factor")) : 0; + const int64_t factor = model->get_scale(requested); + if (factor == 0) + throw Error(SD_STATUS_INVALID_ARGUMENT, "Kandinsky ImageSR supports factors 2 and 4"); if (factor <= 0 || image.channel != 3 || int64_t(image.width) * factor > 16384 || int64_t(image.height) * factor > 16384 || int64_t(image.width) * image.height * factor * factor > 64 * 1024 * 1024) throw Error(SD_STATUS_OUT_OF_RANGE, "upscale requires RGB and output at most 64 megapixels at the model's actual scale"); if (args.count("factor") && get_int(args, "factor") != factor) LOG_WARN("upscale factor=%lld is ignored; the model's actual scale is %lld", (long long)get_int(args, "factor"), (long long)factor); - auto output = model->upscale(image); + auto output = model->upscale(image, factor); std::unique_ptr owner(output.data, free); if (!output.data) throw std::runtime_error("upscale failed"); diff --git a/src/dgl/models/image_upscale.cpp b/src/dgl/models/image_upscale.cpp index 3a4a8a4b28..170bb2edf3 100644 --- a/src/dgl/models/image_upscale.cpp +++ b/src/dgl/models/image_upscale.cpp @@ -3,6 +3,7 @@ #include "core/ggml_extend_backend.h" #include "core/util.h" #include "model/upscaler/esrgan.hpp" +#include "model/upscaler/kandinsky_imagesr.hpp" #include "model/upscaler/mosr.hpp" #include "model/upscaler/scale.hpp" #include "model_manager.h" @@ -25,10 +26,17 @@ namespace sd::dgl::models { } GGMLRunner* ImageUpscaleModel::runner() const { + if (kandinsky_) + return kandinsky_->transformer.get(); return mosr_ != nullptr ? static_cast(mosr_.get()) : esrgan_.get(); } - int ImageUpscaleModel::scale() const { + int ImageUpscaleModel::scale(int requested) const { + if (kandinsky_) { + if (requested == 0) + return 4; + return requested == 2 || requested == 4 ? requested : 0; + } if (mosr_ != nullptr) { return mosr_->config.scale; } @@ -56,14 +64,21 @@ namespace sd::dgl::models { if (model->source_file_ == 0) { return nullptr; } - const auto& tensors = manager->model_source(model->source_file_).get_tensor_storage_map(); - const auto description = sd::upscaling::describe(tensors); + const auto& source = manager->model_source(model->source_file_); + const auto& tensors = source.get_tensor_storage_map(); + const auto description = sd::upscaling::describe(source); if (description.architecture == sd::upscaling::Architecture::Unknown) { LOG_ERROR("unsupported image upscaler weights: '%s'", path.c_str()); return nullptr; } std::map weights; - if (description.architecture == sd::upscaling::Architecture::MoSR) { + const bool kandinsky = description.architecture == sd::upscaling::Architecture::KandinskyImageSR; + if (kandinsky) { + model->kandinsky_ = KandinskyImageSR::Upscaler::create(source, backend, manager, conv_direct); + if (!model->kandinsky_) + return nullptr; + model->kandinsky_->get_param_tensors(weights); + } else if (description.architecture == sd::upscaling::Architecture::MoSR) { model->mosr_ = std::make_unique(backend, tensors, manager); if (model->mosr_->mosr_net == nullptr) { LOG_ERROR("unsupported MoSR weights: '%s'", path.c_str()); @@ -86,17 +101,17 @@ namespace sd::dgl::models { : ModelManager::ResidencyMode::ParamBackend; if (!manager->register_param_tensors(ModelComponent::Upscaler, std::move(weights), mode, backend, params_backend, nullptr, false, false, nullptr, - model->source_file_, VERSION_ESRGAN) || + model->source_file_, kandinsky ? VERSION_FLUX : VERSION_ESRGAN) || !manager->validate_param_tensors(model->weights_)) { LOG_ERROR("register upscaler weights failed: '%s'", path.c_str()); return nullptr; } model->runner()->set_conv2d_direct_enabled(conv_direct); - LOG_INFO("Upscaler architecture: %s, weight type: %s", model->runner()->get_desc().c_str(), ggml_type_name(weight_type)); + LOG_INFO("Upscaler architecture: %s, weight type: %s", model->runner()->get_desc().c_str(), kandinsky ? "checkpoint" : ggml_type_name(weight_type)); return model; } - Tensor upscale_image_tensor(ImageUpscaleModel& model, const Tensor& input, int n_threads, int tile_size) { + Tensor upscale_image_tensor(ImageUpscaleModel& model, const Tensor& input, int n_threads, int tile_size, int factor) { if (input.empty() || input.dim() != 4 || (input.shape()[2] != 3 && input.shape()[2] != 4)) { LOG_ERROR("upscaler expects a 4D RGB or RGBA image tensor"); return {}; @@ -110,9 +125,11 @@ namespace sd::dgl::models { const auto compute = [&](const Tensor& tensor) { return model.mosr_ != nullptr ? model.mosr_->compute(n_threads, tensor) : model.esrgan_->compute(n_threads, tensor); }; - const int scale = model.scale(); + const int scale = model.scale(factor); Tensor output; - if (tile_size <= 0 || (input.shape()[0] <= tile_size && input.shape()[1] <= tile_size)) { + if (model.kandinsky_) { + output = model.kandinsky_->upscale(n_threads, rgb, scale); + } else if (tile_size <= 0 || (input.shape()[0] <= tile_size && input.shape()[1] <= tile_size)) { output = compute(rgb); } else { output = process_tiles_2d(rgb, diff --git a/src/dgl/models/image_upscale.h b/src/dgl/models/image_upscale.h index 2fe9bc3f5f..13928a60f0 100644 --- a/src/dgl/models/image_upscale.h +++ b/src/dgl/models/image_upscale.h @@ -14,6 +14,9 @@ class SDBackendManager; struct GGMLRunner; struct ESRGAN; struct MoSR; +namespace KandinskyImageSR { + struct Upscaler; +} namespace sd::dgl::models { class ImageUpscaleModel { @@ -24,10 +27,11 @@ namespace sd::dgl::models { const std::string&, bool, ggml_type); - friend Tensor upscale_image_tensor(ImageUpscaleModel&, const Tensor&, int, int); + friend Tensor upscale_image_tensor(ImageUpscaleModel&, const Tensor&, int, int, int); std::weak_ptr manager_; std::unique_ptr esrgan_; + std::unique_ptr kandinsky_; std::unique_ptr mosr_; std::vector weights_; uint64_t source_file_ = 0; @@ -37,7 +41,7 @@ namespace sd::dgl::models { public: ~ImageUpscaleModel(); GGMLRunner* runner() const; - int scale() const; + int scale(int requested = 0) const; ModelLoader::FileId source_file() const { return source_file_; } }; @@ -52,7 +56,8 @@ namespace sd::dgl::models { Tensor upscale_image_tensor(ImageUpscaleModel& model, const Tensor& input, int n_threads, - int tile_size); + int tile_size, + int factor = 0); } #endif // __SD_DGL_MODELS_IMAGE_UPSCALE_H__ diff --git a/src/dgl/models/upscaler.cpp b/src/dgl/models/upscaler.cpp index 169c30dd48..09ab24fb25 100644 --- a/src/dgl/models/upscaler.cpp +++ b/src/dgl/models/upscaler.cpp @@ -4,9 +4,9 @@ #include #include "core/ggml_extend_backend.h" +#include "core/ggml_runner.h" #include "core/util.h" -#include "model/upscaler/esrgan.hpp" -#include "model/upscaler/mosr.hpp" +#include "model/upscaler/scale.hpp" #include "model_loader.h" #include "stable-diffusion.h" @@ -28,19 +28,20 @@ namespace sd::dgl::models { release_weights(); } - int ImageUpscaler::get_scale() { - return model != nullptr ? model->scale() : 1; + int ImageUpscaler::get_scale(int factor) { + return model != nullptr ? model->scale(factor) : 1; } bool ImageUpscaler::init(ImageUpscalerParams params) { params_ = std::move(params); ggml_log_set(sd_ggml_log_callback, nullptr); ModelLoader loader; - if (!loader.init_from_file_and_convert_name(params_.path, "", VERSION_ESRGAN)) { + if (!sd::upscaling::load_weights(loader, params_.path)) { LOG_ERROR("init upscaler model loader failed: '%s'", params_.path.c_str()); return false; } - loader.set_wtype_override(model_data_type); + if (!loader.get_metadata().count("kandinsky_imagesr_config")) + loader.set_wtype_override(model_data_type); return build(std::move(loader)); } @@ -70,13 +71,13 @@ namespace sd::dgl::models { return load_weights_eagerly(); } - sd::Tensor ImageUpscaler::upscale_tensor(const sd::Tensor& input_tensor) { + sd::Tensor ImageUpscaler::upscale_tensor(const sd::Tensor& input_tensor, int factor) { Model::ExecutionScope scope(*this); scope.require_ready(); if (model == nullptr) { return {}; } - return upscale_image_tensor(*model, input_tensor, n_threads, params_.tile_size); + return upscale_image_tensor(*model, input_tensor, n_threads, params_.tile_size, factor); } bool ImageUpscaler::attach_loras() { @@ -90,10 +91,14 @@ namespace sd::dgl::models { model->runner()->set_weight_adapter(adapter); } - sd::Image ImageUpscaler::upscale(sd::Image input_image) { + sd::Image ImageUpscaler::upscale(sd::Image input_image, int factor) { sd::ParallelScope tensor_scope(tensor_executor.get()); sd::Image upscaled_image = {0, 0, 0, nullptr}; - const int scale = get_scale(); + const int scale = get_scale(factor); + if (scale <= 0) { + LOG_ERROR("unsupported upscale factor: %d", factor); + return upscaled_image; + } int output_width = (int)input_image.width * scale; int output_height = (int)input_image.height * scale; LOG_INFO("upscaling from (%i x %i) to (%i x %i)", @@ -102,7 +107,7 @@ namespace sd::dgl::models { sd::Tensor input_tensor = sd_image_to_tensor(input_image); sd::Tensor upscaled; int64_t t0 = ggml_time_ms(); - upscaled = upscale_tensor(input_tensor); + upscaled = upscale_tensor(input_tensor, scale); if (upscaled.empty()) { return upscaled_image; } diff --git a/src/dgl/models/upscaler.h b/src/dgl/models/upscaler.h index 71a28f6c41..353eb56252 100644 --- a/src/dgl/models/upscaler.h +++ b/src/dgl/models/upscaler.h @@ -31,9 +31,9 @@ namespace sd::dgl::models { ~ImageUpscaler() override; bool init(ImageUpscalerParams params); - int get_scale(); - sd::Tensor upscale_tensor(const sd::Tensor& input_tensor); - sd::Image upscale(sd::Image input_image); + int get_scale(int factor = 0); + sd::Tensor upscale_tensor(const sd::Tensor& input_tensor, int factor = 0); + sd::Image upscale(sd::Image input_image, int factor = 0); private: ImageUpscalerParams params_; diff --git a/src/model/upscaler/kandinsky_imagesr.cpp b/src/model/upscaler/kandinsky_imagesr.cpp new file mode 100644 index 0000000000..5866031fd9 --- /dev/null +++ b/src/model/upscaler/kandinsky_imagesr.cpp @@ -0,0 +1,184 @@ +#include "model/upscaler/kandinsky_imagesr.hpp" + +#include +#include + +#include "json.hpp" +#include "model/vae/auto_encoder_kl.hpp" +#include "model_loader.h" +#include "runtime/tiling.h" + +namespace KandinskyImageSR { + static constexpr int tile_side = 1024; + static constexpr float timestep_x2 = 0.15f; + static constexpr float timestep_x4 = 0.244f; + + static int timestep_row(const std::vector& steps, float t) { + for (size_t i = 0; i < steps.size(); ++i) { + if (std::abs(steps[i] - t) <= 1e-6f) { + return static_cast(i); + } + } + throw std::runtime_error("missing baked timestep " + std::to_string(t)); + } + + struct BundleConfig { + KandinskyImageSRConfig transformer; + int row_x2, row_x4; + }; + + static BundleConfig read_bundle_config(const ModelLoader& loader) { + const auto json = nlohmann::json::parse(loader.get_metadata().at("kandinsky_imagesr_config")); + const auto steps = json.at("baked_timesteps").get>(); + const auto axes = json.at("axes_dims").get>(); + if (json.at("_class_name") != "KandinskyImageSRBakedTransformer3DModel" || + json.at("attention_type") != "regular" || json.at("visual_cond") != false || + json.at("patch_size") != nlohmann::json::array({1, 2, 2}) || json.at("baked_latent_size") != tile_side / 8 || + json.at("in_visual_dim") != 16 || json.at("out_visual_dim") != 16 || + axes != std::vector{32, 48, 48} || json.at("num_visual_blocks") != 50) { + throw std::runtime_error("unsupported ImageSR transformer configuration"); + } + const auto& tensors = loader.get_tensor_storage_map(); + const auto config = KandinskyImageSRConfig::detect_from_weights(tensors, json.at("num_visual_blocks").get(), axes); + if (config.dim != 2560 || config.ff_dim != 10240 || config.time_dim != 512 || config.rows != static_cast(steps.size())) { + throw std::runtime_error("incompatible transformer weight dimensions"); + } + return {config, timestep_row(steps, timestep_x2), timestep_row(steps, timestep_x4)}; + } + + bool probe_bundle(const ModelLoader& loader) { + try { + const auto config = read_bundle_config(loader); + // Check both networks against the checkpoint headers without allocating weight buffers. + std::unique_ptr ctx( + ggml_init({MAX_PARAMS_TENSOR_NUM * ggml_tensor_overhead(), nullptr, true}), ggml_free); + if (!ctx) + return false; + const auto& tensors = loader.get_tensor_storage_map(); + const std::string vae_prefix = "first_stage_model"; + Transformer model(config.transformer); + model.init(ctx.get()); + AutoEncoderKLModel vae(VERSION_FLUX, false, false, false, tensors, vae_prefix); + vae.init(ctx.get(), tensors, vae_prefix); + std::map expected; + model.get_param_tensors(expected); + vae.get_param_tensors(expected, vae_prefix); + for (const auto& [name, tensor] : expected) { + const auto it = tensors.find(name); + if (it == tensors.end() || !std::equal(std::begin(tensor->ne), std::end(tensor->ne), it->second.ne)) + return false; + } + return true; + } catch (const std::exception& e) { + LOG_DEBUG("invalid Kandinsky ImageSR bundle: %s", e.what()); + return false; + } + } + + std::unique_ptr Upscaler::create(const ModelLoader& loader, ggml_backend_t backend, std::shared_ptr manager, bool direct) { + try { + const auto config = read_bundle_config(loader); + const auto& tensors = loader.get_tensor_storage_map(); + auto upscaler = std::make_unique(); + upscaler->row_x2 = config.row_x2; + upscaler->row_x4 = config.row_x4; + upscaler->transformer = std::make_unique(backend, tensors, config.transformer, tile_side / 8, manager); + upscaler->vae = std::make_shared(backend, tensors, "first_stage_model", false, false, VERSION_FLUX, manager); + upscaler->vae->set_conv2d_direct_enabled(direct); + upscaler->vae->set_flash_attention_enabled(true); + return upscaler; + } catch (const std::exception& e) { + LOG_ERROR("cannot load Kandinsky ImageSR bundle: %s", e.what()); + return nullptr; + } + } + + void Upscaler::get_param_tensors(std::map& tensors) { + transformer->model.get_param_tensors(tensors); + vae->get_param_tensors(tensors); + } + + static std::vector tile_starts(int64_t length, int side) { + int64_t last = std::max(0, length - side); + std::vector starts; + for (int64_t i = 0; i < last; i += side * 3 / 4) { + starts.push_back(i); + } + starts.push_back(last); + return starts; + } + + static std::vector hann_window(bool first, bool last) { + std::vector weights(tile_side, 1.f); + for (int i = first ? tile_side / 2 : 0; i < (last ? tile_side / 2 : tile_side); ++i) { + weights[i] = 0.5f - 0.5f * std::cos(6.283185307179586f * i / tile_side); + } + return weights; + } + + static sd::Tensor prepare_tile(const sd::Tensor& image, int64_t left, int64_t top, int side) { + const auto width = image.shape()[0], height = image.shape()[1]; + sd::Tensor tile({side, side, 3, 1}); + const int64_t copy_width = std::min(side, width - left); + for (int c = 0; c < 3; ++c) { + for (int y = 0; y < side; ++y) { + auto src = image.data() + (c * height + std::min(height - 1, top + y)) * width + left; + auto dst = tile.data() + (c * side + y) * side; + std::copy_n(src, copy_width, dst); + std::fill(dst + copy_width, dst + side, src[copy_width - 1]); + } + } + return sd::ops::clamp(sd::ops::interpolate(tile, {tile_side, tile_side, 3, 1}, sd::ops::InterpolateMode::Bicubic), 0.f, 1.f); + } + + static sd::Tensor upscale_tiles(const sd::Tensor& image, int factor, const TileProcessCallback& predict) { + const auto width = image.shape()[0] * factor, height = image.shape()[1] * factor; + const int side = tile_side / factor; + const auto xs = tile_starts(image.shape()[0], side), ys = tile_starts(image.shape()[1], side); + sd::Tensor output({width, height, 3, 1}); + sd::Tensor weights({width, height}); + for (auto top : ys) { + const auto wy = hann_window(top == 0, top == ys.back()); + for (auto left : xs) { + auto tile = predict(prepare_tile(image, left, top, side)); + if (tile.empty()) { + return {}; + } + const auto wx = hann_window(left == 0, left == xs.back()); + for (int y = 0; y < std::min(tile_side, height - top * factor); ++y) { + auto dst = (top * factor + y) * width + left * factor; + for (int x = 0; x < std::min(tile_side, width - left * factor); ++x) { + const float weight = wy[y] * wx[x]; + weights[dst + x] += weight; + for (int c = 0; c < 3; ++c) { + output[c * width * height + dst + x] += weight * tile[(c * tile_side + y) * tile_side + x]; + } + } + } + } + } + output /= weights; + return output; + } + + sd::Tensor Upscaler::upscale(int threads, const sd::Tensor& image, int factor) { + if ((factor != 2 && factor != 4) || image.shape()[3] != 1) { + LOG_ERROR("Kandinsky ImageSR expects one image and a scale factor of 2 or 4"); + return {}; + } + const float t = factor == 2 ? timestep_x2 : timestep_x4; + return upscale_tiles(image, factor, [&](const sd::Tensor& pixels) -> sd::Tensor { + auto moments = vae->encode(threads, pixels, {}); + if (moments.empty()) { + return {}; + } + // ImageSR takes the posterior mode and applies only the FLUX VAE scale. + auto latent = sd::ops::slice(moments, 2, 0, 16) * vae->scale_factor; + auto v = transformer->predict(threads, latent, factor == 2 ? row_x2 : row_x4); + if (v.empty()) { + return {}; + } + return vae->decode(threads, (latent - t * v) / vae->scale_factor, {}); + }); + } +} // namespace KandinskyImageSR diff --git a/src/model/upscaler/kandinsky_imagesr.hpp b/src/model/upscaler/kandinsky_imagesr.hpp new file mode 100644 index 0000000000..320868c72c --- /dev/null +++ b/src/model/upscaler/kandinsky_imagesr.hpp @@ -0,0 +1,163 @@ +#ifndef __SD_MODEL_UPSCALER_KANDINSKY_IMAGESR_HPP__ +#define __SD_MODEL_UPSCALER_KANDINSKY_IMAGESR_HPP__ + +#include +#include +#include + +#include "model/common/ggml_block.hpp" +#include "model/common/rope.hpp" +#include "model/diffusion/dit.hpp" + +struct AutoEncoderKL; +class ModelLoader; + +namespace KandinskyImageSR { + struct KandinskyImageSRConfig { + int64_t dim, time_dim, ff_dim, rows; + int layers; + std::vector axes; + int head_dim() const { return std::accumulate(axes.begin(), axes.end(), 0); } + + static KandinskyImageSRConfig detect_from_weights(const String2TensorStorage& tensors, int layers, std::vector axes) { + const auto& table = tensors.at("time_embed_table"); + const auto& ff = tensors.at("visual_transformer_blocks.0.feed_forward.in_layer.weight"); + KandinskyImageSRConfig config{ff.ne[0], table.ne[0], ff.ne[1], table.ne[1], layers, std::move(axes)}; + LOG_VERBOSE("Kandinsky ImageSR: dim = %" PRId64 ", ff_dim = %" PRId64 ", time_dim = %" PRId64 ", layers = %d", + config.dim, config.ff_dim, config.time_dim, layers); + return config; + } + }; + + inline ggml_tensor* modulate(ggml_context* ctx, ggml_tensor* x, ggml_tensor* shift, ggml_tensor* scale) { + return ggml_add(ctx, ggml_mul(ctx, ggml_norm(ctx, x, 1e-5f), ggml_scale_bias(ctx, scale, 1.f, 1.f)), shift); + } + + class VisualBlock : public GGMLBlock { + KandinskyImageSRConfig config; + + void init_params(ggml_context* ctx, const String2TensorStorage&, std::string) override { + params["xattn_bias_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, config.dim, config.rows); + } + + ggml_tensor* project(GGMLRunnerContext* ctx, const char* name, ggml_tensor* x) { + return std::static_pointer_cast(blocks.at(name))->forward(ctx, x); + } + + public: + explicit VisualBlock(const KandinskyImageSRConfig& config) : config(config) { + blocks["visual_modulation.out_layer"] = std::make_shared(config.time_dim, 9 * config.dim); + for (const char* name : {"to_query", "to_key", "to_value", "out_layer"}) { + blocks[std::string("self_attention.") + name] = std::make_shared(config.dim, config.dim); + } + for (const char* name : {"query_norm", "key_norm"}) { + blocks[std::string("self_attention.") + name] = std::make_shared(config.head_dim(), std::numeric_limits::epsilon()); + } + blocks["feed_forward.in_layer"] = std::make_shared(config.dim, config.ff_dim, false); + blocks["feed_forward.out_layer"] = std::make_shared(config.ff_dim, config.dim, false); + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* time, ggml_tensor* pe, int row) { + auto g = ctx->ggml_ctx; + auto modulation = project(ctx, "visual_modulation.out_layer", time); + auto part = [&](int index) { + return ggml_view_1d(g, modulation, config.dim, index * config.dim * modulation->nb[0]); + }; + auto h = modulate(g, x, part(0), part(1)); + auto heads = [&](const char* name) { + return ggml_reshape_3d(g, project(ctx, name, h), config.head_dim(), config.dim / config.head_dim(), x->ne[1]); + }; + auto q = project(ctx, "self_attention.query_norm", heads("self_attention.to_query")); + auto k = project(ctx, "self_attention.key_norm", heads("self_attention.to_key")); + h = Rope::attention(ctx, q, k, heads("self_attention.to_value"), pe, nullptr); + x = ggml_add(g, x, ggml_mul(g, project(ctx, "self_attention.out_layer", h), part(2))); + + auto table = params.at("xattn_bias_table"); + x = ggml_add(g, x, ggml_view_1d(g, table, config.dim, row * table->nb[1])); + h = modulate(g, x, part(6), part(7)); + h = ggml_gelu_erf(g, project(ctx, "feed_forward.in_layer", h)); + return ggml_add(g, x, ggml_mul(g, project(ctx, "feed_forward.out_layer", h), part(8))); + } + }; + + class Transformer : public GGMLBlock { + KandinskyImageSRConfig config; + std::vector> layers; + std::shared_ptr input, modulation, output; + + void init_params(ggml_context* ctx, const String2TensorStorage&, std::string) override { + params["time_embed_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, config.time_dim, config.rows); + } + + public: + explicit Transformer(const KandinskyImageSRConfig& config) : config(config) { + blocks["visual_embeddings.in_layer"] = input = std::make_shared(64, config.dim); + blocks["out_layer.modulation.out_layer"] = modulation = std::make_shared(config.time_dim, 2 * config.dim); + blocks["out_layer.out_layer"] = output = std::make_shared(config.dim, 64); + for (int i = 0; i < config.layers; ++i) { + layers.push_back(std::make_shared(config)); + blocks["visual_transformer_blocks." + std::to_string(i)] = layers.back(); + } + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* latent, ggml_tensor* pe, int row) { + auto g = ctx->ggml_ctx; + auto table = params.at("time_embed_table"); + auto time = ggml_silu(g, ggml_view_1d(g, table, config.time_dim, row * table->nb[1])); + // The input projection packs (patch_y, patch_x, channel), the output packs (channel, patch_y, patch_x). + auto x = input->forward(ctx, DiT::patchify(ctx, latent, 2, 2, false)); + for (size_t i = 0; i < layers.size(); ++i) { + x = layers[i]->forward(ctx, x, time, pe, row); + sd::ggml_graph_cut::mark_graph_cut(x, "imagesr.block." + std::to_string(i), "x"); + } + auto m = modulation->forward(ctx, time); + x = modulate(g, x, ggml_view_1d(g, m, config.dim, 0), ggml_view_1d(g, m, config.dim, config.dim * m->nb[0])); + return DiT::unpatchify(ctx, output->forward(ctx, x), latent->ne[1] / 2, latent->ne[0] / 2, 2, 2, true); + } + }; + + struct Runner : GGMLRunner { + Transformer model; + sd::Tensor pe; + + Runner(ggml_backend_t backend, + const String2TensorStorage& tensors, + const KandinskyImageSRConfig& config, + int latent_side, + std::shared_ptr manager) + : GGMLRunner(backend, manager), model(config) { + const auto ids = Rope::gen_flux_img_ids(latent_side, latent_side, 2, 1, 3); + pe = sd::Tensor({2, 2, config.head_dim() / 2, static_cast(ids.size())}, + Rope::embed_nd(ids, 1, 10000.f, config.axes)); + model.init(params_ctx, tensors); + set_flash_attention_enabled(true); + } + + std::string get_desc() override { return "Kandinsky ImageSR"; } + + sd::Tensor predict(int threads, const sd::Tensor& latent, int row) { + auto graph = [&]() { + auto gf = new_graph_custom(1 << 16); + auto ctx = get_context(); + auto out = model.forward(&ctx, make_input(latent), make_input(pe), row); + ggml_build_forward_expand(gf, out); + return gf; + }; + return restore_trailing_singleton_dims(GGMLRunner::compute(graph, threads, false), latent.dim()); + } + }; + + bool probe_bundle(const ModelLoader& loader); + + struct Upscaler { + std::unique_ptr transformer; + std::shared_ptr vae; + int row_x2, row_x4; + + static std::unique_ptr create(const ModelLoader& loader, ggml_backend_t backend, std::shared_ptr manager, bool direct); + void get_param_tensors(std::map& tensors); + sd::Tensor upscale(int threads, const sd::Tensor& image, int factor); + }; +} // namespace KandinskyImageSR + +#endif // __SD_MODEL_UPSCALER_KANDINSKY_IMAGESR_HPP__ diff --git a/src/model/upscaler/scale.cpp b/src/model/upscaler/scale.cpp index 9626d53a17..75aafd7e08 100644 --- a/src/model/upscaler/scale.cpp +++ b/src/model/upscaler/scale.cpp @@ -1,11 +1,15 @@ #include "model/upscaler/scale.hpp" #include "model/upscaler/esrgan.hpp" +#include "model/upscaler/kandinsky_imagesr.hpp" #include "model/upscaler/mosr.hpp" #include "model_loader.h" namespace sd::upscaling { - Description describe(const String2TensorStorage& tensors) { + Description describe(const ModelLoader& loader) { + if (loader.get_metadata().count("kandinsky_imagesr_config")) + return {Architecture::KandinskyImageSR, 4}; + const auto& tensors = loader.get_tensor_storage_map(); if (tensors.count("gblocks.0.weight")) { const auto config = MoSRConfig::detect_from_weights(tensors); return config.is_valid() ? Description{Architecture::MoSR, config.scale} : Description{}; @@ -18,10 +22,20 @@ namespace sd::upscaling { return {Architecture::ESRGAN, ESRGANConfig::detect_from_weights(tensors).scale}; } + bool load_weights(ModelLoader& loader, const std::string& path) { + if (!loader.init_from_file(path)) + return false; + loader.convert_tensors_name(loader.get_metadata().count("kandinsky_imagesr_config") ? VERSION_FLUX : VERSION_ESRGAN); + return true; + } + int probe_scale(const std::string& path) { ModelLoader loader; - if (path.empty() || !loader.init_from_file_and_convert_name(path, "", VERSION_ESRGAN)) + if (path.empty() || !load_weights(loader, path)) + return 0; + const auto description = describe(loader); + if (description.architecture == Architecture::KandinskyImageSR && !KandinskyImageSR::probe_bundle(loader)) return 0; - return describe(loader.get_tensor_storage_map()).scale; + return description.scale; } } diff --git a/src/model/upscaler/scale.hpp b/src/model/upscaler/scale.hpp index d4d10d35bd..7d1ce2f78a 100644 --- a/src/model/upscaler/scale.hpp +++ b/src/model/upscaler/scale.hpp @@ -3,17 +3,19 @@ #include -#include "model.h" +class ModelLoader; namespace sd::upscaling { enum class Architecture { Unknown, ESRGAN, - MoSR }; + MoSR, + KandinskyImageSR }; struct Description { Architecture architecture = Architecture::Unknown; int scale = 0; }; - Description describe(const String2TensorStorage& tensors); + Description describe(const ModelLoader& loader); + bool load_weights(ModelLoader& loader, const std::string& path); int probe_scale(const std::string& path); } diff --git a/src/model_loader.cpp b/src/model_loader.cpp index 65869cef83..7dbcc7f8c8 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -18,6 +18,7 @@ #include "core/file_access.h" #include "core/util.h" +#include "json.hpp" #include "model_io/gguf_io.h" #include "model_io/safetensors_io.h" #include "model_io/torch_legacy_io.h" @@ -206,9 +207,10 @@ bool ModelLoader::parse_file(const std::string& file_path, const std::string& pr } parsed_dependencies_.push_back(stamp); if (is_directory(file_path)) { - const std::string diffusers_index_path = path_join(file_path, "model_index.json"); - const std::string diffusers_unet_path = path_join(file_path, "unet/diffusion_pytorch_model.safetensors"); - const std::string safetensors_index_path = path_join(file_path, "model.safetensors.index.json"); + const auto root = std::filesystem::u8path(file_path); + const std::string diffusers_index_path = (root / "model_index.json").u8string(); + const std::string diffusers_unet_path = (root / "unet/diffusion_pytorch_model.safetensors").u8string(); + const std::string safetensors_index_path = (root / "model.safetensors.index.json").u8string(); bool has_index, has_unet, has_shard_index; if (!inspect_optional_file(diffusers_index_path, has_index) || !inspect_optional_file(diffusers_unet_path, has_unet) || @@ -218,6 +220,26 @@ bool ModelLoader::parse_file(const std::string& file_path, const std::string& pr LOG_VERBOSE("parse '%s' using root safetensors index, prefix = '%s'", file_path.c_str(), prefix.c_str()); return parse_file(safetensors_index_path, prefix); } + if (!has_unet) { + const auto config_path = (root / "transformer/config.json").u8string(); + bool has_config; + if (!inspect_optional_file(config_path, has_config)) + return false; + if (has_config) { + std::ifstream input(std::filesystem::u8path(config_path)); + auto config = nlohmann::json::parse(input, nullptr, false); + if (config.is_object() && config.value("_class_name", "") == "KandinskyImageSRBakedTransformer3DModel") { + auto transformer = (root / "transformer/diffusion_pytorch_model.safetensors").u8string(); + bool sharded; + if (!inspect_optional_file(transformer + ".index.json", sharded) || + !parse_file(sharded ? transformer + ".index.json" : transformer, prefix) || + !parse_file((root / "vae/diffusion_pytorch_model.safetensors").u8string(), prefix + "vae.")) + return false; + metadata_["kandinsky_imagesr_config"] = config.dump(); + return true; + } + } + } LOG_VERBOSE("parse '%s' using diffusers format, prefix = '%s'", file_path.c_str(), prefix.c_str()); return init_from_diffusers_file(file_path, prefix); } else if (is_gguf_file(file_path)) {