From 93eb0358c7125c562b9aa20c3f79b7801470eab6 Mon Sep 17 00:00:00 2001 From: Aleksei Pakhomov Date: Sat, 28 Nov 2026 15:53:36 +0300 Subject: [PATCH 1/3] 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/3] 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/3] 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;