diff --git a/README.md b/README.md index f36a435e8d..40f09e4ca7 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ API and command-line option may change frequently.*** - [Textual inversion embeddings](./docs/embeddings.md) for SD 1.x/2.x/SDXL via `--embd-dir` and `` tags - Latent Consistency Models support (LCM/LCM-LoRA) - Faster and memory efficient latent decoding with [TAESD](./docs/models/taesd.md) - - Upscale images generated with [ESRGAN](./docs/models/esrgan.md) + - Upscale images with [ESRGAN or MoSR](./docs/models/esrgan.md) and [Kandinsky ImageSR 2.0](./docs/models/kandinsky_imagesr.md) - Supported backends - CPU (AVX, AVX2 and AVX512 support for x86 architectures) - CUDA diff --git a/docs/dgl-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 | 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 new file mode 100644 index 0000000000..c2dda42d65 --- /dev/null +++ b/docs/dgl/kandinsky_imagesr/upscale.dgl @@ -0,0 +1,87 @@ +# version: 0.0.0 +# docs/models/kandinsky_imagesr.md +var { + 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() { + 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("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) + return output +} diff --git a/docs/models/README.md b/docs/models/README.md index 06820fac5b..16ac26df95 100644 --- a/docs/models/README.md +++ b/docs/models/README.md @@ -111,6 +111,7 @@ model guide. ## Image and video super-resolution - [ESRGAN and MoSR](esrgan.md) +- [Kandinsky ImageSR 2.0](kandinsky_imagesr.md) - [RelayVSR](relay_vsr.md) - [SeedVR2](seedvr2.md) diff --git a/docs/models/kandinsky_imagesr.md b/docs/models/kandinsky_imagesr.md new file mode 100644 index 0000000000..d4f8bb9317 --- /dev/null +++ b/docs/models/kandinsky_imagesr.md @@ -0,0 +1,36 @@ +# Kandinsky ImageSR 2.0 + +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 | DGL parameter | Requirement | +| --- | --- | --- | --- | +| 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 | + +The files share a name. Keep them in separate `transformer/` and `vae/` directories. + +## Usage + +### DGL + +| Example | Description | +| --- | --- | +| [Upscale an image](../dgl/kandinsky_imagesr/upscale.dgl) | Set `upscale_4x = false` for 2× (default) or `true` for 4×. | + +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)** + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\kandinsky_imagesr\upscale.dgl +``` + +**Linux/macOS** + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/kandinsky_imagesr/upscale.dgl +``` + +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/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/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_loader.cpp b/src/model_loader.cpp index 65869cef83..8606fceeec 100644 --- a/src/model_loader.cpp +++ b/src/model_loader.cpp @@ -441,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");