From 93eb0358c7125c562b9aa20c3f79b7801470eab6 Mon Sep 17 00:00:00 2001 From: Aleksei Pakhomov Date: Sat, 28 Nov 2026 15:53:36 +0300 Subject: [PATCH 1/6] feat: add Kandinsky ImageSR 2.0 upscaling --- README.md | 2 +- docs/kandinsky_imagesr.md | 12 ++ examples/cli/main.cpp | 9 +- examples/common/common.cpp | 21 ++- examples/common/common.h | 1 + examples/server/api.md | 9 +- examples/server/routes_sdcpp.cpp | 14 +- examples/server/runtime.cpp | 16 ++ include/stable-diffusion.h | 6 +- src/model/upscaler/kandinsky_imagesr.cpp | 190 +++++++++++++++++++++++ src/model/upscaler/kandinsky_imagesr.hpp | 163 +++++++++++++++++++ src/pipeline/image.cpp | 6 +- src/upscaler.cpp | 150 +++++++++++------- src/upscaler.h | 11 +- 14 files changed, 535 insertions(+), 75 deletions(-) create mode 100644 docs/kandinsky_imagesr.md create mode 100644 src/model/upscaler/kandinsky_imagesr.cpp create mode 100644 src/model/upscaler/kandinsky_imagesr.hpp diff --git a/README.md b/README.md index 33b1ccb116..b4955e3b9e 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ API and command-line option may change frequently.*** - LoRA support, same as [stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#lora) - Latent Consistency Models support (LCM/LCM-LoRA) - Faster and memory efficient latent decoding with [TAESD](./docs/taesd.md) - - Upscale images generated with [ESRGAN](./docs/esrgan.md) + - Upscale images with [ESRGAN](./docs/esrgan.md) or [Kandinsky ImageSR 2.0](./docs/kandinsky_imagesr.md) - Supported backends - CPU (AVX, AVX2 and AVX512 support for x86 architectures) - CUDA diff --git a/docs/kandinsky_imagesr.md b/docs/kandinsky_imagesr.md new file mode 100644 index 0000000000..f375f29663 --- /dev/null +++ b/docs/kandinsky_imagesr.md @@ -0,0 +1,12 @@ +# Kandinsky ImageSR 2.0 + +Kandinsky ImageSR uses the same transformer and FLUX VAE for both 2× and 4× super-resolution. Download the transformer configuration, all transformer shards and their index, and the VAE from the [official model bundle](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0). + +```sh +hf download kandinskylab/Kandinsky-ImageSR-2.0 --include 'transformer/*' 'vae/*' --local-dir models/Kandinsky-ImageSR-2.0 +sd-cli -M upscale -i input.png --upscale-model models/Kandinsky-ImageSR-2.0 --upscale-factor 2 -o output.png +``` + +Use `--upscale-factor 4` for 4×, the default. Both scales use the baked zero-text conditioning and take one flow step per tile. The timestep is 0.15 for 2× and 0.244 for 4×. Tiles overlap by 25% and have a fixed output size of 1024×1024. The output is cropped to the requested multiple of the input dimensions. + +The C API accepts the bundle directory in `new_upscaler_ctx` and the scale in `upscale`. For the server, place the bundle directory under `--hires-upscalers-dir` and use its directory name as the `upscaler` in [the upscale endpoint](../examples/server/api.md#post-sdcppv1upscale). diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index dc79b8ce10..dc2701f4a1 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -942,7 +942,6 @@ int main(int argc, const char* argv[]) { } } - int upscale_factor = 4; // unused for RealESRGAN_x4plus_anime_6B.pth if (ctx_params.esrgan_path.size() > 0 && gen_params.upscale_repeats > 0) { UpscalerCtxPtr upscaler_ctx(new_upscaler_ctx(ctx_params.esrgan_path.c_str(), ctx_params.diffusion_conv_direct, @@ -953,6 +952,9 @@ int main(int argc, const char* argv[]) { if (upscaler_ctx == nullptr) { LOG_ERROR("new_upscaler_ctx failed"); + if (cli_params.mode == UPSCALE) { + return 1; + } } else { for (int i = 0; i < num_results; i++) { if (results[i].data == nullptr) { @@ -965,12 +967,15 @@ int main(int argc, const char* argv[]) { int upscaled_count = 0; bool upscale_ok = upscale(upscaler_ctx.get(), current_image.get(), - upscale_factor, + gen_params.upscale_factor, &upscaled_images, &upscaled_count); if (!upscale_ok || upscaled_count <= 0 || upscaled_images[0].data == nullptr) { free_sd_images(upscaled_images, upscaled_count); LOG_ERROR("upscale failed"); + if (cli_params.mode == UPSCALE) { + return 1; + } break; } sd_image_t upscaled_image = upscaled_images[0]; diff --git a/examples/common/common.cpp b/examples/common/common.cpp index dc15b4e25e..4be588bd5b 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -534,7 +534,7 @@ ArgOptions SDContextParams::get_options() { &pulid_weights_path}, {"", "--upscale-model", - "path to esrgan model.", + "path to an ESRGAN model file or Kandinsky ImageSR 2.0 bundle directory", 0, &esrgan_path}, {"", @@ -1187,9 +1187,13 @@ ArgOptions SDGenerationParams::get_options() { "shift timestep for NitroFusion models (default: 0). " "recommended N for NitroSD-Realism around 250 and 500 for NitroSD-Vibrant", &sample_params.shifted_timestep}, + {"", + "--upscale-factor", + "Kandinsky ImageSR scale factor, 2 or 4 (default: 4)", + &upscale_factor}, {"", "--upscale-repeats", - "Run the ESRGAN upscaler this many times (default: 1)", + "Run the upscaler this many times (default: 1)", &upscale_repeats}, {"", "--upscale-tile-size", @@ -2009,6 +2013,13 @@ static bool resolve_model_file_from_dir(const std::string& model_name, } } + const auto bundle = model_dir_path / model_name; + if (model_name != "." && model_name != ".." && fs::is_directory(bundle) && + fs::is_regular_file(bundle / "transformer" / "config.json") && + get_upscaler_model_scale(bundle.u8string().c_str()) > 0) { + resolved_path = bundle.lexically_normal().string(); + return true; + } LOG_ERROR("can not find %s %s in %s", label, model_name.c_str(), model_dir_path.lexically_normal().string().c_str()); return false; } @@ -2096,6 +2107,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); @@ -2575,6 +2587,10 @@ bool SDGenerationParams::validate(SDMode mode) { return false; } + if (upscale_factor != 2 && upscale_factor != 4) { + LOG_ERROR("error: --upscale-factor must be 2 or 4"); + return false; + } if (upscale_repeats < 1) { return false; } @@ -2919,6 +2935,7 @@ std::string SDGenerationParams::to_string() const { << " strength: " << strength << ",\n" << " control_strength: " << control_strength << ",\n" << " seed: " << seed << ",\n" + << " upscale_factor: " << upscale_factor << ",\n" << " upscale_repeats: " << upscale_repeats << ",\n" << " upscale_tile_size: " << upscale_tile_size << ",\n" << " hires: { enabled: " << (hires_enabled ? "true" : "false") diff --git a/examples/common/common.h b/examples/common/common.h index d0d39b738d..b654fc94de 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -256,6 +256,7 @@ struct SDGenerationParams { std::string pulid_id_embedding_path; float pulid_id_weight = 1.0f; + int upscale_factor = 4; int upscale_repeats = 1; int upscale_tile_size = 128; diff --git a/examples/server/api.md b/examples/server/api.md index 541e260a59..52ea3355d5 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -651,11 +651,7 @@ Typical status codes: #### `POST /sdcpp/v1/upscale` -Runs one RGB ESRGAN upscaler over an image, with no generation involved. Latent upscaler models remain available for hires generation but cannot be used here. - -This is the HTTP equivalent of `sd-cli -M upscale`: no diffusion model, text -encoder or sampling is used, so it is fast enough to answer synchronously and -does not create a job. +Runs an RGB upscaler synchronously, like `sd-cli -M upscale`. Place an ESRGAN model file or a Kandinsky ImageSR 2.0 bundle directory under `--hires-upscalers-dir`. Request fields: @@ -664,7 +660,8 @@ Request fields: | `image` | `string` | Required. Base64 or data URL image | | `upscaler` | `string` | A name from `upscalers` with `image_upscale: true`; the first compatible entry when omitted | | `repeats` | `integer` | Run the upscaler this many times, 1 to 4 (default `1`) | -| `tile_size` | `integer` | Tile size, defaulting to the server's `--upscale-tile-size` | +| `upscale_factor` | `integer` | Kandinsky ImageSR accepts 2 or 4 (default 4). ESRGAN uses its model scale. | +| `tile_size` | `integer` | ESRGAN tile size, defaulting to the server's `--upscale-tile-size`. Kandinsky ImageSR uses 1024-pixel output tiles. | | `output_format` | `string` | `png`, `jpeg`, or `webp` when built with WebP support (default `png`); unsupported formats return 400 | | `output_compression` | `integer` | Range is clamped to `0..100` | diff --git a/examples/server/routes_sdcpp.cpp b/examples/server/routes_sdcpp.cpp index b8767b6293..578ea489d0 100644 --- a/examples/server/routes_sdcpp.cpp +++ b/examples/server/routes_sdcpp.cpp @@ -474,7 +474,7 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(R"({"error":"body must be an object"})", "application/json"); return; } - for (const char* key : {"repeats", "tile_size", "output_compression"}) { + for (const char* key : {"repeats", "tile_size", "upscale_factor", "output_compression"}) { if (!body.contains(key)) { continue; } @@ -535,7 +535,7 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { if (model_path.empty()) { res.status = 400; res.set_content(json({{"error", wanted.empty() - ? std::string("no RGB ESRGAN upscaler models are available; " + ? std::string("no RGB upscaler models are available; " "start the server with --hires-upscalers-dir") : "no compatible image upscaler called " + wanted}}) .dump(), @@ -543,7 +543,8 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { return; } - if (!valid_upscale_dimensions(input.get(), model_scale, repeats)) { + const int requested_factor = body.value("upscale_factor", model_scale); + if (!valid_upscale_dimensions(input.get(), requested_factor, repeats)) { res.status = 400; res.set_content(R"({"error":"upscaled dimensions must not exceed 8192 x 8192"})", "application/json"); return; @@ -562,7 +563,12 @@ void register_sdcpp_api_endpoints(httplib::Server& svr, ServerRuntime& rt) { res.set_content(R"({"error":"the upscaler model could not be loaded"})", "application/json"); return; } - const int factor = get_upscale_factor(upscaler_ctx.get()); + const int factor = body.contains("upscale_factor") ? requested_factor : get_upscale_factor(upscaler_ctx.get()); + if (!upscaler_supports_factor(upscaler_ctx.get(), factor)) { + res.status = 400; + res.set_content(R"({"error":"unsupported scale factor for this upscaler"})", "application/json"); + return; + } // The model file may have changed since its metadata was cached. if (!valid_upscale_dimensions(input.get(), factor, repeats)) { res.status = 400; diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index 3a209313a3..2fbbdf079b 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -334,6 +334,22 @@ void refresh_upscaler_cache(ServerRuntime& rt) { while (!ec && it != end) { std::error_code entry_ec; bool is_reg = it->is_regular_file(entry_ec); + if (!entry_ec && it->is_directory(entry_ec)) { + const fs::path& path = it->path(); + if (fs::is_regular_file(path / "transformer" / "config.json", entry_ec)) { + UpscalerEntry entry; + entry.name = entry.path = path.filename().u8string(); + entry.fullpath = fs::absolute(path).lexically_normal().u8string(); + entry.image_upscale_factor = get_upscaler_model_scale(entry.fullpath.c_str()); + if (entry.image_upscale_factor > 0) { + entry.model_name = "Kandinsky ImageSR 2.0"; + entry.scale = entry.image_upscale_factor; + new_cache.push_back(std::move(entry)); + } + } + it.increment(ec); + continue; + } if (entry_ec || !is_reg) { it.increment(ec); continue; diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h index 8e5577d5e0..48f3f5df83 100644 --- a/include/stable-diffusion.h +++ b/include/stable-diffusion.h @@ -545,7 +545,7 @@ SD_API bool generate_video(sd_ctx_t* sd_ctx, typedef struct upscaler_ctx_t upscaler_ctx_t; -SD_API upscaler_ctx_t* new_upscaler_ctx(const char* esrgan_path, +SD_API upscaler_ctx_t* new_upscaler_ctx(const char* model_path, bool direct, int n_threads, int tile_size, @@ -553,6 +553,7 @@ SD_API upscaler_ctx_t* new_upscaler_ctx(const char* esrgan_path, const char* params_backend); SD_API void free_upscaler_ctx(upscaler_ctx_t* upscaler_ctx); +// Kandinsky ImageSR accepts a factor of 2 or 4. ESRGAN uses the intrinsic model scale. SD_API bool upscale(upscaler_ctx_t* upscaler_ctx, sd_image_t input_image, uint32_t upscale_factor, @@ -560,7 +561,8 @@ SD_API bool upscale(upscaler_ctx_t* upscaler_ctx, int* num_images_out); SD_API int get_upscale_factor(upscaler_ctx_t* upscaler_ctx); -// Reads model metadata only; returns 0 if the file is not a recognized RGB ESRGAN model. +SD_API bool upscaler_supports_factor(upscaler_ctx_t* upscaler_ctx, uint32_t factor); +// Returns the default scale from model metadata, or 0 for an unrecognized upscaler. SD_API int get_upscaler_model_scale(const char* model_path); typedef struct adetailer_ctx_t adetailer_ctx_t; diff --git a/src/model/upscaler/kandinsky_imagesr.cpp b/src/model/upscaler/kandinsky_imagesr.cpp new file mode 100644 index 0000000000..9552391c36 --- /dev/null +++ b/src/model/upscaler/kandinsky_imagesr.cpp @@ -0,0 +1,190 @@ +#include "model/upscaler/kandinsky_imagesr.hpp" + +#include +#include "json.hpp" +#include "model/vae/auto_encoder_kl.hpp" +#include "model_io/safetensors_io.h" +#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 Bundle { + std::string transformer_path; + std::string vae_path; + std::vector axes; + int layers; + int64_t rows; + int row_x2, row_x4; + }; + + static Bundle read_bundle(const std::string& path) { + std::ifstream input(std::filesystem::u8path(path) / "transformer" / "config.json"); + const auto json = nlohmann::json::parse(input); + 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"); + } + auto transformer_path = path_join(path, "transformer/diffusion_pytorch_model.safetensors"); + if (file_exists(transformer_path + ".index.json")) { + transformer_path += ".index.json"; + } + return {transformer_path, path_join(path, "vae/diffusion_pytorch_model.safetensors"), axes, + json.at("num_visual_blocks").get(), static_cast(steps.size()), + timestep_row(steps, timestep_x2), timestep_row(steps, timestep_x4)}; + } + + bool is_bundle(const std::string& path) { + try { + const auto bundle = read_bundle(path); + if (!is_safetensors_file(bundle.vae_path)) { + return false; + } + if (ends_with(bundle.transformer_path, ".index.json")) { + std::vector shards; + return read_safetensors_index_file(bundle.transformer_path, shards) && + std::all_of(shards.begin(), shards.end(), is_safetensors_file); + } + return is_safetensors_file(bundle.transformer_path); + } catch (const std::exception&) { + return false; + } + } + + std::unique_ptr Upscaler::load(const std::string& path, ModelLoader& loader, ggml_backend_t backend, std::shared_ptr manager, bool direct) { + try { + const auto bundle = read_bundle(path); + if (!loader.init_from_file_and_convert_name(bundle.vae_path, "vae.", VERSION_FLUX) || + !loader.add_file(bundle.transformer_path)) { + throw std::runtime_error("could not load the transformer or VAE weights"); + } + const auto& tensors = loader.get_tensor_storage_map(); + const auto config = KandinskyImageSRConfig::detect_from_weights(tensors, bundle.layers, bundle.axes); + if (config.dim != 2560 || config.ff_dim != 10240 || config.time_dim != 512 || config.rows != bundle.rows) { + throw std::runtime_error("incompatible transformer weight dimensions"); + } + auto upscaler = std::make_unique(); + upscaler->row_x2 = bundle.row_x2; + upscaler->row_x4 = bundle.row_x4; + upscaler->transformer = std::make_unique(backend, tensors, config, 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': %s", path.c_str(), e.what()); + return nullptr; + } + } + + void Upscaler::get_param_tensors(std::map& tensors) { + transformer->model.get_param_tensors(tensors); + vae->get_param_tensors(tensors); + } + + void Upscaler::set_max_graph_vram_bytes(size_t bytes) { + transformer->set_max_graph_vram_bytes(bytes); + vae->set_max_graph_vram_bytes(bytes); + } + + 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..ace23aabf6 --- /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(g, 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(g, 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), latent.dim()); + } + }; + bool is_bundle(const std::string& path); + + struct Upscaler { + std::unique_ptr transformer; + std::shared_ptr vae; + int row_x2, row_x4; + + static std::unique_ptr load(const std::string& path, ModelLoader& loader, ggml_backend_t backend, std::shared_ptr manager, bool direct); + void get_param_tensors(std::map& tensors); + void set_max_graph_vram_bytes(size_t bytes); + sd::Tensor upscale(int threads, const sd::Tensor& image, int factor); + }; +} // namespace KandinskyImageSR + +#endif // __SD_MODEL_UPSCALER_KANDINSKY_IMAGESR_HPP__ diff --git a/src/pipeline/image.cpp b/src/pipeline/image.cpp index d3d25c8af4..80c2842386 100644 --- a/src/pipeline/image.cpp +++ b/src/pipeline/image.cpp @@ -731,7 +731,11 @@ namespace sd::pipeline { sd::Tensor upscaled_tensor; if (request.hires.upscaler == SD_HIRES_UPSCALER_MODEL) { - upscaled_tensor = upscaler->upscale_tensor(decoded); + const int factor = request.hires.target_width <= 2 * decoded.shape()[0] && + request.hires.target_height <= 2 * decoded.shape()[1] + ? 2 + : 4; + upscaled_tensor = upscaler->upscale_tensor(decoded, factor); if (upscaled_tensor.empty()) { LOG_ERROR("hires model upscale failed"); return {}; diff --git a/src/upscaler.cpp b/src/upscaler.cpp index dc3498e646..1ff10b3acd 100644 --- a/src/upscaler.cpp +++ b/src/upscaler.cpp @@ -1,6 +1,7 @@ #include "upscaler.h" #include "core/ggml_extend_backend.h" #include "core/util.h" +#include "model/upscaler/kandinsky_imagesr.hpp" #include "model_loader.h" #include "runtime/tiling.h" #include "stable-diffusion.h" @@ -29,12 +30,15 @@ UpscalerGGML::~UpscalerGGML() { void UpscalerGGML::set_max_graph_vram_bytes(size_t max_vram_bytes) { max_graph_vram_bytes = max_vram_bytes; + if (kandinsky_upscaler) { + kandinsky_upscaler->set_max_graph_vram_bytes(max_vram_bytes); + } if (esrgan_upscaler) { esrgan_upscaler->set_max_graph_vram_bytes(max_vram_bytes); } } -bool UpscalerGGML::load_from_file(const std::string& esrgan_path, +bool UpscalerGGML::load_from_file(const std::string& model_path, int n_threads) { sd::ParallelScope tensor_scope(&tensor_executor); ggml_log_set(sd_ggml_log_callback, nullptr); @@ -76,26 +80,32 @@ bool UpscalerGGML::load_from_file(const std::string& esrgan_path, model_manager->set_enable_mmap(false); ModelLoader model_loader; - if (!model_loader.init_from_file_and_convert_name(esrgan_path, "", VERSION_ESRGAN)) { - LOG_ERROR("init model loader from file failed: '%s'", esrgan_path.c_str()); - return false; - } - model_loader.set_wtype_override(model_data_type); - LOG_INFO("Upscaler weight type: %s", ggml_type_name(model_data_type)); - esrgan_upscaler = std::make_shared(backend_for(SDBackendModule::UPSCALER), - model_loader.get_tensor_storage_map(), - model_manager); - if (esrgan_upscaler == nullptr || esrgan_upscaler->rrdb_net == nullptr) { - LOG_ERROR("init esrgan model from metadata failed: '%s'", esrgan_path.c_str()); - return false; - } - esrgan_upscaler->set_max_graph_vram_bytes(max_graph_vram_bytes); - if (direct) { - esrgan_upscaler->set_conv2d_direct_enabled(true); - } - std::map tensors; - esrgan_upscaler->get_param_tensors(tensors); + auto backend = backend_for(SDBackendModule::UPSCALER); + if (file_exists(path_join(model_path, "transformer/config.json"))) { + kandinsky_upscaler = KandinskyImageSR::Upscaler::load(model_path, model_loader, backend, model_manager, direct); + if (!kandinsky_upscaler) { + return false; + } + kandinsky_upscaler->get_param_tensors(tensors); + } else { + if (!model_loader.init_from_file_and_convert_name(model_path, "", VERSION_ESRGAN)) { + LOG_ERROR("init model loader from file failed: '%s'", model_path.c_str()); + return false; + } + model_loader.set_wtype_override(model_data_type); + LOG_INFO("Upscaler weight type: %s", ggml_type_name(model_data_type)); + esrgan_upscaler = std::make_shared(backend, + model_loader.get_tensor_storage_map(), + model_manager); + if (esrgan_upscaler == nullptr || esrgan_upscaler->rrdb_net == nullptr) { + LOG_ERROR("init esrgan model from metadata failed: '%s'", model_path.c_str()); + return false; + } + esrgan_upscaler->set_conv2d_direct_enabled(direct); + esrgan_upscaler->get_param_tensors(tensors); + } + set_max_graph_vram_bytes(max_graph_vram_bytes); if (!model_manager->set_loader(model_loader) || !model_manager->register_param_tensors(ModelComponent::Upscaler, std::move(tensors), @@ -103,17 +113,17 @@ bool UpscalerGGML::load_from_file(const std::string& esrgan_path, backend_for(SDBackendModule::UPSCALER), params_backend_for(SDBackendModule::UPSCALER)) || !model_manager->validate_registered_tensors()) { - LOG_ERROR("register esrgan tensors with model manager failed"); + LOG_ERROR("register upscaler tensors with model manager failed"); return false; } return true; } -sd::Tensor UpscalerGGML::upscale_tensor(const sd::Tensor& input_tensor) { +sd::Tensor UpscalerGGML::upscale_tensor(const sd::Tensor& input_tensor, uint32_t factor) { sd::ParallelScope tensor_scope(&tensor_executor); if (input_tensor.empty() || input_tensor.dim() != 4 || (input_tensor.shape()[2] != 3 && input_tensor.shape()[2] != 4)) { - LOG_ERROR("esrgan expects a 4D RGB or RGBA image tensor"); + LOG_ERROR("upscaler expects a 4D RGB or RGBA image tensor"); return {}; } @@ -124,33 +134,37 @@ sd::Tensor UpscalerGGML::upscale_tensor(const sd::Tensor& input_te } const sd::Tensor& model_input = has_alpha ? rgb : input_tensor; sd::Tensor upscaled; - const int scale = esrgan_upscaler->config.scale; - if (tile_size <= 0 || (input_tensor.shape()[0] <= tile_size && input_tensor.shape()[1] <= tile_size)) { - upscaled = esrgan_upscaler->compute(n_threads, model_input); + if (kandinsky_upscaler) { + upscaled = kandinsky_upscaler->upscale(n_threads, model_input, factor); } else { - auto on_processing = [&](const sd::Tensor& input_tile) -> sd::Tensor { - auto output_tile = esrgan_upscaler->compute(n_threads, input_tile); - if (output_tile.empty()) { - LOG_ERROR("esrgan compute failed while processing a tile"); - return {}; - } - return output_tile; - }; + const int scale = esrgan_upscaler->config.scale; + if (tile_size <= 0 || (input_tensor.shape()[0] <= tile_size && input_tensor.shape()[1] <= tile_size)) { + upscaled = esrgan_upscaler->compute(n_threads, model_input); + } else { + auto on_processing = [&](const sd::Tensor& input_tile) -> sd::Tensor { + auto output_tile = esrgan_upscaler->compute(n_threads, input_tile); + if (output_tile.empty()) { + LOG_ERROR("esrgan compute failed while processing a tile"); + return {}; + } + return output_tile; + }; - upscaled = process_tiles_2d(model_input, - static_cast(input_tensor.shape()[0] * scale), - static_cast(input_tensor.shape()[1] * scale), - scale, - tile_size, - tile_size, - 0.25f, - false, - false, - on_processing); + upscaled = process_tiles_2d(model_input, + static_cast(input_tensor.shape()[0] * scale), + static_cast(input_tensor.shape()[1] * scale), + scale, + tile_size, + tile_size, + 0.25f, + false, + false, + on_processing); + } + esrgan_upscaler->runner_end(); } - esrgan_upscaler->runner_end(); if (upscaled.empty()) { - LOG_ERROR("esrgan compute failed"); + LOG_ERROR("upscale failed"); return {}; } if (has_alpha) { @@ -164,11 +178,25 @@ sd::Tensor UpscalerGGML::upscale_tensor(const sd::Tensor& input_te return upscaled; } +int UpscalerGGML::default_scale() const { + return kandinsky_upscaler ? 4 : esrgan_upscaler->config.scale; +} + sd_image_t UpscalerGGML::upscale(sd_image_t input_image, uint32_t upscale_factor) { sd::ParallelScope tensor_scope(&tensor_executor); - // upscale_factor, unused for RealESRGAN_x4plus_anime_6B.pth sd_image_t upscaled_image = {0, 0, 0, nullptr}; - const int scale = esrgan_upscaler->config.scale; + if (kandinsky_upscaler && upscale_factor != 2 && upscale_factor != 4) { + LOG_ERROR("Kandinsky ImageSR supports factors 2 and 4"); + return upscaled_image; + } + const int scale = kandinsky_upscaler ? static_cast(upscale_factor) : default_scale(); + if (!input_image.data || !input_image.width || !input_image.height || + (input_image.channel != 3 && input_image.channel != 4) || + input_image.width > INT32_MAX / scale || input_image.height > INT32_MAX / scale || + input_image.width * scale > INT32_MAX / (input_image.height * scale) / input_image.channel) { + LOG_ERROR("invalid image dimensions for upscaling"); + 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)", @@ -177,7 +205,7 @@ sd_image_t UpscalerGGML::upscale(sd_image_t input_image, uint32_t upscale_factor 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, upscale_factor); if (upscaled.empty()) { return upscaled_image; } @@ -192,24 +220,27 @@ struct upscaler_ctx_t { UpscalerGGML* upscaler = nullptr; }; -upscaler_ctx_t* new_upscaler_ctx(const char* esrgan_path_c_str, +upscaler_ctx_t* new_upscaler_ctx(const char* model_path_c_str, bool direct, int n_threads, int tile_size, const char* backend, const char* params_backend) { + if (!model_path_c_str || !model_path_c_str[0]) { + return nullptr; + } upscaler_ctx_t* upscaler_ctx = (upscaler_ctx_t*)malloc(sizeof(upscaler_ctx_t)); if (upscaler_ctx == nullptr) { return nullptr; } - std::string esrgan_path(esrgan_path_c_str); + std::string model_path(model_path_c_str); upscaler_ctx->upscaler = new UpscalerGGML(n_threads, direct, tile_size, SAFE_STR(backend), SAFE_STR(params_backend)); if (upscaler_ctx->upscaler == nullptr) { return nullptr; } - if (!upscaler_ctx->upscaler->load_from_file(esrgan_path, n_threads)) { + if (!upscaler_ctx->upscaler->load_from_file(model_path, n_threads)) { delete upscaler_ctx->upscaler; upscaler_ctx->upscaler = nullptr; free(upscaler_ctx); @@ -256,10 +287,18 @@ bool upscale(upscaler_ctx_t* upscaler_ctx, } int get_upscale_factor(upscaler_ctx_t* upscaler_ctx) { - if (upscaler_ctx == nullptr || upscaler_ctx->upscaler == nullptr || upscaler_ctx->upscaler->esrgan_upscaler == nullptr) { + if (upscaler_ctx == nullptr || upscaler_ctx->upscaler == nullptr) { return 1; } - return upscaler_ctx->upscaler->esrgan_upscaler->config.scale; + return upscaler_ctx->upscaler->default_scale(); +} + +bool upscaler_supports_factor(upscaler_ctx_t* ctx, uint32_t factor) { + if (!ctx || !ctx->upscaler) { + return false; + } + return ctx->upscaler->kandinsky_upscaler ? (factor == 2 || factor == 4) + : factor == static_cast(ctx->upscaler->default_scale()); } int get_upscaler_model_scale(const char* model_path) { @@ -267,6 +306,9 @@ int get_upscaler_model_scale(const char* model_path) { return 0; } try { + if (is_directory(model_path) && file_exists(path_join(model_path, "transformer/config.json"))) { + return KandinskyImageSR::is_bundle(model_path) ? 4 : 0; + } ModelLoader loader; if (!loader.init_from_file_and_convert_name(model_path, "", VERSION_ESRGAN)) { return 0; diff --git a/src/upscaler.h b/src/upscaler.h index c23e9d0f25..9ffbb7d6ad 100644 --- a/src/upscaler.h +++ b/src/upscaler.h @@ -10,12 +10,16 @@ #include #include +namespace KandinskyImageSR { + struct Upscaler; +} + struct UpscalerGGML { SDBackendManager backend_manager; std::shared_ptr model_manager; ggml_type model_data_type = GGML_TYPE_F16; std::shared_ptr esrgan_upscaler; - std::string esrgan_path; + std::unique_ptr kandinsky_upscaler; int n_threads; sd::ParallelExecutor tensor_executor; bool direct = false; @@ -31,10 +35,11 @@ struct UpscalerGGML { std::string params_backend_spec = ""); ~UpscalerGGML(); - bool load_from_file(const std::string& esrgan_path, + bool load_from_file(const std::string& model_path, int n_threads); void set_max_graph_vram_bytes(size_t max_vram_bytes); - sd::Tensor upscale_tensor(const sd::Tensor& input_tensor); + sd::Tensor upscale_tensor(const sd::Tensor& input_tensor, uint32_t factor = 4); + int default_scale() const; sd_image_t upscale(sd_image_t input_image, uint32_t upscale_factor); }; From 715c015cd71c531667adb4f04ed462a1ba5861c5 Mon Sep 17 00:00:00 2001 From: Aleksei Pakhomov Date: Sat, 28 Nov 2026 16:38:45 +0300 Subject: [PATCH 2/6] fix: address Kandinsky ImageSR review findings --- examples/common/common.cpp | 10 ++-- src/dgl/models/image_upscale.cpp | 7 ++- src/dgl/models/upscaler.cpp | 4 ++ src/model/upscaler/kandinsky_imagesr.cpp | 73 ++++++++++++++++++------ src/model/upscaler/kandinsky_imagesr.hpp | 4 +- src/model/upscaler/scale.cpp | 12 ++-- src/model/upscaler/scale.hpp | 4 +- src/model_loader.cpp | 13 +++-- 8 files changed, 87 insertions(+), 40 deletions(-) diff --git a/examples/common/common.cpp b/examples/common/common.cpp index 8bfa0b64db..efd342f27e 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -1930,18 +1930,16 @@ 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 / fs::u8path(model_name); - if (model_name != "." && model_name != ".." && fs::is_regular_file(bundle / "transformer" / "config.json")) { + const auto bundle = model_dir_path / name; + if (fs::is_regular_file(bundle / "transformer" / "config.json")) { resolved_path = bundle.lexically_normal().u8string(); return true; } diff --git a/src/dgl/models/image_upscale.cpp b/src/dgl/models/image_upscale.cpp index 9d2435c47f..170bb2edf3 100644 --- a/src/dgl/models/image_upscale.cpp +++ b/src/dgl/models/image_upscale.cpp @@ -64,8 +64,9 @@ 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; @@ -73,7 +74,7 @@ namespace sd::dgl::models { std::map weights; const bool kandinsky = description.architecture == sd::upscaling::Architecture::KandinskyImageSR; if (kandinsky) { - model->kandinsky_ = KandinskyImageSR::Upscaler::create(manager->model_source(model->source_file_), backend, manager, conv_direct); + model->kandinsky_ = KandinskyImageSR::Upscaler::create(source, backend, manager, conv_direct); if (!model->kandinsky_) return nullptr; model->kandinsky_->get_param_tensors(weights); diff --git a/src/dgl/models/upscaler.cpp b/src/dgl/models/upscaler.cpp index 847320a462..09ab24fb25 100644 --- a/src/dgl/models/upscaler.cpp +++ b/src/dgl/models/upscaler.cpp @@ -95,6 +95,10 @@ namespace sd::dgl::models { sd::ParallelScope tensor_scope(tensor_executor.get()); sd::Image upscaled_image = {0, 0, 0, nullptr}; 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)", diff --git a/src/model/upscaler/kandinsky_imagesr.cpp b/src/model/upscaler/kandinsky_imagesr.cpp index 4966da3eb9..bb3be7176a 100644 --- a/src/model/upscaler/kandinsky_imagesr.cpp +++ b/src/model/upscaler/kandinsky_imagesr.cpp @@ -1,5 +1,8 @@ #include "model/upscaler/kandinsky_imagesr.hpp" +#include +#include + #include "json.hpp" #include "model/vae/auto_encoder_kl.hpp" #include "model_loader.h" @@ -19,27 +22,63 @@ namespace KandinskyImageSR { throw std::runtime_error("missing baked timestep " + std::to_string(t)); } - std::unique_ptr Upscaler::create(const ModelLoader& loader, ggml_backend_t backend, std::shared_ptr manager, bool direct) { + 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 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 config = read_bundle_config(loader); + // Build only tensor descriptors so discovery checks the same transformer layout as inference. + std::unique_ptr ctx( + ggml_init({MAX_PARAMS_TENSOR_NUM * ggml_tensor_overhead(), nullptr, true}), ggml_free); + if (!ctx) + return false; + Transformer model(config.transformer); + model.init(ctx.get()); + std::map expected; + model.get_param_tensors(expected); 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"); + 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 tensors.count("first_stage_model.encoder.conv_in.weight") != 0; + } 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 = timestep_row(steps, timestep_x2); - upscaler->row_x4 = timestep_row(steps, timestep_x4); - upscaler->transformer = std::make_unique(backend, tensors, config, tile_side / 8, manager); + 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); diff --git a/src/model/upscaler/kandinsky_imagesr.hpp b/src/model/upscaler/kandinsky_imagesr.hpp index c9066fa3c0..320868c72c 100644 --- a/src/model/upscaler/kandinsky_imagesr.hpp +++ b/src/model/upscaler/kandinsky_imagesr.hpp @@ -143,10 +143,12 @@ namespace KandinskyImageSR { ggml_build_forward_expand(gf, out); return gf; }; - return restore_trailing_singleton_dims(GGMLRunner::compute(graph, threads), latent.dim()); + 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; diff --git a/src/model/upscaler/scale.cpp b/src/model/upscaler/scale.cpp index de60e4c3b4..75aafd7e08 100644 --- a/src/model/upscaler/scale.cpp +++ b/src/model/upscaler/scale.cpp @@ -1,14 +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) { - if (tensors.count("time_embed_table") && tensors.count("visual_transformer_blocks.0.xattn_bias_table") && - tensors.count("first_stage_model.encoder.conv_in.weight")) + 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{}; @@ -32,6 +33,9 @@ namespace sd::upscaling { ModelLoader loader; if (path.empty() || !load_weights(loader, path)) return 0; - return describe(loader.get_tensor_storage_map()).scale; + const auto description = describe(loader); + if (description.architecture == Architecture::KandinskyImageSR && !KandinskyImageSR::probe_bundle(loader)) + return 0; + return description.scale; } } diff --git a/src/model/upscaler/scale.hpp b/src/model/upscaler/scale.hpp index dd3f6fb79d..7d1ce2f78a 100644 --- a/src/model/upscaler/scale.hpp +++ b/src/model/upscaler/scale.hpp @@ -3,8 +3,6 @@ #include -#include "model.h" - class ModelLoader; namespace sd::upscaling { @@ -16,7 +14,7 @@ namespace sd::upscaling { 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 4f50329528..7dbcc7f8c8 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -207,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) || @@ -220,7 +221,7 @@ bool ModelLoader::parse_file(const std::string& file_path, const std::string& pr return parse_file(safetensors_index_path, prefix); } if (!has_unet) { - const auto config_path = path_join(file_path, "transformer/config.json"); + const auto config_path = (root / "transformer/config.json").u8string(); bool has_config; if (!inspect_optional_file(config_path, has_config)) return false; @@ -228,11 +229,11 @@ bool ModelLoader::parse_file(const std::string& file_path, const std::string& pr 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 = path_join(file_path, "transformer/diffusion_pytorch_model.safetensors"); + 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(path_join(file_path, "vae/diffusion_pytorch_model.safetensors"), prefix + "vae.")) + !parse_file((root / "vae/diffusion_pytorch_model.safetensors").u8string(), prefix + "vae.")) return false; metadata_["kandinsky_imagesr_config"] = config.dump(); return true; From b08ab80a9ca76ed1916f8f976a6873cee98d67ba Mon Sep 17 00:00:00 2001 From: Aleksei Pakhomov Date: Sat, 28 Nov 2026 17:29:43 +0300 Subject: [PATCH 3/6] fix: validate all Kandinsky ImageSR VAE tensors during discovery --- src/model/upscaler/kandinsky_imagesr.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/model/upscaler/kandinsky_imagesr.cpp b/src/model/upscaler/kandinsky_imagesr.cpp index bb3be7176a..5866031fd9 100644 --- a/src/model/upscaler/kandinsky_imagesr.cpp +++ b/src/model/upscaler/kandinsky_imagesr.cpp @@ -49,22 +49,26 @@ namespace KandinskyImageSR { bool probe_bundle(const ModelLoader& loader) { try { const auto config = read_bundle_config(loader); - // Build only tensor descriptors so discovery checks the same transformer layout as inference. + // 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); - const auto& tensors = loader.get_tensor_storage_map(); + 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 tensors.count("first_stage_model.encoder.conv_in.weight") != 0; + return true; } catch (const std::exception& e) { LOG_DEBUG("invalid Kandinsky ImageSR bundle: %s", e.what()); return false; From 86d8477e1ceea88c93986d48cc6e90b12cc1da31 Mon Sep 17 00:00:00 2001 From: Aleksei Pakhomov Date: Tue, 1 Dec 2026 00:21:44 +0300 Subject: [PATCH 4/6] fix: run the official Kandinsky ImageSR checkpoint through DGL --- docs/dgl/README.md | 1 + docs/dgl/kandinsky_imagesr/upscale.dgl | 84 ++++++++- docs/guides/c_api.md | 7 +- docs/models/kandinsky_imagesr.md | 52 ++---- examples/cli/main.cpp | 6 +- examples/common/common.cpp | 22 +-- examples/common/common.h | 1 - examples/common/resource_owners.hpp | 3 +- examples/server/api.md | 6 +- examples/server/runtime.cpp | 15 -- src/api/generation.cpp | 2 +- src/api/generation_hires.cpp | 5 - src/api/options.cpp | 1 - src/api/templates/image_helpers.dgl | 2 +- src/api/templates/image_hires.dgl | 2 +- src/api/templates/upscale.dgl | 2 +- src/api/upscaler.cpp | 12 +- src/config.h | 1 - src/dgl/bindings/model.cpp | 7 +- src/dgl/models/image_upscale.cpp | 35 +--- src/dgl/models/image_upscale.h | 11 +- src/dgl/models/upscaler.cpp | 27 ++- src/dgl/models/upscaler.h | 6 +- src/model.h | 1 + src/model/diffusion/kandinsky_imagesr.hpp | 149 +++++++++++++++ src/model/integrations/kandinsky_imagesr.cpp | 27 +++ src/model/upscaler/kandinsky_imagesr.cpp | 184 ------------------- src/model/upscaler/kandinsky_imagesr.hpp | 163 ---------------- src/model/upscaler/scale.cpp | 20 +- src/model/upscaler/scale.hpp | 8 +- src/model_loader.cpp | 31 +--- src/model_registry.cpp | 2 + 32 files changed, 330 insertions(+), 565 deletions(-) create mode 100644 src/model/diffusion/kandinsky_imagesr.hpp create mode 100644 src/model/integrations/kandinsky_imagesr.cpp delete mode 100644 src/model/upscaler/kandinsky_imagesr.cpp delete mode 100644 src/model/upscaler/kandinsky_imagesr.hpp diff --git a/docs/dgl/README.md b/docs/dgl/README.md index df8958cc69..3b6652c3e4 100644 --- a/docs/dgl/README.md +++ b/docs/dgl/README.md @@ -107,6 +107,7 @@ and [NumPy tensor files](../dgl.md#tensor-files). | [ADetailer](../models/adetailer.md) | [Refine an existing image](adetailer/adetailer-existing-image.dgl) · [Generate and refine](adetailer/adetailer-generated-image.dgl) | | [ESRGAN and MoSR](../models/esrgan.md) | [Generate and upscale](esrgan/sd1-5-txt2img-esrgan.dgl) · [Upscale an image](esrgan/realesrgan-x4plus-anime-6b-upscale.dgl) | | [IP-Adapter](../models/ip_adapter.md) | [SD 1.5 Classic](ip_adapter/ip-adapter-sd1-5.dgl) · [SDXL Classic](ip_adapter/ip-adapter-sdxl.dgl) · [SD 1.5 Plus](ip_adapter/ip-adapter-plus-sd1-5.dgl) · [SDXL with ControlNet](ip_adapter/ip-adapter-sdxl-controlnet.dgl) | +| [Kandinsky ImageSR 2.0](../models/kandinsky_imagesr.md) | [Upscale an image at 2× or 4×](kandinsky_imagesr/upscale.dgl) | | [LCM and LCM-LoRA](../models/lcm.md) | [LCM-LoRA with SD 1.5](lcm/lcm-lora-sd1-5.dgl) | | [LoRA](../models/lora.md) | [SD 1.5 UNet and text encoder](lora/sd1-5-lora.dgl) | | [PhotoMaker](../models/photo_maker.md) | [PhotoMaker v1](photo_maker/photomaker-v1-sdxl.dgl) · [PhotoMaker v2](photo_maker/photomaker-v2-sdxl.dgl) | diff --git a/docs/dgl/kandinsky_imagesr/upscale.dgl b/docs/dgl/kandinsky_imagesr/upscale.dgl index 14806c367b..a1d67178c3 100644 --- a/docs/dgl/kandinsky_imagesr/upscale.dgl +++ b/docs/dgl/kandinsky_imagesr/upscale.dgl @@ -1,17 +1,87 @@ # version: 0.0.0 -# docs/models/kandinsky_imagesr.md — standalone image upscaling - +# docs/models/kandinsky_imagesr.md var { - upscaler_path = "../models/Kandinsky-ImageSR-2.0" - + dit_path = "../models/Kandinsky-ImageSR-2.0/transformer/diffusion_pytorch_model.safetensors" + vae_path = "../models/Kandinsky-ImageSR-2.0/vae/diffusion_pytorch_model.safetensors" input_path = "input.png" output_path = "upscaled.png" + upscale_4x = false +} + +fn double_angle(weight, step) { + return tensor::mul(weight, tensor::affine(weight, scale = -4, offset = 4)) +} + +fn hann_window() { + # Hann(i) = sin(pi*i/1024)^2. Start at 1/32 of the angle and double it five times. + angle = tensor::mul(tensor::cast(tensor::arange(0, 1024), "f32"), 3.141592653589793 / 32768) + squared = tensor::mul(angle, angle) + sine = tensor::mul(angle, tensor::add(1, tensor::mul(squared, tensor::affine(squared, scale = 1 / 120, offset = -1 / 6)))) + return fold([0, 1, 2, 3, 4], tensor::mul(sine, sine), process = double_angle) +} + +fn boundary_window(window, index, count) { + left = tensor::full([512], 1 - math::min(1, index)) + right = tensor::full([512], 1 - math::min(1, count - index - 1)) + return tensor::maximum(window, tensor::concat([left, right], axis = 0)) +} + +fn pad_indices(length, tile) { + padded = length + tile - math::min(length, tile) + indices = tensor::cast(tensor::arange(0, padded), "f64") + return tensor::cast(tensor::clamp(indices, 0, length - 1), "i64") +} + +fn upscale_tile(state, index, pixels, geometry, predict, vae, rng, sigmas, window) { + cols = geometry.cols + row = math::floor(index / cols) + col = index - row * cols + side = geometry.side + left = math::min(col * geometry.stride, geometry.width - side) + top = math::min(row * geometry.stride, geometry.height - side) + tile = tensor::crop(pixels, axes = [0, 1], start = [left, top], size = [side, side]) + enlarged = tensor::clamp(tensor::interpolate(tile, [1024, 1024], mode = "bicubic"), 0, 1) + encoded = vae_encode(vae, enlarged, rng = rng, posterior = "mode") + # ImageSR uses the FLUX VAE scale without its latent shift. + latent = tensor::mul(encoded, 0.3611) + restored = sample(latent, sigmas, predict = predict, method = "euler", rng = rng) + decoded = vae_decode(vae, tensor::div(restored, 0.3611), dtype = "f32") + + wx = boundary_window(window, col, cols) + wy = boundary_window(window, row, geometry.rows) + weight = tensor::mul(wx, tensor::reshape(wy, [1, 1024])) + x = left * geometry.factor + y = top * geometry.factor + pad = [x, geometry.width * geometry.factor - x - 1024, y, geometry.height * geometry.factor - y - 1024] + return { + pixels = tensor::add(state.pixels, tensor::pad(tensor::mul(decoded, weight), pad)), + weights = tensor::add(state.weights, tensor::pad(weight, pad)) + } } fn main() { - upscaler = load_upscaler(upscaler_path) - image = image::load(input_path) - output = upscale(upscaler, image, factor = 2) + dit = load_dit(dit_path, flash_attn_mode = "on") + vae = load_vae(vae_path, family = "flux") + factor = if upscale_4x { 4 } else { 2 } + timestep = if upscale_4x { 0.244 } else { 0.15 } + input = image::to_f32(image::load(input_path), channels = 3) + shape = tensor::shape(input) + side = math::floor(1024 / factor) + stride = math::floor(3 * side / 4) + padded_x = tensor::index_select(input, axis = 0, indices = pad_indices(shape[0], side)) + pixels = tensor::index_select(padded_x, axis = 1, indices = pad_indices(shape[1], side)) + padded = tensor::shape(pixels) + width = padded[0] + height = padded[1] + cols = 1 + math::ceil_div(width - side, stride) + rows = 1 + math::ceil_div(height - side, stride) + geometry = {width = width, height = height, cols = cols, rows = rows, side = side, stride = stride, factor = factor} + initial = {pixels = tensor::zeros([width * factor, height * factor, 3, 1]), weights = tensor::zeros([width * factor, height * factor])} + tiles = tensor::to_list(tensor::arange(0, cols * rows)) + sum = fold(tiles, initial, process = upscale_tile, pixels = pixels, geometry = geometry, predict = predictor(dit, {}), + vae = vae, rng = make_rng("std_default", seed = 42), sigmas = tensor::vector([timestep, 0.0]), window = hann_window()) + cropped = tensor::crop(tensor::div(sum.pixels, sum.weights), axes = [0, 1], start = [0, 0], size = [shape[0] * factor, shape[1] * factor]) + output = image::to_u8(cropped) image::save(output_path, output) return output } diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index 604ffb742c..e456c0050d 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`. 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. +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. ```c sd_upscaler_opt_t* load = sd_upscaler_opt_create(); @@ -424,7 +424,6 @@ 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/kandinsky_imagesr.md b/docs/models/kandinsky_imagesr.md index a3d4596979..d4f8bb9317 100644 --- a/docs/models/kandinsky_imagesr.md +++ b/docs/models/kandinsky_imagesr.md @@ -1,66 +1,36 @@ # 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×. +Kandinsky ImageSR upscales an RGB image by 2× or 4× through DGL. Both scales use the same transformer and FLUX VAE. ## Model files -| Component | Weights and downloads | CLI option | Requirement | +| Component | Weights and downloads | DGL parameter | 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/`. | +| Kandinsky ImageSR transformer | [transformer/diffusion_pytorch_model.safetensors](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0/resolve/8c24b59ae1c5a1e7f7f211cbc184e2a3aa6ebd50/transformer/diffusion_pytorch_model.safetensors) | `dit_path` passed to `load_dit` | Baked transformer, shared by both scales | +| FLUX VAE | [vae/diffusion_pytorch_model.safetensors](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0/resolve/8c24b59ae1c5a1e7f7f211cbc184e2a3aa6ebd50/vae/diffusion_pytorch_model.safetensors) | `vae_path` passed to `load_vae` | Matching FLUX 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 -``` +The files share a name. Keep them in separate `transformer/` and `vae/` directories. ## Usage -Run the following examples from the build directory with an RGB image named `input.png`. - ### DGL -| Task | Script | +| Example | Description | | --- | --- | -| Upscale an image at 2× | [Kandinsky ImageSR upscaling](../dgl/kandinsky_imagesr/upscale.dgl) | +| [Upscale an image](../dgl/kandinsky_imagesr/upscale.dgl) | Set `upscale_4x = false` for 2× (default) or `true` for 4×. | -Set `factor = 4` in the script for 4× output. +Set the model paths, `input_path` and `output_path` in the script's `var` block. Run from the build directory. Relative paths resolve from that directory. -**Windows PowerShell** +**Windows (PowerShell)** ```powershell .\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\kandinsky_imagesr\upscale.dgl ``` -**Linux / macOS** +**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. +The script enlarges each source tile to 1024×1024, takes the VAE posterior mode and applies one Euler step at the checkpoint's calibrated timestep (0.15 for 2× or 0.244 for 4×). It blends overlapping tiles and crops edge padding to give exactly the requested output dimensions. The full-resolution RGB accumulator must fit the DGL limit of 1 GiB per tensor. diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index fbcdc44e18..e3b7202f45 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -827,9 +827,7 @@ int main(int argc, const char* argv[]) { ctx_params.linear_type)); if (upscaler_ctx == nullptr) { - LOG_ERROR("sd_upscaler_create failed: %s", sd_get_last_error()); - if (cli_params.mode == UPSCALE) - return 1; + LOG_ERROR("sd_upscaler_create failed"); } else { for (int i = 0; i < num_results; i++) { if (results[i].data == nullptr) { @@ -838,7 +836,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, gen_params.upscale_factor.value_or(0)) || !upscaled) { + if (!upscale_sd_image(upscaler_ctx.get(), current_image.get(), &upscaled, gen_params.upscale_repeats) || !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 efd342f27e..c66502fdcb 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 or MoSR weights, or a Kandinsky ImageSR bundle directory", + "path to esrgan model.", 0, &esrgan_path}, {"", @@ -1174,10 +1174,6 @@ 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)", @@ -1930,19 +1926,16 @@ static bool resolve_model_file_from_dir(const std::string& model_name, return false; }; - const auto name = fs::u8path(model_name); - if (name.empty() || name == "." || name == ".." || name.has_parent_path() || name.has_root_path() || + 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); - 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)) { @@ -2048,7 +2041,6 @@ 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); @@ -2413,10 +2405,6 @@ 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 239b399ffb..cddfaf0c88 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -257,7 +257,6 @@ 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 f5cdf3648e..83f2dca503 100644 --- a/examples/common/resource_owners.hpp +++ b/examples/common/resource_owners.hpp @@ -339,13 +339,12 @@ 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, int factor = 0) { +static inline bool upscale_sd_image(sd_upscaler_t* ctx, SDImage image, sd_result_t** result, int repeats = 1) { 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 581bb09462..ae61d0598f 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 include weight files and Kandinsky ImageSR bundle directories directly under `--hires-upscalers-dir`. Use the bundle directory name to select Kandinsky. +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. `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 include weight files and Kandinsky ImageSR bundle directories directly under `--hires-upscalers-dir`. Use the bundle directory name to select Kandinsky. +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. `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`. 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`. +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`. HTTP-only output fields: diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index ae6a8c84f3..6853acd33b 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -504,21 +504,6 @@ 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.cpp b/src/api/generation.cpp index 5de121d1c7..d1c70730be 100644 --- a/src/api/generation.cpp +++ b/src/api/generation.cpp @@ -140,7 +140,7 @@ namespace sd::api { bool supports_generation(const ModelDefinition& definition, bool video) { return definition.traits.supports_video_generation == video && definition.version != VERSION_ESRGAN && - definition.version != VERSION_SEEDVR2 && definition.version != VERSION_RELAY_VSR; + definition.version != VERSION_KANDINSKY_IMAGESR && definition.version != VERSION_SEEDVR2 && definition.version != VERSION_RELAY_VSR; } void GenerationContext::check_cancelled() const { diff --git a/src/api/generation_hires.cpp b/src/api/generation_hires.cpp index 1635f31d5a..7c11b21dc8 100644 --- a/src/api/generation_hires.cpp +++ b/src/api/generation_hires.cpp @@ -61,11 +61,6 @@ 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 e0f697bdcf..4f1970a25e 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -475,7 +475,6 @@ 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 44ff08c8c6..bb16609e55 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), factor = {{hires_upscale_factor}}) + upscaled = upscale(args.upscaler, image::to_u8(image)) 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 f13ed898ae..14c09a5445 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), factor = {{hires_upscale_factor}}) + hires_upscaled = upscale(hires_upscaler, image::to_u8(hires_pixels)) 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 40995a56ed..daa4649de0 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{{factor_option}}) + return upscale(model, image) } fn main(input_image) { diff --git a/src/api/upscaler.cpp b/src/api/upscaler.cpp index 2764d4bebe..2e2aa051e0 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, int factor = 0) { + static std::string upscale_source(const OptConfig& config, int repeats) { const auto& settings = config.context; std::string options; for (const auto& [name, spec] : std::map{{"backend", settings.backend}, {"params_backend", settings.params_backend}}) { @@ -34,7 +34,6 @@ 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}}); } } @@ -101,9 +100,7 @@ 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(config.post.factor); - if (!scale) - return sd::api::error(SD_STATUS_INVALID_ARGUMENT, "factor", "Kandinsky ImageSR supports factors 2 and 4"); + const auto scale = upscaler->model->get_scale(); for (int i = 0; i < config.post.repeats; ++i) { width *= scale; height *= scale; @@ -112,10 +109,9 @@ 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; - 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.source = config.post.repeats == 1 ? upscaler->source : sd::api::upscale_source(upscaler->context.model.config, config.post.repeats); program.inputs.emplace("input_image", sd::dgl::Value::object(std::shared_ptr(sd_tensor_retain(input), sd_tensor_free))); - auto value = sd::api::execute_program(upscaler->context, program, use_cached ? &upscaler->program : nullptr); + auto value = sd::api::execute_program(upscaler->context, program, config.post.repeats == 1 ? &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 a9476e8887..c93e84ad19 100644 --- a/src/config.h +++ b/src/config.h @@ -210,7 +210,6 @@ 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 348b1be56a..8e4af3a97c 100644 --- a/src/dgl/bindings/model.cpp +++ b/src/dgl/bindings/model.cpp @@ -35,16 +35,13 @@ namespace sd::dgl { Value execute_upscale(Values& args, RunState&) { auto image = image_view(args.at("image")); auto model = object(args, "upscaler"); - 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"); + const int64_t factor = model->get_scale(); 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, factor); + auto output = model->upscale(image); 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 170bb2edf3..3a4a8a4b28 100644 --- a/src/dgl/models/image_upscale.cpp +++ b/src/dgl/models/image_upscale.cpp @@ -3,7 +3,6 @@ #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" @@ -26,17 +25,10 @@ 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(int requested) const { - if (kandinsky_) { - if (requested == 0) - return 4; - return requested == 2 || requested == 4 ? requested : 0; - } + int ImageUpscaleModel::scale() const { if (mosr_ != nullptr) { return mosr_->config.scale; } @@ -64,21 +56,14 @@ namespace sd::dgl::models { if (model->source_file_ == 0) { return nullptr; } - const auto& source = manager->model_source(model->source_file_); - const auto& tensors = source.get_tensor_storage_map(); - const auto description = sd::upscaling::describe(source); + const auto& tensors = manager->model_source(model->source_file_).get_tensor_storage_map(); + const auto description = sd::upscaling::describe(tensors); if (description.architecture == sd::upscaling::Architecture::Unknown) { LOG_ERROR("unsupported image upscaler weights: '%s'", path.c_str()); return nullptr; } std::map weights; - 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) { + 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()); @@ -101,17 +86,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_, kandinsky ? VERSION_FLUX : VERSION_ESRGAN) || + model->source_file_, 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(), kandinsky ? "checkpoint" : ggml_type_name(weight_type)); + LOG_INFO("Upscaler architecture: %s, weight type: %s", model->runner()->get_desc().c_str(), ggml_type_name(weight_type)); return model; } - Tensor upscale_image_tensor(ImageUpscaleModel& model, const Tensor& input, int n_threads, int tile_size, int factor) { + Tensor upscale_image_tensor(ImageUpscaleModel& model, const Tensor& input, int n_threads, int tile_size) { 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 {}; @@ -125,11 +110,9 @@ 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(factor); + const int scale = model.scale(); Tensor output; - 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)) { + 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 13928a60f0..2fe9bc3f5f 100644 --- a/src/dgl/models/image_upscale.h +++ b/src/dgl/models/image_upscale.h @@ -14,9 +14,6 @@ class SDBackendManager; struct GGMLRunner; struct ESRGAN; struct MoSR; -namespace KandinskyImageSR { - struct Upscaler; -} namespace sd::dgl::models { class ImageUpscaleModel { @@ -27,11 +24,10 @@ namespace sd::dgl::models { const std::string&, bool, ggml_type); - friend Tensor upscale_image_tensor(ImageUpscaleModel&, const Tensor&, int, int, int); + friend Tensor upscale_image_tensor(ImageUpscaleModel&, const Tensor&, 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; @@ -41,7 +37,7 @@ namespace sd::dgl::models { public: ~ImageUpscaleModel(); GGMLRunner* runner() const; - int scale(int requested = 0) const; + int scale() const; ModelLoader::FileId source_file() const { return source_file_; } }; @@ -56,8 +52,7 @@ namespace sd::dgl::models { Tensor upscale_image_tensor(ImageUpscaleModel& model, const Tensor& input, int n_threads, - int tile_size, - int factor = 0); + int tile_size); } #endif // __SD_DGL_MODELS_IMAGE_UPSCALE_H__ diff --git a/src/dgl/models/upscaler.cpp b/src/dgl/models/upscaler.cpp index 09ab24fb25..169c30dd48 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/scale.hpp" +#include "model/upscaler/esrgan.hpp" +#include "model/upscaler/mosr.hpp" #include "model_loader.h" #include "stable-diffusion.h" @@ -28,20 +28,19 @@ namespace sd::dgl::models { release_weights(); } - int ImageUpscaler::get_scale(int factor) { - return model != nullptr ? model->scale(factor) : 1; + int ImageUpscaler::get_scale() { + return model != nullptr ? model->scale() : 1; } bool ImageUpscaler::init(ImageUpscalerParams params) { params_ = std::move(params); ggml_log_set(sd_ggml_log_callback, nullptr); ModelLoader loader; - if (!sd::upscaling::load_weights(loader, params_.path)) { + if (!loader.init_from_file_and_convert_name(params_.path, "", VERSION_ESRGAN)) { LOG_ERROR("init upscaler model loader failed: '%s'", params_.path.c_str()); return false; } - if (!loader.get_metadata().count("kandinsky_imagesr_config")) - loader.set_wtype_override(model_data_type); + loader.set_wtype_override(model_data_type); return build(std::move(loader)); } @@ -71,13 +70,13 @@ namespace sd::dgl::models { return load_weights_eagerly(); } - sd::Tensor ImageUpscaler::upscale_tensor(const sd::Tensor& input_tensor, int factor) { + sd::Tensor ImageUpscaler::upscale_tensor(const sd::Tensor& input_tensor) { Model::ExecutionScope scope(*this); scope.require_ready(); if (model == nullptr) { return {}; } - return upscale_image_tensor(*model, input_tensor, n_threads, params_.tile_size, factor); + return upscale_image_tensor(*model, input_tensor, n_threads, params_.tile_size); } bool ImageUpscaler::attach_loras() { @@ -91,14 +90,10 @@ namespace sd::dgl::models { model->runner()->set_weight_adapter(adapter); } - sd::Image ImageUpscaler::upscale(sd::Image input_image, int factor) { + sd::Image ImageUpscaler::upscale(sd::Image input_image) { sd::ParallelScope tensor_scope(tensor_executor.get()); sd::Image upscaled_image = {0, 0, 0, nullptr}; - const int scale = get_scale(factor); - if (scale <= 0) { - LOG_ERROR("unsupported upscale factor: %d", factor); - return upscaled_image; - } + const int scale = get_scale(); 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)", @@ -107,7 +102,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, scale); + upscaled = upscale_tensor(input_tensor); if (upscaled.empty()) { return upscaled_image; } diff --git a/src/dgl/models/upscaler.h b/src/dgl/models/upscaler.h index 353eb56252..71a28f6c41 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(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); + int get_scale(); + sd::Tensor upscale_tensor(const sd::Tensor& input_tensor); + sd::Image upscale(sd::Image input_image); private: ImageUpscalerParams params_; diff --git a/src/model.h b/src/model.h index 85dfb68d49..fb411349b8 100644 --- a/src/model.h +++ b/src/model.h @@ -74,6 +74,7 @@ enum SDVersion { VERSION_MINIMAX_H3_IMAGE, VERSION_RELAY_VSR, VERSION_SEEDVR2, + VERSION_KANDINSKY_IMAGESR, VERSION_COUNT, }; diff --git a/src/model/diffusion/kandinsky_imagesr.hpp b/src/model/diffusion/kandinsky_imagesr.hpp new file mode 100644 index 0000000000..cf2175e246 --- /dev/null +++ b/src/model/diffusion/kandinsky_imagesr.hpp @@ -0,0 +1,149 @@ +#ifndef __SD_MODEL_DIFFUSION_KANDINSKY_IMAGESR_HPP__ +#define __SD_MODEL_DIFFUSION_KANDINSKY_IMAGESR_HPP__ + +#include +#include +#include +#include + +#include "model/common/ggml_block.hpp" +#include "model/common/rope.hpp" +#include "model/diffusion/dit.hpp" +#include "model/diffusion/model.hpp" + +namespace KandinskyImageSR { + // Timesteps (in the flow denoiser's 0..1000 units) in release checkpoint row order. + static constexpr float baked_timesteps[] = {5, 10, 15, 20, 25, 35, 50, 70, 86, 100, 118, 134, 150, + 170, 180, 188.5f, 207, 210, 225.5f, 244, 270, 278, 300, 312, 346, 380}; + static constexpr int model_dim = 2560; + static constexpr int head_dim = 128; + static constexpr int time_dim = 512; + static constexpr int ff_dim = 10240; + static constexpr int num_layers = 50; + static constexpr int num_timesteps = std::size(baked_timesteps); + + 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 { + void init_params(ggml_context* ctx, const String2TensorStorage&, std::string) override { + params["visual_modulation_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 6 * model_dim, num_timesteps); + params["xattn_bias_table"] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, model_dim, num_timesteps); + } + + ggml_tensor* project(GGMLRunnerContext* ctx, const char* name, ggml_tensor* x) { + return std::static_pointer_cast(blocks.at(name))->forward(ctx, x); + } + + public: + VisualBlock() { + for (const char* name : {"to_query", "to_key", "to_value", "out_layer"}) { + blocks[std::string("self_attention.") + name] = std::make_shared(model_dim, model_dim); + } + for (const char* name : {"query_norm", "key_norm"}) { + blocks[std::string("self_attention.") + name] = std::make_shared(head_dim, std::numeric_limits::epsilon()); + } + blocks["feed_forward.in_layer"] = std::make_shared(model_dim, ff_dim, false); + blocks["feed_forward.out_layer"] = std::make_shared(ff_dim, model_dim, false); + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* pe, int row) { + auto g = ctx->ggml_ctx; + auto modulation = params.at("visual_modulation_table"); + auto part = [&](int index) { + return ggml_view_1d(g, modulation, model_dim, row * modulation->nb[1] + index * model_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), head_dim, model_dim / 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, model_dim, row * table->nb[1])); + h = modulate(g, x, part(3), part(4)); + 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(5))); + } + }; + + class Transformer : public GGMLBlock { + 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, time_dim, num_timesteps); + } + + public: + Transformer() { + blocks["visual_embeddings.in_layer"] = input_ = std::make_shared(64, model_dim); + blocks["out_layer.modulation.out_layer"] = modulation_ = std::make_shared(time_dim, 2 * model_dim); + blocks["out_layer.out_layer"] = output_ = std::make_shared(model_dim, 64); + for (int i = 0; i < num_layers; ++i) { + layers_.push_back(std::make_shared()); + 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, 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, 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, model_dim, 0), ggml_view_1d(g, m, model_dim, model_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 : DiffusionModelRunner { + Transformer model; + sd::Tensor pe; + + Runner(ggml_backend_t backend, const String2TensorStorage& tensors, std::shared_ptr manager) + : DiffusionModelRunner(backend, "model.diffusion_model", manager) { + const auto ids = Rope::gen_flux_img_ids(128, 128, 2, 1, 3); + pe = sd::Tensor({2, 2, 64, static_cast(ids.size())}, + Rope::embed_nd(ids, 1, 10000.f, {32, 48, 48})); + model.init(params_ctx, tensors, prefix); + } + + std::string get_desc() override { return "Kandinsky ImageSR DiT"; } + int get_patch_size() const override { return 2; } + using DiffusionModelRunner::get_param_tensors; + void get_param_tensors(std::map& tensors, const std::string& prefix) override { + model.get_param_tensors(tensors, prefix); + } + + sd::Tensor compute(int threads, const DiffusionParams& params) override { + const auto& latent = tensor_or_empty(params.x); + const auto& times = tensor_or_empty(params.timesteps); + if (latent.shape() != std::vector{128, 128, 16, 1} || times.numel() != 1) + throw std::runtime_error("Kandinsky ImageSR requires one 128x128 latent with 16 channels and one timestep"); + const auto row = std::find_if(std::begin(baked_timesteps), std::end(baked_timesteps), + [&](float t) { return std::abs(t - times[0]) <= 1e-3f; }); + if (row == std::end(baked_timesteps)) + throw std::runtime_error("timestep is not baked in the Kandinsky ImageSR checkpoint"); + auto graph = [&]() { + auto gf = new_graph_custom(1 << 16); + auto ctx = get_context(gf); + auto out = model.forward(&ctx, make_input(latent), make_input(pe), int(row - baked_timesteps)); + ggml_build_forward_expand(gf, out); + return gf; + }; + return restore_trailing_singleton_dims(GGMLRunner::compute(graph, threads), latent.dim()); + } + }; +} // namespace KandinskyImageSR + +#endif // __SD_MODEL_DIFFUSION_KANDINSKY_IMAGESR_HPP__ diff --git a/src/model/integrations/kandinsky_imagesr.cpp b/src/model/integrations/kandinsky_imagesr.cpp new file mode 100644 index 0000000000..80ba3626ab --- /dev/null +++ b/src/model/integrations/kandinsky_imagesr.cpp @@ -0,0 +1,27 @@ +#include "model/diffusion/kandinsky_imagesr.hpp" +#include "model_build_context.h" +#include "model_definition.h" + +static bool build_kandinsky_imagesr(const sd::model_builders::Context& ctx, const TokenizerConfig&, sd::model_builders::CoreRunners& runners) { + if (!ctx.build_diffusion || ctx.build_conditioner) + return false; + runners.diffusion = std::make_shared(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION), + ctx.tensor_storage_map, ctx.weight_manager); + return true; +} + +const std::vector& kandinsky_imagesr_definitions() { + static const std::vector definitions = [] { + ModelDefinition definition; + definition.version = VERSION_KANDINSKY_IMAGESR; + definition.name = "Kandinsky ImageSR 2.0"; + definition.id = "kandinsky_imagesr"; + definition.geometry = {2, 16, 3}; + definition.traits.is_dit = true; + definition.sampling = {FLOW_PRED, 1.f}; + definition.sampling.default_sample_method = EULER_SAMPLE_METHOD; + definition.build = build_kandinsky_imagesr; + return std::vector{definition}; + }(); + return definitions; +} diff --git a/src/model/upscaler/kandinsky_imagesr.cpp b/src/model/upscaler/kandinsky_imagesr.cpp deleted file mode 100644 index 5866031fd9..0000000000 --- a/src/model/upscaler/kandinsky_imagesr.cpp +++ /dev/null @@ -1,184 +0,0 @@ -#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 deleted file mode 100644 index 320868c72c..0000000000 --- a/src/model/upscaler/kandinsky_imagesr.hpp +++ /dev/null @@ -1,163 +0,0 @@ -#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 75aafd7e08..9626d53a17 100644 --- a/src/model/upscaler/scale.cpp +++ b/src/model/upscaler/scale.cpp @@ -1,15 +1,11 @@ #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 ModelLoader& loader) { - if (loader.get_metadata().count("kandinsky_imagesr_config")) - return {Architecture::KandinskyImageSR, 4}; - const auto& tensors = loader.get_tensor_storage_map(); + Description describe(const String2TensorStorage& tensors) { if (tensors.count("gblocks.0.weight")) { const auto config = MoSRConfig::detect_from_weights(tensors); return config.is_valid() ? Description{Architecture::MoSR, config.scale} : Description{}; @@ -22,20 +18,10 @@ 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() || !load_weights(loader, path)) - return 0; - const auto description = describe(loader); - if (description.architecture == Architecture::KandinskyImageSR && !KandinskyImageSR::probe_bundle(loader)) + if (path.empty() || !loader.init_from_file_and_convert_name(path, "", VERSION_ESRGAN)) return 0; - return description.scale; + return describe(loader.get_tensor_storage_map()).scale; } } diff --git a/src/model/upscaler/scale.hpp b/src/model/upscaler/scale.hpp index 7d1ce2f78a..d4d10d35bd 100644 --- a/src/model/upscaler/scale.hpp +++ b/src/model/upscaler/scale.hpp @@ -3,19 +3,17 @@ #include -class ModelLoader; +#include "model.h" namespace sd::upscaling { enum class Architecture { Unknown, ESRGAN, - MoSR, - KandinskyImageSR }; + MoSR }; struct Description { Architecture architecture = Architecture::Unknown; int scale = 0; }; - Description describe(const ModelLoader& loader); - bool load_weights(ModelLoader& loader, const std::string& path); + Description describe(const String2TensorStorage& tensors); int probe_scale(const std::string& path); } diff --git a/src/model_loader.cpp b/src/model_loader.cpp index 7dbcc7f8c8..8606fceeec 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -18,7 +18,6 @@ #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" @@ -207,10 +206,9 @@ bool ModelLoader::parse_file(const std::string& file_path, const std::string& pr } parsed_dependencies_.push_back(stamp); if (is_directory(file_path)) { - 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(); + 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"); 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) || @@ -220,26 +218,6 @@ 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)) { @@ -463,6 +441,9 @@ SDVersion ModelLoader::get_sd_version() const { if ((tensor_storage_map.count(prefix + "positive_conditioning") || tensor_storage_map.count(prefix + "prompt_embeds")) && (tensor_storage_map.count(prefix + "lq_proj_in.conv1.weight") || tensor_storage_map.count(prefix + "lq_proj.conv1.weight"))) return VERSION_RELAY_VSR; + if (tensor_storage_map.count(prefix + "time_embed_table") && + tensor_storage_map.count(prefix + "visual_transformer_blocks.0.visual_modulation_table")) + return VERSION_KANDINSKY_IMAGESR; if (prefix != "wan." && tensor_storage_map.count(prefix + "vid_in.proj.weight") && tensor_storage_map.count(prefix + "blocks.0.attn.rope.rope.freqs") && tensor_storage_map.count(prefix + "positive_conditioning")) diff --git a/src/model_registry.cpp b/src/model_registry.cpp index 231b699c09..e8496c0a23 100644 --- a/src/model_registry.cpp +++ b/src/model_registry.cpp @@ -35,6 +35,7 @@ const std::vector& iris_definitions(); const std::vector& sd_definitions(); const std::vector& moss_image_definitions(); const std::vector& seedvr2_definitions(); +const std::vector& kandinsky_imagesr_definitions(); static bool valid_model_id(std::string_view id) { if (id.empty() || id == "auto" || id.front() < 'a' || id.front() > 'z') @@ -99,6 +100,7 @@ static const std::array& model_definition append(sd_definitions()); append(moss_image_definitions()); append(seedvr2_definitions()); + append(kandinsky_imagesr_definitions()); for (const auto* definition : result) { if (!definition) throw std::logic_error("missing model registration"); From 8c8732481f418c42a0b206e6df4d2aac967d01a5 Mon Sep 17 00:00:00 2001 From: Aleksei Pakhomov Date: Tue, 1 Dec 2026 16:35:53 +0300 Subject: [PATCH 5/6] docs: add Kandinsky ImageSR to the DGL built-in catalog --- docs/dgl-builtins.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md index 1cedb5b62b..47d4935578 100644 --- a/docs/dgl-builtins.md +++ b/docs/dgl-builtins.md @@ -213,3 +213,4 @@ Pass the ID as the component loader's `family` argument. The default is `"auto"` | `minimax_h3_image` | MiniMax-H3-Image | | `relayvsr` | RelayVSR | | `seedvr2` | SeedVR2 | +| `kandinsky_imagesr` | Kandinsky ImageSR 2.0 | From 221a1934d306826a356c3690cf1807eb33ca8f35 Mon Sep 17 00:00:00 2001 From: leejet Date: Tue, 1 Dec 2026 22:19:52 +0800 Subject: [PATCH 6/6] use cuda rng --- docs/dgl/kandinsky_imagesr/upscale.dgl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dgl/kandinsky_imagesr/upscale.dgl b/docs/dgl/kandinsky_imagesr/upscale.dgl index a1d67178c3..c2dda42d65 100644 --- a/docs/dgl/kandinsky_imagesr/upscale.dgl +++ b/docs/dgl/kandinsky_imagesr/upscale.dgl @@ -79,7 +79,7 @@ fn main() { initial = {pixels = tensor::zeros([width * factor, height * factor, 3, 1]), weights = tensor::zeros([width * factor, height * factor])} tiles = tensor::to_list(tensor::arange(0, cols * rows)) sum = fold(tiles, initial, process = upscale_tile, pixels = pixels, geometry = geometry, predict = predictor(dit, {}), - vae = vae, rng = make_rng("std_default", seed = 42), sigmas = tensor::vector([timestep, 0.0]), window = hann_window()) + vae = vae, rng = make_rng("cuda", seed = 42), sigmas = tensor::vector([timestep, 0.0]), window = hann_window()) cropped = tensor::crop(tensor::div(sum.pixels, sum.weights), axes = [0, 1], start = [0, 0], size = [shape[0] * factor, shape[1] * factor]) output = image::to_u8(cropped) image::save(output_path, output)