Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<embedding:...>` 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
Expand Down
17 changes: 17 additions & 0 deletions docs/dgl/kandinsky_imagesr/upscale.dgl
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# version: 0.0.0
# docs/models/kandinsky_imagesr.md — standalone image upscaling

var {
upscaler_path = "../models/Kandinsky-ImageSR-2.0"

input_path = "input.png"
output_path = "upscaled.png"
}

fn main() {
upscaler = load_upscaler(upscaler_path)
image = image::load(input_path)
output = upscale(upscaler, image, factor = 2)
image::save(output_path, output)
return output
}
7 changes: 4 additions & 3 deletions docs/guides/c_api.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,9 @@ are required and set to `NULL` on failure. All outputs use `sd_result_t`.

Image upscaling loads `model_path` with optional `n_threads`, `backend`,
`params_backend`, `conv_direct` and `tile_size` (default 128). Execution takes
an RGB `image`. Its scale is fixed by the loaded model and can be queried with
`sd_upscaler_get_scale()`; metadata records that actual scale. The former
image-upscale factor argument was unused and has been removed.
an RGB `image`. Query the model's default scale with `sd_upscaler_get_scale()`.
Kandinsky ImageSR supports a per-run integer `factor` of 2 or 4 (default 4).
ESRGAN and MoSR use the scale encoded in their weights.

```c
sd_upscaler_opt_t* load = sd_upscaler_opt_create();
Expand Down Expand Up @@ -424,6 +424,7 @@ For SDXL's bundled VAE (no `vae_path`), generation emits
| `fps` | `int` | video |
| `height` | `int` | image, video |
| `high_noise_diffusion_model_path` | `string` | context |
| `factor` | `int` | upscale. Selects 2× or 4× for Kandinsky ImageSR |
| `image` | `tensor` | upscale |
| `init_image` | `tensor` | image, video |
| `linear_scale` | `float` | context |
Expand Down
1 change: 1 addition & 0 deletions docs/models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
66 changes: 66 additions & 0 deletions docs/models/kandinsky_imagesr.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Kandinsky ImageSR 2.0

Kandinsky ImageSR performs 2× and 4× super-resolution on RGB images. Both scales use the same weights. The default is 4×.

## Model files

| Component | Weights and downloads | CLI option | Requirement |
| --- | --- | --- | --- |
| ImageSR transformer | [Transformer files](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0/tree/main/transformer) | `--upscale-model` | Keep the configuration, shard index and all shards under `transformer/`. |
| FLUX VAE | [VAE files](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0/tree/main/vae) | Same bundle directory | Keep the supplied VAE under `vae/`. |

From the repository root, download both components with the Hugging Face CLI.

```sh
hf download kandinskylab/Kandinsky-ImageSR-2.0 --include 'transformer/*' 'vae/*' --local-dir models/Kandinsky-ImageSR-2.0
```

## Usage

Run the following examples from the build directory with an RGB image named `input.png`.

### DGL

| Task | Script |
| --- | --- |
| Upscale an image at 2× | [Kandinsky ImageSR upscaling](../dgl/kandinsky_imagesr/upscale.dgl) |

Set `factor = 4` in the script for 4× output.

**Windows PowerShell**

```powershell
.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\kandinsky_imagesr\upscale.dgl
```

**Linux / macOS**

```sh
./bin/sd-cli -M dgl --script ../docs/dgl/kandinsky_imagesr/upscale.dgl
```

### Legacy CLI

**Windows PowerShell**

```powershell
.\bin\Release\sd-cli.exe -M upscale --upscale-model ..\models\Kandinsky-ImageSR-2.0 `
-i input.png --upscale-factor 2 -o output.png
```

**Linux / macOS**

```sh
./bin/sd-cli -M upscale --upscale-model ../models/Kandinsky-ImageSR-2.0 \
-i input.png --upscale-factor 2 -o output.png
```

### API

For the [C API](../guides/c_api.md), pass the bundle directory as `model_path` and set the integer `factor` on the per-run options before calling `sd_upscale`.

For [server hires upscaling](../../examples/server/api.md), place the bundle directly under `--hires-upscalers-dir` and use its directory name in `hires.upscaler`. The hires pass selects 2× when it covers both target dimensions and 4× for larger targets.

## Notes and limitations

ImageSR processes overlapping tiles with a fixed output tile size of 1024×1024. Standalone output dimensions are exactly the input dimensions multiplied by the selected scale, including for small and non-square inputs.
6 changes: 4 additions & 2 deletions examples/cli/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -827,7 +827,9 @@ int main(int argc, const char* argv[]) {
ctx_params.linear_type));

if (upscaler_ctx == nullptr) {
LOG_ERROR("sd_upscaler_create failed");
LOG_ERROR("sd_upscaler_create failed: %s", sd_get_last_error());
if (cli_params.mode == UPSCALE)
return 1;
} else {
for (int i = 0; i < num_results; i++) {
if (results[i].data == nullptr) {
Expand All @@ -836,7 +838,7 @@ int main(int argc, const char* argv[]) {
SDImageOwner current_image(results[i]);
results[i] = {0, 0, 0, nullptr};
sd_result_t* upscaled = nullptr;
if (!upscale_sd_image(upscaler_ctx.get(), current_image.get(), &upscaled, gen_params.upscale_repeats) || !upscaled) {
if (!upscale_sd_image(upscaler_ctx.get(), current_image.get(), &upscaled, gen_params.upscale_repeats, gen_params.upscale_factor.value_or(0)) || !upscaled) {
LOG_ERROR("upscale failed: %s", sd_get_last_error());
sd_result_free(upscaled);
return 1;
Expand Down
22 changes: 17 additions & 5 deletions examples/common/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ ArgOptions SDContextParams::get_options() {
&model_args},
{"",
"--upscale-model",
"path to esrgan model.",
"path to ESRGAN or MoSR weights, or a Kandinsky ImageSR bundle directory",
0,
&esrgan_path},
{"",
Expand Down Expand Up @@ -1174,6 +1174,10 @@ ArgOptions SDGenerationParams::get_options() {
"--fps",
"fps (default: 24)",
&fps},
{"",
"--upscale-factor",
"Kandinsky ImageSR scale factor: 2 or 4 (default: 4)",
&upscale_factor},
{"",
"--upscale-repeats",
"Run the ESRGAN upscaler this many times (default: 1)",
Expand Down Expand Up @@ -1926,16 +1930,19 @@ static bool resolve_model_file_from_dir(const std::string& model_name,
return false;
};

if (model_name.empty() ||
model_name.find('/') != std::string::npos ||
model_name.find('\\') != std::string::npos ||
fs::u8path(model_name).has_root_path() ||
const auto name = fs::u8path(model_name);
if (name.empty() || name == "." || name == ".." || name.has_parent_path() || name.has_root_path() ||
ends_with_valid_ext()) {
LOG_ERROR("%s must be a model name without path or extension: %s", label, model_name.c_str());
return false;
}

fs::path model_dir_path = fs::u8path(model_dir);
const auto bundle = model_dir_path / name;
if (fs::is_regular_file(bundle / "transformer" / "config.json")) {
resolved_path = bundle.lexically_normal().u8string();
return true;
}
for (const auto& ext : valid_ext) {
fs::path try_path = model_dir_path / fs::u8path(model_name + ext);
if (fs::exists(try_path) && fs::is_regular_file(try_path)) {
Expand Down Expand Up @@ -2041,6 +2048,7 @@ bool SDGenerationParams::from_json_str(
load_if_exists("qwen_image_layers", qwen_image_layers);
load_if_exists("video_frames", video_frames);
load_if_exists("fps", fps);
load_if_exists("upscale_factor", upscale_factor);
load_if_exists("upscale_repeats", upscale_repeats);
load_if_exists("seed", seed);

Expand Down Expand Up @@ -2405,6 +2413,10 @@ bool SDGenerationParams::validate(SDMode mode) {
return false;
}

if (upscale_factor && upscale_factor != 2 && upscale_factor != 4) {
LOG_ERROR("upscale factor must be 2 or 4");
return false;
}
if (upscale_repeats < 1) {
return false;
}
Expand Down
1 change: 1 addition & 0 deletions examples/common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ struct SDGenerationParams {
SDTilingParams vae_tiling_params;
std::string extra_tiling_args;

std::optional<int> upscale_factor;
int upscale_repeats = 1;
std::optional<int> upscale_tile_size;

Expand Down
3 changes: 2 additions & 1 deletion examples/common/resource_owners.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -339,12 +339,13 @@ static inline sd_upscaler_t* create_sd_upscaler(const char* path, std::optional<
return result;
}

static inline bool upscale_sd_image(sd_upscaler_t* ctx, SDImage image, sd_result_t** result, int repeats = 1) {
static inline bool upscale_sd_image(sd_upscaler_t* ctx, SDImage image, sd_result_t** result, int repeats = 1, int factor = 0) {
if (result)
*result = nullptr;
SDOptPtr opt(sd_upscale_opt_create());
auto tensor = image_tensor(image);
return opt && tensor && sd_opt_set_tensor(opt.get(), "image", tensor.get()) == SD_STATUS_OK &&
(!factor || sd_opt_set_int(opt.get(), "factor", factor) == SD_STATUS_OK) &&
sd_opt_set_int(opt.get(), "repeats", repeats) == SD_STATUS_OK && sd_upscale(ctx, opt.get(), result) == SD_STATUS_OK;
}

Expand Down
6 changes: 3 additions & 3 deletions examples/server/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -659,7 +659,7 @@ Response fields:
| `[].model_url` | `string \| null` | Currently always null |
| `[].scale` | `integer` | Currently `4` |

Built-in entries include `None`, `Lanczos`, and `Nearest`. Model-backed entries are scanned from the top level of `--hires-upscalers-dir`; subdirectories are not scanned.
Built-in entries include `None`, `Lanczos`, and `Nearest`. Model-backed entries include weight files and Kandinsky ImageSR bundle directories directly under `--hires-upscalers-dir`. Use the bundle directory name to select Kandinsky.

`GET /sdapi/v1/latent-upscale-modes`

Expand Down Expand Up @@ -904,7 +904,7 @@ Shared nested fields:
| `upscalers[].name` | `string` | Built-in name or model stem; use this value in `hires.upscaler` |
| `upscalers[].model` | `boolean` | True for a model-backed upscaler, false for a built-in scaling filter |

Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, and `Latent (bicubic antialiased)`. Model-backed entries are scanned from the top level of `--hires-upscalers-dir`; subdirectories are not scanned.
Built-in entries include `None`, `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, and `Latent (bicubic antialiased)`. Model-backed entries include weight files and Kandinsky ImageSR bundle directories directly under `--hires-upscalers-dir`. Use the bundle directory name to select Kandinsky.

`limits`

Expand Down Expand Up @@ -1293,7 +1293,7 @@ Other native fields:
| `scm_mask` | `string` |
| `scm_policy_dynamic` | `boolean` |

For `hires.upscaler`, use `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, `Latent (bicubic antialiased)`, or an `upscalers[].name` value from `GET /sdcpp/v1/capabilities`. Model-backed upscalers are resolved as `--hires-upscalers-dir / (name + ext)` and must live directly in that directory. `hires.custom_sigmas`, when present, overrides the generated second-pass hires sigma schedule; otherwise the hires schedule is trimmed by `hires.denoising_strength`.
For `hires.upscaler`, use `Lanczos`, `Nearest`, `Latent`, `Latent (nearest)`, `Latent (nearest-exact)`, `Latent (antialiased)`, `Latent (bicubic)`, `Latent (bicubic antialiased)`, or an `upscalers[].name` value from `GET /sdcpp/v1/capabilities`. Use the stem of a weight file or the name of a Kandinsky ImageSR bundle directly under `--hires-upscalers-dir`. `hires.custom_sigmas`, when present, overrides the generated second-pass hires sigma schedule; otherwise the hires schedule is trimmed by `hires.denoising_strength`.

HTTP-only output fields:

Expand Down
15 changes: 15 additions & 0 deletions examples/server/runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,21 @@ void refresh_upscaler_cache(ServerRuntime& rt) {
auto end = fs::directory_iterator();
while (!ec && it != end) {
std::error_code entry_ec;
const auto& path = it->path();
if (it->is_directory(entry_ec)) {
if (fs::is_regular_file(path / "transformer" / "config.json", entry_ec)) {
UpscalerEntry entry{};
entry.path = entry.name = path.filename().u8string();
entry.fullpath = fs::absolute(path).lexically_normal().u8string();
entry.scale = sd_upscaler_probe_scale(entry.fullpath.c_str());
if (entry.scale > 0) {
entry.model_name = "Kandinsky ImageSR 2.0";
new_cache.push_back(std::move(entry));
}
}
it.increment(ec);
continue;
}
bool is_reg = it->is_regular_file(entry_ec);
if (entry_ec || !is_reg) {
it.increment(ec);
Expand Down
5 changes: 5 additions & 0 deletions src/api/generation_hires.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ namespace sd::api {
if (hires.custom_sigmas_count)
request.values["hires_custom_sigmas"] = std::vector<float>(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<int>() <= 2 * request.values.at("width").get<int>() &&
request.values.at("hires_target_height").get<int>() <= 2 * request.values.at("height").get<int>();
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) {
Expand Down
1 change: 1 addition & 0 deletions src/api/options.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ static void add_postprocess_specs(std::vector<ParamSpec>& 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);
Expand Down
2 changes: 1 addition & 1 deletion src/api/templates/image_helpers.dgl
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn upscale_layer(index, args) {
latent = args.latent[:, :, index]
image = vae_decode(args.vae, dit_to_vae_latents(args.vae, latent), dtype = "f32"{{vae_run_options}})
{% if flags.hires_model %}
upscaled = upscale(args.upscaler, image::to_u8(image))
upscaled = upscale(args.upscaler, image::to_u8(image), factor = {{hires_upscale_factor}})
pixels = image::to_f32(tensor::interpolate(upscaled, size = args.size, axes = [1, 2], mode = args.mode))
{% else %}
pixels = tensor::interpolate(image, size = args.size, mode = args.mode)
Expand Down
2 changes: 1 addition & 1 deletion src/api/templates/image_hires.dgl
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
{% endif %}
{% if flags.hires_model %}
hires_upscaler = load_upscaler(hires_model_path{{hires_model_options}})
hires_upscaled = upscale(hires_upscaler, image::to_u8(hires_pixels))
hires_upscaled = upscale(hires_upscaler, image::to_u8(hires_pixels), factor = {{hires_upscale_factor}})
hires_resized = image::to_f32(tensor::interpolate(hires_upscaled, size = [hires_target_width, hires_target_height], axes = [1, 2], mode = hires_mode), channels = {{channels}})
{% else %}
hires_resized = tensor::interpolate(hires_pixels, size = [hires_target_width, hires_target_height], mode = hires_mode)
Expand Down
2 changes: 1 addition & 1 deletion src/api/templates/upscale.dgl
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ var {
}

fn enlarge(image, index, model) {
return upscale(model, image)
return upscale(model, image{{factor_option}})
}

fn main(input_image) {
Expand Down
12 changes: 8 additions & 4 deletions src/api/upscaler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ struct sd_upscaler {
};

namespace sd::api {
static std::string upscale_source(const OptConfig& config, int repeats) {
static std::string upscale_source(const OptConfig& config, int repeats, int factor = 0) {
const auto& settings = config.context;
std::string options;
for (const auto& [name, spec] : std::map<std::string, const char*>{{"backend", settings.backend}, {"params_backend", settings.params_backend}}) {
Expand All @@ -34,6 +34,7 @@ namespace sd::api {
return render_template("upscale", {{"model_path", nlohmann::json(settings.model_path).dump()},
{"tile_size", std::to_string(config.post.tile_size)},
{"repeats", std::to_string(repeats)},
{"factor_option", factor ? ", factor = " + std::to_string(factor) : ""},
{"loader_options", options}});
}
}
Expand Down Expand Up @@ -100,7 +101,9 @@ sd_status_t sd_upscale(sd_upscaler_t* upscaler, const sd_upscale_opt_t* options,
if (status != SD_STATUS_OK)
return status;
int64_t width = config.post.image.width, height = config.post.image.height;
const auto scale = upscaler->model->get_scale();
const auto scale = upscaler->model->get_scale(config.post.factor);
if (!scale)
return sd::api::error(SD_STATUS_INVALID_ARGUMENT, "factor", "Kandinsky ImageSR supports factors 2 and 4");
for (int i = 0; i < config.post.repeats; ++i) {
width *= scale;
height *= scale;
Expand All @@ -109,9 +112,10 @@ sd_status_t sd_upscale(sd_upscaler_t* upscaler, const sd_upscale_opt_t* options,
}
const auto* input = sd::api::bound_tensor(snapshot.get(), "image");
sd::api::GenerationProgram program;
program.source = config.post.repeats == 1 ? upscaler->source : sd::api::upscale_source(upscaler->context.model.config, config.post.repeats);
const bool use_cached = config.post.repeats == 1 && config.post.factor == 0;
program.source = use_cached ? upscaler->source : sd::api::upscale_source(upscaler->context.model.config, config.post.repeats, config.post.factor);
program.inputs.emplace("input_image", sd::dgl::Value::object(std::shared_ptr<sd_tensor_t>(sd_tensor_retain(input), sd_tensor_free)));
auto value = sd::api::execute_program(upscaler->context, program, config.post.repeats == 1 ? &upscaler->program : nullptr);
auto value = sd::api::execute_program(upscaler->context, program, use_cached ? &upscaler->program : nullptr);
auto result = std::make_unique<sd_result_t>();
sd::api::append_program_image(*result, value, program.source);
*out = result.release();
Expand Down
1 change: 1 addition & 0 deletions src/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ namespace sd {
bool conv_direct = false;
int tile_size = 128;
int repeats = 1;
int factor = 0;
};

struct OptConfig {
Expand Down
Loading
Loading