From e43ea7a7b0b01f87c5d3021bd5ac169e0db1d307 Mon Sep 17 00:00:00 2001 From: Irina Tolstykh Date: Sat, 5 Dec 2026 00:14:46 +0300 Subject: [PATCH] Add Kandinsky ImageSR 2.0 --- docs/source/en/_toctree.yml | 4 + .../models/kandinsky_imagesr_transformer.md | 36 ++ .../en/api/pipelines/kandinsky_imagesr.md | 107 +++++ src/diffusers/__init__.py | 6 + src/diffusers/loaders/single_file_model.py | 4 + src/diffusers/models/__init__.py | 2 + src/diffusers/models/transformers/__init__.py | 1 + .../transformer_kandinsky_imagesr.py | 406 ++++++++++++++++++ src/diffusers/modular_pipelines/__init__.py | 2 + .../kandinsky_imagesr/__init__.py | 47 ++ .../kandinsky_imagesr/decoders.py | 171 ++++++++ .../kandinsky_imagesr/denoise.py | 123 ++++++ .../kandinsky_imagesr/encoders.py | 151 +++++++ .../modular_blocks_kandinsky_imagesr.py | 84 ++++ .../kandinsky_imagesr/modular_pipeline.py | 80 ++++ .../modular_pipelines/modular_pipeline.py | 1 + src/diffusers/utils/dummy_pt_objects.py | 15 + .../dummy_torch_and_transformers_objects.py | 30 ++ ...st_models_transformer_kandinsky_imagesr.py | 123 ++++++ .../kandinsky_imagesr/__init__.py | 0 ...test_modular_pipeline_kandinsky_imagesr.py | 163 +++++++ 21 files changed, 1556 insertions(+) create mode 100644 docs/source/en/api/models/kandinsky_imagesr_transformer.md create mode 100644 docs/source/en/api/pipelines/kandinsky_imagesr.md create mode 100644 src/diffusers/models/transformers/transformer_kandinsky_imagesr.py create mode 100644 src/diffusers/modular_pipelines/kandinsky_imagesr/__init__.py create mode 100644 src/diffusers/modular_pipelines/kandinsky_imagesr/decoders.py create mode 100644 src/diffusers/modular_pipelines/kandinsky_imagesr/denoise.py create mode 100644 src/diffusers/modular_pipelines/kandinsky_imagesr/encoders.py create mode 100644 src/diffusers/modular_pipelines/kandinsky_imagesr/modular_blocks_kandinsky_imagesr.py create mode 100644 src/diffusers/modular_pipelines/kandinsky_imagesr/modular_pipeline.py create mode 100644 tests/models/transformers/test_models_transformer_kandinsky_imagesr.py create mode 100644 tests/modular_pipelines/kandinsky_imagesr/__init__.py create mode 100644 tests/modular_pipelines/kandinsky_imagesr/test_modular_pipeline_kandinsky_imagesr.py diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 1c3a1572e3b0..31d6ce90aa15 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -387,6 +387,8 @@ title: JoyImageEditTransformer3DModel - local: api/models/kandinsky6_transformer title: Kandinsky 6 Transformers + - local: api/models/kandinsky_imagesr_transformer + title: KandinskyImageSRTransformer3DModel - local: api/models/kandinsky_s2v_transformer title: KandinskyS2VTransformer3DModel - local: api/models/krea2_transformer2d @@ -643,6 +645,8 @@ title: Kandinsky 3 - local: api/pipelines/kandinsky5_image title: Kandinsky 5.0 Image + - local: api/pipelines/kandinsky_imagesr + title: Kandinsky ImageSR 2.0 - local: api/pipelines/kolors title: Kolors - local: api/pipelines/krea2 diff --git a/docs/source/en/api/models/kandinsky_imagesr_transformer.md b/docs/source/en/api/models/kandinsky_imagesr_transformer.md new file mode 100644 index 000000000000..0d5e11d7b41d --- /dev/null +++ b/docs/source/en/api/models/kandinsky_imagesr_transformer.md @@ -0,0 +1,36 @@ + + +# KandinskyImageSRTransformer3DModel + +The text-free Kandinsky 5 transformer used by [`KandinskyImageSRModularPipeline`] to correct one image tile latent in a +single flow step. The time embedding, the block modulation and the zero-text cross-attention are stored as tables +for the supported timesteps. + +```python +import torch +from diffusers import KandinskyImageSRTransformer3DModel + +transformer = KandinskyImageSRTransformer3DModel.from_pretrained( + "kandinskylab/Kandinsky-ImageSR-2.0-Diffusers", subfolder="transformer", dtype=torch.bfloat16 +) +``` + +## KandinskyImageSRTransformer3DModel + +[[autodoc]] KandinskyImageSRTransformer3DModel + - all + - forward + +## KandinskyImageSRTransformer3DModelOutput + +[[autodoc]] models.transformers.transformer_kandinsky_imagesr.KandinskyImageSRTransformer3DModelOutput diff --git a/docs/source/en/api/pipelines/kandinsky_imagesr.md b/docs/source/en/api/pipelines/kandinsky_imagesr.md new file mode 100644 index 000000000000..30b238a93779 --- /dev/null +++ b/docs/source/en/api/pipelines/kandinsky_imagesr.md @@ -0,0 +1,107 @@ + + +# Kandinsky ImageSR 2.0 + +Kandinsky ImageSR 2.0 is an image super-resolution model from [Kandinsky Lab](https://huggingface.co/kandinskylab). +A single text-free Kandinsky 5 transformer enhances an image at its original resolution (×1) or upscales it ×2 or +×4. The image is processed in overlapping 1024-pixel output tiles: every tile is encoded with the FLUX VAE, corrected +by one flow step, decoded, and blended back with boundary-aware Hann windows. + +Kandinsky ImageSR 2.0 is integrated as a [modular pipeline](../../modular_diffusers/overview) only; there is no +standard `DiffusionPipeline` class for it. [`KandinskyImageSRBlocks`] runs three blocks in sequence: `vae_encoder` +tiles and encodes the images, `denoise` corrects every tile latent with a single flow step, and `decode` decodes and +blends the tiles. + +## Available models + +| Model | Notes | +|---|---| +| [`kandinskylab/Kandinsky-ImageSR-2.0-Diffusers`](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0-Diffusers) | BF16 transformer and VAE | +| [`kandinskylab/Kandinsky-ImageSR-2.0-GGUF`](https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0-GGUF) | GGUF Q8_0 transformer, see [GGUF checkpoint](#gguf-checkpoint) | + +## Super-resolution + +```python +import torch +from diffusers import ModularPipeline +from diffusers.utils import load_image + +pipe = ModularPipeline.from_pretrained("kandinskylab/Kandinsky-ImageSR-2.0-Diffusers") +pipe.load_components(dtype=torch.bfloat16) +pipe.to("cuda") + +image = load_image("input.png") +pipe(image=image, upscale_factor=4, creativity=4, output="images")[0].save("output.png") +``` + +`creativity` selects one of nine calibrated flow timesteps for the chosen scale. Lower levels preserve fine text and +details; higher levels synthesize more texture. `one_step_t` sets the timestep directly, in place of the +`creativity` preset, and must be one of `pipe.transformer.config.baked_timesteps`. + +| Scale | Creativity range (`t`) | Default (level 4) | +|---:|---:|---:| +| ×1 | 0.005–0.118 | 0.05 | +| ×2 | 0.07–0.30 | 0.15 | +| ×4 | 0.17–0.38 | 0.244 | + +Inputs are treated as sRGB; convert images with an embedded color profile beforehand. + +The blocks also run on their own. Pass the same `upscale_factor` and `overlap` to `vae_encoder`, `denoise` and +`decode`: the decoder blends the tiles with the layout they were encoded with. + +## Speed + +Compile the repeated transformer blocks and the VAE decoder for repeated inference. Every tile has the same shape, so +the compiled graphs are reused across tiles and images. + +```python +pipe.transformer.compile_repeated_blocks(fullgraph=True) +pipe.vae.decoder.compile() +``` + +Attention runs on PyTorch SDPA by default. Switch to FlashAttention-2, or FlashAttention-3 on a supported Hopper GPU, +with [`~ModelMixin.set_attention_backend`]: + +```python +pipe.transformer.set_attention_backend("flash") # or "_flash_3_hub" +``` + +## GGUF checkpoint + +The GGUF Q8_0 transformer loads with [`~loaders.FromOriginalModelMixin.from_single_file`]. Load the VAE and the +scheduler from the pipeline repository and pass it the transformer. + +```python +import torch +from diffusers import GGUFQuantizationConfig, KandinskyImageSRTransformer3DModel, ModularPipeline + +transformer = KandinskyImageSRTransformer3DModel.from_single_file( + "https://huggingface.co/kandinskylab/Kandinsky-ImageSR-2.0-GGUF/blob/main/Kandinsky-ImageSR-2.0-x1-Q8_0.gguf", + config="kandinskylab/Kandinsky-ImageSR-2.0-Diffusers", + subfolder="transformer", + quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16), + dtype=torch.bfloat16, +) +pipe = ModularPipeline.from_pretrained("kandinskylab/Kandinsky-ImageSR-2.0-Diffusers") +pipe.load_components(names=["vae", "scheduler"], dtype=torch.bfloat16) +pipe.update_components(transformer=transformer) +pipe.to("cuda") +``` + +## KandinskyImageSRModularPipeline + +[[autodoc]] KandinskyImageSRModularPipeline + +## KandinskyImageSRBlocks + +[[autodoc]] KandinskyImageSRBlocks diff --git a/src/diffusers/__init__.py b/src/diffusers/__init__.py index 4690e8bd197f..69597bb2b521 100644 --- a/src/diffusers/__init__.py +++ b/src/diffusers/__init__.py @@ -337,6 +337,7 @@ "Kandinsky6SRTransformer3DModel", "Kandinsky6SRVAE", "Kandinsky6Transformer3DModel", + "KandinskyImageSRTransformer3DModel", "KandinskyS2VTransformer3DModel", "Krea2Transformer2DModel", "LatteTransformer3DModel", @@ -602,6 +603,8 @@ "HunyuanVideo15ModularPipeline", "Ideogram4AutoBlocks", "Ideogram4ModularPipeline", + "KandinskyImageSRBlocks", + "KandinskyImageSRModularPipeline", "KandinskyS2VAutoBlocks", "KandinskyS2VDistilledAutoBlocks", "KandinskyS2VDistilledModularPipeline", @@ -1268,6 +1271,7 @@ Kandinsky6SRTransformer3DModel, Kandinsky6SRVAE, Kandinsky6Transformer3DModel, + KandinskyImageSRTransformer3DModel, KandinskyS2VTransformer3DModel, Krea2Transformer2DModel, LatteTransformer3DModel, @@ -1511,6 +1515,8 @@ HunyuanVideo15ModularPipeline, Ideogram4AutoBlocks, Ideogram4ModularPipeline, + KandinskyImageSRBlocks, + KandinskyImageSRModularPipeline, KandinskyS2VAutoBlocks, KandinskyS2VDistilledAutoBlocks, KandinskyS2VDistilledModularPipeline, diff --git a/src/diffusers/loaders/single_file_model.py b/src/diffusers/loaders/single_file_model.py index 2ffaf3cb37c0..db165722d0fe 100644 --- a/src/diffusers/loaders/single_file_model.py +++ b/src/diffusers/loaders/single_file_model.py @@ -240,6 +240,10 @@ "checkpoint_mapping_fn": convert_minimax_h3_transformer_checkpoint_to_diffusers, "default_subfolder": "transformer", }, + "KandinskyImageSRTransformer3DModel": { + "checkpoint_mapping_fn": lambda checkpoint, **kwargs: checkpoint, + "default_subfolder": "transformer", + }, } diff --git a/src/diffusers/models/__init__.py b/src/diffusers/models/__init__.py index 3d5567408738..309c8b007a1f 100755 --- a/src/diffusers/models/__init__.py +++ b/src/diffusers/models/__init__.py @@ -160,6 +160,7 @@ _import_structure["transformers.transformer_kandinsky"] = ["Kandinsky5Transformer3DModel"] _import_structure["transformers.transformer_kandinsky6"] = ["Kandinsky6Transformer3DModel"] _import_structure["transformers.transformer_kandinsky6_sr"] = ["Kandinsky6SRTransformer3DModel"] + _import_structure["transformers.transformer_kandinsky_imagesr"] = ["KandinskyImageSRTransformer3DModel"] _import_structure["transformers.transformer_kandinsky_s2v"] = ["KandinskyS2VTransformer3DModel"] _import_structure["transformers.transformer_krea2"] = ["Krea2Transformer2DModel"] _import_structure["transformers.transformer_longcat_audio_dit"] = ["LongCatAudioDiTTransformer"] @@ -338,6 +339,7 @@ Kandinsky5Transformer3DModel, Kandinsky6SRTransformer3DModel, Kandinsky6Transformer3DModel, + KandinskyImageSRTransformer3DModel, KandinskyS2VTransformer3DModel, Krea2Transformer2DModel, LatteTransformer3DModel, diff --git a/src/diffusers/models/transformers/__init__.py b/src/diffusers/models/transformers/__init__.py index 2a49be82fab6..de58b491c03a 100755 --- a/src/diffusers/models/transformers/__init__.py +++ b/src/diffusers/models/transformers/__init__.py @@ -49,6 +49,7 @@ from .transformer_kandinsky import Kandinsky5Transformer3DModel from .transformer_kandinsky6 import Kandinsky6Transformer3DModel from .transformer_kandinsky6_sr import Kandinsky6SRTransformer3DModel + from .transformer_kandinsky_imagesr import KandinskyImageSRTransformer3DModel from .transformer_kandinsky_s2v import KandinskyS2VTransformer3DModel from .transformer_krea2 import Krea2Transformer2DModel from .transformer_longcat_audio_dit import LongCatAudioDiTTransformer diff --git a/src/diffusers/models/transformers/transformer_kandinsky_imagesr.py b/src/diffusers/models/transformers/transformer_kandinsky_imagesr.py new file mode 100644 index 000000000000..257e769b8e9b --- /dev/null +++ b/src/diffusers/models/transformers/transformer_kandinsky_imagesr.py @@ -0,0 +1,406 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from dataclasses import dataclass + +import torch +import torch.nn as nn +from torch import Tensor + +from ...configuration_utils import ConfigMixin, register_to_config +from ...loaders import FromOriginalModelMixin +from ...utils import BaseOutput +from ..attention import AttentionMixin, AttentionModuleMixin +from ..attention_dispatch import dispatch_attention_fn +from ..modeling_utils import ModelMixin + + +@dataclass +class KandinskyImageSRTransformer3DModelOutput(BaseOutput): + r""" + The output of [`KandinskyImageSRTransformer3DModel`]. + + Args: + sample (`torch.Tensor` of shape `(batch_size, num_frames, height, width, out_visual_dim)`): + The predicted flow velocity of the latent. + """ + + sample: torch.Tensor + + +# Tokens per axis the RoPE tables cover, as in Kandinsky 5. +ROPE_MAX_POSITIONS = 128 + + +# Copied from diffusers.models.transformers.transformer_kandinsky.get_freqs +def get_freqs(dim, max_period=10000.0): + freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=dim, dtype=torch.float32) / dim) + return freqs + + +# Copied from diffusers.models.transformers.transformer_kandinsky6.apply_rotary +def apply_rotary(x: Tensor, rope: Tensor) -> Tensor: + """RoPE apply in fp32 (rope tables are fp32), cast back to ``x.dtype``.""" + x_ = x.reshape(*x.shape[:-1], -1, 1, 2).float() + return (rope.float() * x_).sum(dim=-1).reshape(*x.shape).to(dtype=x.dtype) + + +# Copied from diffusers.models.transformers.transformer_kandinsky.Kandinsky5VisualEmbeddings with Kandinsky5->KandinskyImageSR +class KandinskyImageSRVisualEmbeddings(nn.Module): + def __init__(self, visual_dim, model_dim, patch_size): + super().__init__() + self.patch_size = patch_size + self.in_layer = nn.Linear(math.prod(patch_size) * visual_dim, model_dim) + + def forward(self, x) -> torch.Tensor: + batch_size, duration, height, width, dim = x.shape + x = ( + x.view( + batch_size, + duration // self.patch_size[0], + self.patch_size[0], + height // self.patch_size[1], + self.patch_size[1], + width // self.patch_size[2], + self.patch_size[2], + dim, + ) + .permute(0, 1, 3, 5, 2, 4, 6, 7) + .flatten(4, 7) + ) + return self.in_layer(x) + + +# Adapted from diffusers.models.transformers.transformer_kandinsky.Kandinsky5RoPE3D without the position scale factors, +# which are always 1 for ImageSR. +class KandinskyImageSRRoPE3D(nn.Module): + def __init__(self, axes_dims: tuple[int, int, int]): + super().__init__() + for i, axes_dim in enumerate(axes_dims): + freq = get_freqs(axes_dim // 2) + pos = torch.arange(ROPE_MAX_POSITIONS, dtype=freq.dtype) + self.register_buffer(f"args_{i}", torch.outer(pos, freq), persistent=False) + + def forward(self, shape: torch.Size, pos: list[Tensor]) -> Tensor: + batch_size, duration, height, width = shape + args_t = self.args_0[pos[0]] + args_h = self.args_1[pos[1]] + args_w = self.args_2[pos[2]] + + args = torch.cat( + [ + args_t.view(1, duration, 1, 1, -1).repeat(batch_size, 1, height, width, 1), + args_h.view(1, 1, height, 1, -1).repeat(batch_size, duration, 1, width, 1), + args_w.view(1, 1, 1, width, -1).repeat(batch_size, duration, height, 1, 1), + ], + dim=-1, + ) + cosine = torch.cos(args) + sine = torch.sin(args) + rope = torch.stack([cosine, -sine, sine, cosine], dim=-1) + rope = rope.view(*rope.shape[:-1], 2, 2) + return rope.unsqueeze(-4) + + +# Copied from diffusers.models.transformers.transformer_kandinsky.Kandinsky5Modulation with Kandinsky5->KandinskyImageSR +class KandinskyImageSRModulation(nn.Module): + def __init__(self, time_dim, model_dim, num_params): + super().__init__() + self.activation = nn.SiLU() + self.out_layer = nn.Linear(time_dim, num_params * model_dim) + self.out_layer.weight.data.zero_() + self.out_layer.bias.data.zero_() + + def forward(self, x) -> torch.Tensor: + return self.out_layer(self.activation(x)) + + +# Adapted from diffusers.models.transformers.transformer_kandinsky.Kandinsky5AttnProcessor: self-attention only, +# without the text cross-attention and NABLA sparse-attention paths that the ImageSR checkpoints never take. +class KandinskyImageSRAttnProcessor: + """Full self-attention over the visual tokens with Kandinsky 5 query/key RMSNorm and 3D RoPE.""" + + _attention_backend = None + _parallel_config = None + + def __call__(self, attn: "KandinskyImageSRAttention", hidden_states: Tensor, rotary_emb: Tensor) -> Tensor: + query = attn.to_query(hidden_states).unflatten(-1, (attn.num_heads, -1)) + key = attn.to_key(hidden_states).unflatten(-1, (attn.num_heads, -1)) + value = attn.to_value(hidden_states).unflatten(-1, (attn.num_heads, -1)) + query = attn.query_norm(query.float()).type_as(query) + key = attn.key_norm(key.float()).type_as(key) + query = apply_rotary(query, rotary_emb) + key = apply_rotary(key, rotary_emb) + + hidden_states = dispatch_attention_fn( + query, + key, + value, + backend=self._attention_backend, + parallel_config=self._parallel_config, + ) + return attn.out_layer(hidden_states.flatten(-2, -1)) + + +# Adapted from diffusers.models.transformers.transformer_kandinsky.Kandinsky5Attention without the unused +# `encoder_hidden_states` and `sparse_params` inputs. +class KandinskyImageSRAttention(nn.Module, AttentionModuleMixin): + _default_processor_cls = KandinskyImageSRAttnProcessor + _available_processors = [KandinskyImageSRAttnProcessor] + # The projections keep the Kandinsky 5 checkpoint names (`to_query`, ...), which QKV fusion does not handle. + _supports_qkv_fusion = False + + def __init__(self, num_channels: int, head_dim: int): + super().__init__() + if num_channels % head_dim: + raise ValueError(f"`num_channels` ({num_channels}) must be divisible by `head_dim` ({head_dim}).") + self.num_heads = num_channels // head_dim + self.to_query = nn.Linear(num_channels, num_channels, bias=True) + self.to_key = nn.Linear(num_channels, num_channels, bias=True) + self.to_value = nn.Linear(num_channels, num_channels, bias=True) + self.query_norm = nn.RMSNorm(head_dim) + self.key_norm = nn.RMSNorm(head_dim) + self.out_layer = nn.Linear(num_channels, num_channels, bias=True) + self.set_processor(self._default_processor_cls()) + + def forward(self, hidden_states: Tensor, rotary_emb: Tensor) -> Tensor: + return self.processor(self, hidden_states, rotary_emb) + + +# Copied from diffusers.models.transformers.transformer_kandinsky.Kandinsky5FeedForward with Kandinsky5->KandinskyImageSR +class KandinskyImageSRFeedForward(nn.Module): + def __init__(self, dim, ff_dim): + super().__init__() + self.in_layer = nn.Linear(dim, ff_dim, bias=False) + self.activation = nn.GELU() + self.out_layer = nn.Linear(ff_dim, dim, bias=False) + + def forward(self, x) -> torch.Tensor: + return self.out_layer(self.activation(self.in_layer(x))) + + +# Adapted from diffusers.models.transformers.transformer_kandinsky.Kandinsky5OutLayer without the unused `text_embed` +# input. +class KandinskyImageSROutLayer(nn.Module): + def __init__(self, model_dim: int, time_dim: int, visual_dim: int, patch_size: tuple[int, int, int]): + super().__init__() + self.patch_size = patch_size + self.modulation = KandinskyImageSRModulation(time_dim, model_dim, 2) + self.norm = nn.LayerNorm(model_dim, elementwise_affine=False) + self.out_layer = nn.Linear(model_dim, math.prod(patch_size) * visual_dim, bias=True) + + def forward(self, visual_embed: Tensor, time_embed: Tensor) -> Tensor: + shift, scale = torch.chunk(self.modulation(time_embed).unsqueeze(dim=1), 2, dim=-1) + + visual_embed = ( + self.norm(visual_embed.float()) * (scale.float()[:, None, None] + 1.0) + shift.float()[:, None, None] + ).type_as(visual_embed) + + hidden_states = self.out_layer(visual_embed) + + batch_size, duration, height, width, _ = hidden_states.shape + return ( + hidden_states.view( + batch_size, + duration, + height, + width, + -1, + self.patch_size[0], + self.patch_size[1], + self.patch_size[2], + ) + .permute(0, 1, 5, 2, 6, 3, 7, 4) + .flatten(1, 2) + .flatten(2, 3) + .flatten(3, 4) + ) + + +class KandinskyImageSRTransformerBlock(nn.Module): + """ + Kandinsky 5 visual block whose text cross-attention and modulation are replaced by tables precomputed for the zero + text conditioning at every supported timestep. + """ + + def __init__(self, model_dim: int, ff_dim: int, head_dim: int, num_timesteps: int): + super().__init__() + self.self_attention_norm = nn.LayerNorm(model_dim, elementwise_affine=False) + self.self_attention = KandinskyImageSRAttention(model_dim, head_dim) + self.feed_forward_norm = nn.LayerNorm(model_dim, elementwise_affine=False) + self.feed_forward = KandinskyImageSRFeedForward(model_dim, ff_dim) + self.register_buffer("visual_modulation_table", torch.zeros(num_timesteps, 6 * model_dim)) + self.register_buffer("xattn_bias_table", torch.zeros(num_timesteps, model_dim)) + + def forward(self, visual_embed: Tensor, rope: Tensor, timestep_indices: Tensor) -> Tensor: + modulation = self.visual_modulation_table.index_select(0, timestep_indices).unsqueeze(1) + self_attn_params, ff_params = modulation.chunk(2, dim=-1) + + shift, scale, gate = torch.chunk(self_attn_params, 3, dim=-1) + visual_out = (self.self_attention_norm(visual_embed.float()) * (scale.float() + 1.0) + shift.float()).type_as( + visual_embed + ) + visual_out = self.self_attention(visual_out, rotary_emb=rope) + visual_embed = (visual_embed.float() + gate.float() * visual_out.float()).type_as(visual_embed) + + xattn_bias = self.xattn_bias_table.index_select(0, timestep_indices).unsqueeze(1) + visual_embed = (visual_embed.float() + xattn_bias.float()).type_as(visual_embed) + + shift, scale, gate = torch.chunk(ff_params, 3, dim=-1) + visual_out = (self.feed_forward_norm(visual_embed.float()) * (scale.float() + 1.0) + shift.float()).type_as( + visual_embed + ) + visual_out = self.feed_forward(visual_out) + return (visual_embed.float() + gate.float() * visual_out.float()).type_as(visual_embed) + + +class KandinskyImageSRTransformer3DModel(ModelMixin, ConfigMixin, FromOriginalModelMixin, AttentionMixin): + r""" + The Kandinsky ImageSR 2.0 transformer: a text-free Kandinsky 5 diffusion transformer that predicts the flow + velocity of a low-quality image latent. + + The model is conditioned only on the timestep. The time embedding, the per-block modulation and the contribution of + the zero-text cross-attention are stored as tables with one row per supported timestep, so only the timesteps + listed in `baked_timesteps` are valid inputs. + + Args: + in_visual_dim (`int`, defaults to `16`): + Number of latent channels of the input. + out_visual_dim (`int`, defaults to `16`): + Number of latent channels of the output. + time_dim (`int`, defaults to `512`): + Dimension of the time embedding. + patch_size (`tuple[int, int, int]`, defaults to `(1, 2, 2)`): + Temporal, height and width patch sizes. + model_dim (`int`, defaults to `2560`): + Hidden dimension of the transformer blocks. + ff_dim (`int`, defaults to `10240`): + Hidden dimension of the feed-forward layers. + num_visual_blocks (`int`, defaults to `50`): + Number of transformer blocks. + axes_dims (`tuple[int, int, int]`, defaults to `(32, 48, 48)`): + RoPE dimensions of the temporal, height and width axes. Their sum is the attention head dimension. + baked_timesteps (`tuple[float, ...]`): + Flow timesteps in `(0, 1)` with a precomputed table row. + baked_latent_size (`int`, defaults to `128`): + Latent tile size the tables were computed for. The pipeline uses it to choose its tile size. + """ + + _supports_gradient_checkpointing = True + _no_split_modules = ["KandinskyImageSRTransformerBlock"] + _repeated_blocks = ["KandinskyImageSRTransformerBlock"] + _keep_in_fp32_modules = ["modulation", "time_embed_table", "xattn_bias_table"] + + @register_to_config + def __init__( + self, + in_visual_dim: int = 16, + out_visual_dim: int = 16, + time_dim: int = 512, + patch_size: tuple[int, int, int] = (1, 2, 2), + model_dim: int = 2560, + ff_dim: int = 10240, + num_visual_blocks: int = 50, + axes_dims: tuple[int, int, int] = (32, 48, 48), + baked_timesteps: tuple[float, ...] = ( + 0.005, + 0.01, + 0.015, + 0.02, + 0.025, + 0.035, + 0.05, + 0.07, + 0.086, + 0.1, + 0.118, + 0.134, + 0.15, + 0.17, + 0.18, + 0.1885, + 0.207, + 0.21, + 0.2255, + 0.244, + 0.27, + 0.278, + 0.3, + 0.312, + 0.346, + 0.38, + ), + baked_latent_size: int = 128, + ) -> None: + super().__init__() + head_dim = sum(axes_dims) + num_timesteps = len(baked_timesteps) + + self.visual_embeddings = KandinskyImageSRVisualEmbeddings(in_visual_dim, model_dim, patch_size) + self.visual_rope_embeddings = KandinskyImageSRRoPE3D(axes_dims) + self.visual_transformer_blocks = nn.ModuleList( + [ + KandinskyImageSRTransformerBlock(model_dim, ff_dim, head_dim, num_timesteps) + for _ in range(num_visual_blocks) + ] + ) + self.out_layer = KandinskyImageSROutLayer(model_dim, time_dim, out_visual_dim, patch_size) + self.register_buffer("time_embed_table", torch.zeros(num_timesteps, time_dim)) + + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: Tensor, + timestep: Tensor, + return_dict: bool = True, + ) -> KandinskyImageSRTransformer3DModelOutput | tuple[Tensor]: + r""" + Args: + hidden_states (`torch.Tensor` of shape `(batch_size, num_frames, height, width, in_visual_dim)`): + The low-quality image latent. + timestep (`torch.Tensor` of shape `(batch_size,)`): + Flow timestep scaled to `[0, 1000]`. Each value selects the closest entry of `baked_timesteps`; the + caller is responsible for passing one of those values. + return_dict (`bool`, defaults to `True`): + Whether to return a [`KandinskyImageSRTransformer3DModelOutput`] instead of a plain tuple. + + Returns: + [`KandinskyImageSRTransformer3DModelOutput`] or `tuple`: + The predicted flow velocity; a one-element tuple when `return_dict=False`. + """ + baked_timesteps = torch.tensor(self.config.baked_timesteps, device=timestep.device, dtype=torch.float32) + timestep_indices = (timestep.float()[:, None] / 1000.0 - baked_timesteps[None]).abs().argmin(dim=1) + time_embed = self.time_embed_table.index_select(0, timestep_indices) + + visual_embed = self.visual_embeddings(hidden_states) + visual_shape = visual_embed.shape[:-1] + rope_positions = [torch.arange(size, device=hidden_states.device) for size in visual_shape[1:]] + visual_rope = self.visual_rope_embeddings(visual_shape, rope_positions) + visual_embed = visual_embed.flatten(1, 3) + visual_rope = visual_rope.flatten(1, 3) + + for block in self.visual_transformer_blocks: + if torch.is_grad_enabled() and self.gradient_checkpointing: + visual_embed = self._gradient_checkpointing_func(block, visual_embed, visual_rope, timestep_indices) + else: + visual_embed = block(visual_embed, visual_rope, timestep_indices) + + visual_embed = visual_embed.reshape(*visual_shape, -1) + output = self.out_layer(visual_embed, time_embed) + + if not return_dict: + return (output,) + return KandinskyImageSRTransformer3DModelOutput(sample=output) diff --git a/src/diffusers/modular_pipelines/__init__.py b/src/diffusers/modular_pipelines/__init__.py index 07030cb7c8dc..0f05f3a39439 100644 --- a/src/diffusers/modular_pipelines/__init__.py +++ b/src/diffusers/modular_pipelines/__init__.py @@ -92,6 +92,7 @@ "Ideogram4AutoBlocks", "Ideogram4ModularPipeline", ] + _import_structure["kandinsky_imagesr"] = ["KandinskyImageSRBlocks", "KandinskyImageSRModularPipeline"] _import_structure["kandinsky_s2v"] = [ "KandinskyS2VAutoBlocks", "KandinskyS2VDistilledAutoBlocks", @@ -235,6 +236,7 @@ Ideogram4AutoBlocks, Ideogram4ModularPipeline, ) + from .kandinsky_imagesr import KandinskyImageSRBlocks, KandinskyImageSRModularPipeline from .kandinsky_s2v import ( KandinskyS2VAutoBlocks, KandinskyS2VDistilledAutoBlocks, diff --git a/src/diffusers/modular_pipelines/kandinsky_imagesr/__init__.py b/src/diffusers/modular_pipelines/kandinsky_imagesr/__init__.py new file mode 100644 index 000000000000..7447c4317cbf --- /dev/null +++ b/src/diffusers/modular_pipelines/kandinsky_imagesr/__init__.py @@ -0,0 +1,47 @@ +from typing import TYPE_CHECKING + +from ...utils import ( + DIFFUSERS_SLOW_IMPORT, + OptionalDependencyNotAvailable, + _LazyModule, + get_objects_from_module, + is_torch_available, + is_transformers_available, +) + + +_dummy_objects = {} +_import_structure = {} + +try: + if not (is_transformers_available() and is_torch_available()): + raise OptionalDependencyNotAvailable() +except OptionalDependencyNotAvailable: + from ...utils import dummy_torch_and_transformers_objects # noqa F403 + + _dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects)) +else: + _import_structure["modular_blocks_kandinsky_imagesr"] = ["KandinskyImageSRBlocks"] + _import_structure["modular_pipeline"] = ["KandinskyImageSRModularPipeline"] + +if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT: + try: + if not (is_transformers_available() and is_torch_available()): + raise OptionalDependencyNotAvailable() + except OptionalDependencyNotAvailable: + from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 + else: + from .modular_blocks_kandinsky_imagesr import KandinskyImageSRBlocks + from .modular_pipeline import KandinskyImageSRModularPipeline +else: + import sys + + sys.modules[__name__] = _LazyModule( + __name__, + globals()["__file__"], + _import_structure, + module_spec=__spec__, + ) + + for name, value in _dummy_objects.items(): + setattr(sys.modules[__name__], name, value) diff --git a/src/diffusers/modular_pipelines/kandinsky_imagesr/decoders.py b/src/diffusers/modular_pipelines/kandinsky_imagesr/decoders.py new file mode 100644 index 000000000000..14520d8326f2 --- /dev/null +++ b/src/diffusers/modular_pipelines/kandinsky_imagesr/decoders.py @@ -0,0 +1,171 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math + +import torch + +from ...configuration_utils import FrozenDict +from ...image_processor import VaeImageProcessor +from ...models import AutoencoderKL +from ...utils import logging +from ..modular_pipeline import ModularPipelineBlocks, PipelineState +from ..modular_pipeline_utils import ComponentSpec, InputParam, OutputParam +from .modular_pipeline import KandinskyImageSRModularPipeline, tile_layout + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def decode_latents(vae: AutoencoderKL, latents: torch.Tensor) -> torch.Tensor: + """Decodes scaled VAE latents into a `(batch_size, 3, height, width)` image in `[0, 1]`.""" + image = vae.decode((latents / vae.config.scaling_factor).to(vae.dtype), return_dict=False)[0] + return (image.float().clamp(-1.0, 1.0) + 1.0) * 0.5 + + +def boundary_aware_window( + height: int, width: int, top: bool, bottom: bool, left: bool, right: bool, device: torch.device +) -> torch.Tensor: + """2D Hann window whose halves facing an image border are flat, so border pixels keep their full weight.""" + window_y = 0.5 - 0.5 * torch.cos(2 * math.pi * torch.arange(height, device=device) / height) + window_x = 0.5 - 0.5 * torch.cos(2 * math.pi * torch.arange(width, device=device) / width) + if top: + window_y[: height // 2] = 1.0 + if bottom: + window_y[height // 2 :] = 1.0 + if left: + window_x[: width // 2] = 1.0 + if right: + window_x[width // 2 :] = 1.0 + return window_y[:, None] * window_x[None, :] + + +class KandinskyImageSRDecodeStep(ModularPipelineBlocks): + model_name = "kandinsky-imagesr" + + @property + def description(self) -> str: + return ( + "Decode step that decodes every tile, blends the tiles back with boundary-aware Hann windows and crops " + "each image to its upscaled size." + ) + + @property + def expected_components(self) -> list[ComponentSpec]: + return [ + ComponentSpec("vae", AutoencoderKL), + ComponentSpec( + "image_processor", + VaeImageProcessor, + config=FrozenDict({"do_resize": False, "do_normalize": False, "do_convert_rgb": True}), + default_creation_method="from_config", + ), + ] + + @property + def inputs(self) -> list[InputParam]: + return [ + InputParam( + "latents", + required=True, + type_hint=list[torch.Tensor], + description="Corrected latents of the tiles of every image, from the denoise step.", + ), + InputParam( + "image_sizes", + required=True, + type_hint=list[tuple[int, int]], + description="Original `(height, width)` of every image, from the VAE encoder step.", + ), + InputParam( + "upscale_factor", + type_hint=int, + default=4, + description="Output scale: `1` enhances the image at its original resolution, `2` and `4` upscale it.", + ), + InputParam( + "overlap", + type_hint=float, + default=0.25, + description="Overlap between neighbouring low-resolution tiles as a fraction of the tile size, in " + "`(0, 1)`.", + ), + InputParam.template("output_type"), + ] + + @property + def intermediate_outputs(self) -> list[OutputParam]: + return [OutputParam.template("images", description="The super-resolved images.")] + + @staticmethod + def check_inputs(block_state): + if block_state.output_type not in ("pil", "np", "pt"): + raise ValueError(f"`output_type` must be 'pil', 'np' or 'pt' but is {block_state.output_type!r}.") + if block_state.output_type != "pil" and len(set(block_state.image_sizes)) > 1: + raise ValueError("Images of different sizes can only be returned with `output_type='pil'`.") + if len(block_state.latents) != len(block_state.image_sizes): + raise ValueError( + f"Got tile latents for {len(block_state.latents)} images but {len(block_state.image_sizes)} image sizes." + ) + + @torch.no_grad() + def __call__(self, components: KandinskyImageSRModularPipeline, state: PipelineState) -> PipelineState: + block_state = self.get_block_state(state) + self.check_inputs(block_state) + + tile_size = components.tile_size + upscale_factor = block_state.upscale_factor + device = components._execution_device + outputs = [] + for tile_latents, (height, width) in zip(block_state.latents, block_state.image_sizes): + padded_height, padded_width, tops, lefts = tile_layout( + height, width, tile_size // upscale_factor, block_state.overlap + ) + canvas_height, canvas_width = padded_height * upscale_factor, padded_width * upscale_factor + image_acc = torch.zeros((1, 3, canvas_height, canvas_width), device=device) + weight_acc = torch.zeros((1, 1, canvas_height, canvas_width), device=device) + tile_grid = [(top, left) for top in tops for left in lefts] + if tile_latents.shape[0] != len(tile_grid): + raise ValueError( + f"Got {tile_latents.shape[0]} tile latents for a {height}x{width} image that has {len(tile_grid)}" + " tiles; pass the same `upscale_factor` and `overlap` as to the VAE encoder step." + ) + for (top, left), latent in zip(tile_grid, tile_latents.split(1)): + window = boundary_aware_window( + tile_size, + tile_size, + top=top == tops[0], + bottom=top == tops[-1], + left=left == lefts[0], + right=left == lefts[-1], + device=device, + ) + top, left = top * upscale_factor, left * upscale_factor + tile_area = (..., slice(top, top + tile_size), slice(left, left + tile_size)) + image_acc[tile_area] += decode_latents(components.vae, latent) * window + weight_acc[tile_area] += window + image = image_acc / weight_acc.clamp_min(1e-6) + outputs.append(image[:, :, : height * upscale_factor, : width * upscale_factor]) + + if block_state.output_type == "pil": + block_state.images = [ + components.image_processor.postprocess(output, output_type="pil")[0] for output in outputs + ] + else: + block_state.images = components.image_processor.postprocess( + torch.cat(outputs), output_type=block_state.output_type + ) + + self.set_block_state(state, block_state) + return components, state diff --git a/src/diffusers/modular_pipelines/kandinsky_imagesr/denoise.py b/src/diffusers/modular_pipelines/kandinsky_imagesr/denoise.py new file mode 100644 index 000000000000..46e668fb2b86 --- /dev/null +++ b/src/diffusers/modular_pipelines/kandinsky_imagesr/denoise.py @@ -0,0 +1,123 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from ...models import KandinskyImageSRTransformer3DModel +from ...schedulers import FlowMatchEulerDiscreteScheduler +from ...utils import logging +from ..modular_pipeline import ModularPipelineBlocks, PipelineState +from ..modular_pipeline_utils import ComponentSpec, InputParam, OutputParam +from .modular_pipeline import CREATIVITY_TIMESTEPS, KandinskyImageSRModularPipeline, check_upscale_factor + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +class KandinskyImageSRDenoiseStep(ModularPipelineBlocks): + model_name = "kandinsky-imagesr" + + @property + def description(self) -> str: + return "Denoise step that corrects every tile latent with a single flow step from timestep `t` to 0." + + @property + def expected_components(self) -> list[ComponentSpec]: + return [ + ComponentSpec("transformer", KandinskyImageSRTransformer3DModel), + ComponentSpec("scheduler", FlowMatchEulerDiscreteScheduler), + ] + + @property + def inputs(self) -> list[InputParam]: + return [ + InputParam( + "image_latents", + required=True, + type_hint=list[torch.Tensor], + description="Scaled VAE latents of the tiles of every image, from the VAE encoder step.", + ), + InputParam( + "upscale_factor", + type_hint=int, + default=4, + description="Output scale: `1` enhances the image at its original resolution, `2` and `4` upscale it.", + ), + InputParam( + "creativity", + type_hint=int, + default=4, + description="Calibrated strength level from `0` to `8`. Lower levels preserve fine text and details, " + "higher levels synthesize more texture.", + ), + InputParam( + "one_step_t", + type_hint=float, + description="Raw flow timestep in `(0, 1)` that replaces the `creativity` preset. Must be one of " + "`transformer.config.baked_timesteps`.", + ), + ] + + @property + def intermediate_outputs(self) -> list[OutputParam]: + return [ + OutputParam.template( + "latents", + type_hint=list[torch.Tensor], + description="Corrected latents of the tiles of every image, in the layout of `image_latents`.", + ) + ] + + @staticmethod + def check_inputs(components, block_state): + check_upscale_factor(block_state.upscale_factor) + if type(block_state.creativity) is not int or not 0 <= block_state.creativity <= 8: + raise ValueError(f"`creativity` must be an integer from 0 to 8 but is {block_state.creativity!r}.") + baked_timesteps = components.transformer.config.baked_timesteps + if block_state.one_step_t is not None and not any( + abs(block_state.one_step_t - value) <= 1e-6 for value in baked_timesteps + ): + raise ValueError( + f"`one_step_t` must be one of the timesteps the transformer supports, {list(baked_timesteps)}, but is" + f" {block_state.one_step_t}." + ) + + @torch.no_grad() + def __call__(self, components: KandinskyImageSRModularPipeline, state: PipelineState) -> PipelineState: + block_state = self.get_block_state(state) + self.check_inputs(components, block_state) + + one_step_t = block_state.one_step_t + if one_step_t is None: + one_step_t = CREATIVITY_TIMESTEPS[block_state.upscale_factor][block_state.creativity] + device = components._execution_device + + block_state.latents = [] + for tile_latents in block_state.image_latents: + corrected = [] + for lq_latent in tile_latents.split(1): + # The scheduler's step index advances with every step, so each tile starts a fresh one-step schedule. + components.scheduler.set_timesteps(sigmas=[one_step_t], device=device) + timestep = components.scheduler.timesteps[0] + # The transformer works on `(batch, frames, height, width, channels)` latents + hidden_states = lq_latent.permute(0, 2, 3, 1).unsqueeze(1).to(components.transformer.dtype) + velocity = components.transformer( + hidden_states=hidden_states, timestep=timestep.expand(1), return_dict=False + )[0] + velocity = velocity.squeeze(1).permute(0, 3, 1, 2).float() + corrected.append(components.scheduler.step(velocity, timestep, lq_latent, return_dict=False)[0]) + block_state.latents.append(torch.cat(corrected)) + + self.set_block_state(state, block_state) + return components, state diff --git a/src/diffusers/modular_pipelines/kandinsky_imagesr/encoders.py b/src/diffusers/modular_pipelines/kandinsky_imagesr/encoders.py new file mode 100644 index 000000000000..25e341d70983 --- /dev/null +++ b/src/diffusers/modular_pipelines/kandinsky_imagesr/encoders.py @@ -0,0 +1,151 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import numpy as np +import torch +import torch.nn.functional as F + +from ...configuration_utils import FrozenDict +from ...image_processor import PipelineImageInput, VaeImageProcessor +from ...models import AutoencoderKL +from ...utils import logging +from ..modular_pipeline import ModularPipelineBlocks, PipelineState +from ..modular_pipeline_utils import ComponentSpec, InputParam, OutputParam +from .modular_pipeline import KandinskyImageSRModularPipeline, check_upscale_factor, tile_layout + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def encode_image(vae: AutoencoderKL, image: torch.Tensor) -> torch.Tensor: + """ + Encodes a `(batch_size, 3, height, width)` image in `[0, 1]` into VAE latents scaled by the VAE `scaling_factor`. + The model was trained without the VAE `shift_factor`, so it is not applied. + """ + image = (image * 2.0 - 1.0).to(dtype=vae.dtype) + latents = vae.encode(image).latent_dist.mode() + return latents.float() * vae.config.scaling_factor + + +class KandinskyImageSRVaeEncoderStep(ModularPipelineBlocks): + model_name = "kandinsky-imagesr" + + @property + def description(self) -> str: + return ( + "VAE encoder step that splits every image into overlapping low-resolution tiles, upscales each tile " + "bicubically to the transformer tile size and encodes it." + ) + + @property + def expected_components(self) -> list[ComponentSpec]: + return [ + ComponentSpec("vae", AutoencoderKL), + ComponentSpec( + "image_processor", + VaeImageProcessor, + # Images keep their exact size and stay in [0, 1]; the pipeline pads and normalizes the tiles itself. + config=FrozenDict({"do_resize": False, "do_normalize": False, "do_convert_rgb": True}), + default_creation_method="from_config", + ), + ] + + @property + def inputs(self) -> list[InputParam]: + return [ + InputParam.template( + "image", + type_hint=PipelineImageInput, + description="The image(s) to enhance: PIL images, float NumPy arrays of shape `(height, width, 3)`, " + "or float tensors of shape `(3, height, width)` or `(batch_size, 3, height, width)` with values in " + "`[0, 1]`. Colors are taken as sRGB.", + ), + InputParam( + "upscale_factor", + type_hint=int, + default=4, + description="Output scale: `1` enhances the image at its original resolution, `2` and `4` upscale it.", + ), + InputParam( + "overlap", + type_hint=float, + default=0.25, + description="Overlap between neighbouring low-resolution tiles as a fraction of the tile size, in " + "`(0, 1)`.", + ), + ] + + @property + def intermediate_outputs(self) -> list[OutputParam]: + return [ + OutputParam.template( + "image_latents", + type_hint=list[torch.Tensor], + description="Scaled VAE latents of the tiles of every image, one `(num_tiles, channels, latent_size, " + "latent_size)` tensor per image.", + ), + OutputParam( + "image_sizes", + type_hint=list[tuple[int, int]], + description="Original `(height, width)` of every image.", + ), + ] + + @staticmethod + def check_inputs(block_state): + for item in block_state.image if isinstance(block_state.image, list) else [block_state.image]: + is_integer_tensor = isinstance(item, torch.Tensor) and not item.is_floating_point() + is_integer_array = isinstance(item, np.ndarray) and not np.issubdtype(item.dtype, np.floating) + if is_integer_tensor or is_integer_array: + raise ValueError( + f"NumPy and tensor images must be floating point in [0, 1] but got {item.dtype}; divide integer" + " pixels by 255 first." + ) + check_upscale_factor(block_state.upscale_factor) + # Every inner tile's first row and column has zero blending weight, so neighbouring tiles must overlap. + if not 0.0 < block_state.overlap < 1.0: + raise ValueError(f"`overlap` must be in (0, 1) but is {block_state.overlap}.") + + @torch.no_grad() + def __call__(self, components: KandinskyImageSRModularPipeline, state: PipelineState) -> PipelineState: + block_state = self.get_block_state(state) + self.check_inputs(block_state) + + images = block_state.image if isinstance(block_state.image, list) else [block_state.image] + images = [pixels for item in images for pixels in components.image_processor.preprocess(item).split(1)] + if any(pixels.shape[1] != 3 for pixels in images): + channels = sorted({pixels.shape[1] for pixels in images}) + raise ValueError(f"Images must have 3 channels (RGB) but got {channels}.") + + tile_size = components.tile_size + lq_tile_size = tile_size // block_state.upscale_factor + block_state.image_latents = [] + block_state.image_sizes = [] + for pixels in images: + pixels = pixels.to(device=components._execution_device, dtype=torch.float32) + height, width = pixels.shape[-2:] + padded_height, padded_width, tops, lefts = tile_layout(height, width, lq_tile_size, block_state.overlap) + pixels = F.pad(pixels, (0, padded_width - width, 0, padded_height - height), mode="replicate") + tile_latents = [] + for top in tops: + for left in lefts: + tile = pixels[:, :, top : top + lq_tile_size, left : left + lq_tile_size] + if block_state.upscale_factor != 1: + tile = F.interpolate(tile, size=(tile_size,) * 2, mode="bicubic", align_corners=False) + tile_latents.append(encode_image(components.vae, tile.clamp(0.0, 1.0))) + block_state.image_latents.append(torch.cat(tile_latents)) + block_state.image_sizes.append((height, width)) + + self.set_block_state(state, block_state) + return components, state diff --git a/src/diffusers/modular_pipelines/kandinsky_imagesr/modular_blocks_kandinsky_imagesr.py b/src/diffusers/modular_pipelines/kandinsky_imagesr/modular_blocks_kandinsky_imagesr.py new file mode 100644 index 000000000000..6d63a084e7a5 --- /dev/null +++ b/src/diffusers/modular_pipelines/kandinsky_imagesr/modular_blocks_kandinsky_imagesr.py @@ -0,0 +1,84 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ...utils import logging +from ..modular_pipeline import SequentialPipelineBlocks +from ..modular_pipeline_utils import InsertableDict, OutputParam +from .decoders import KandinskyImageSRDecodeStep +from .denoise import KandinskyImageSRDenoiseStep +from .encoders import KandinskyImageSRVaeEncoderStep + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +KANDINSKY_IMAGESR_BLOCKS = InsertableDict( + [ + ("vae_encoder", KandinskyImageSRVaeEncoderStep()), + ("denoise", KandinskyImageSRDenoiseStep()), + ("decode", KandinskyImageSRDecodeStep()), + ] +) + + +# auto_docstring +class KandinskyImageSRBlocks(SequentialPipelineBlocks): + """ + Modular pipeline for image super-resolution with Kandinsky ImageSR 2.0: the image is enhanced at its original + resolution or upscaled 2x or 4x in overlapping tiles, each corrected by a single flow step. + + Components: + - vae (`AutoencoderKL`) + - image_processor (`VaeImageProcessor`) + - transformer (`KandinskyImageSRTransformer3DModel`) + - scheduler (`FlowMatchEulerDiscreteScheduler`) + + Inputs: + image (`Image | ndarray | Tensor | list | list | list`): + The image(s) to enhance: PIL images, float NumPy arrays of shape `(height, width, 3)`, or float tensors + of shape `(3, height, width)` or `(batch_size, 3, height, width)` with values in `[0, 1]`. Colors are + taken as sRGB. + upscale_factor (`int`, *optional*, defaults to 4): + Output scale: `1` enhances the image at its original resolution, `2` and `4` upscale it. + overlap (`float`, *optional*, defaults to 0.25): + Overlap between neighbouring low-resolution tiles as a fraction of the tile size, in `(0, 1)`. + creativity (`int`, *optional*, defaults to 4): + Calibrated strength level from `0` to `8`. Lower levels preserve fine text and details, higher levels + synthesize more texture. + one_step_t (`float`, *optional*): + Raw flow timestep in `(0, 1)` that replaces the `creativity` preset. Must be one of + `transformer.config.baked_timesteps`. + output_type (`str`, *optional*, defaults to pil): + Output format: 'pil', 'np', 'pt'. + + Outputs: + images (`list`): + The super-resolved images. + """ + + model_name = "kandinsky-imagesr" + + block_classes = KANDINSKY_IMAGESR_BLOCKS.values() + block_names = KANDINSKY_IMAGESR_BLOCKS.keys() + + @property + def description(self): + return ( + "Modular pipeline for image super-resolution with Kandinsky ImageSR 2.0: the image is enhanced at its " + "original resolution or upscaled 2x or 4x in overlapping tiles, each corrected by a single flow step." + ) + + @property + def outputs(self): + return [OutputParam.template("images", description="The super-resolved images.")] diff --git a/src/diffusers/modular_pipelines/kandinsky_imagesr/modular_pipeline.py b/src/diffusers/modular_pipelines/kandinsky_imagesr/modular_pipeline.py new file mode 100644 index 000000000000..d2d0bdb06c3e --- /dev/null +++ b/src/diffusers/modular_pipelines/kandinsky_imagesr/modular_pipeline.py @@ -0,0 +1,80 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ...utils import logging +from ..modular_pipeline import ModularPipeline + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + +# Flow timesteps calibrated for creativity levels 0 to 8 at each upscale factor. Level 4 is the default. +CREATIVITY_TIMESTEPS = { + 1: (0.005, 0.015, 0.025, 0.035, 0.05, 0.07, 0.086, 0.10, 0.118), + 2: (0.07, 0.086, 0.118, 0.134, 0.15, 0.18, 0.21, 0.27, 0.30), + 4: (0.17, 0.1885, 0.207, 0.2255, 0.244, 0.278, 0.312, 0.346, 0.38), +} + + +def check_upscale_factor(upscale_factor: int) -> None: + if type(upscale_factor) is not int or upscale_factor not in CREATIVITY_TIMESTEPS: + raise ValueError(f"`upscale_factor` must be one of {list(CREATIVITY_TIMESTEPS)} but is {upscale_factor}.") + + +def tile_positions(length: int, tile: int, stride: int) -> list[int]: + """Start positions of tiles of size `tile` placed every `stride` pixels, the last one flush with the end.""" + if length <= tile: + return [0] + positions = list(range(0, length - tile, stride)) + if positions[-1] + tile < length: + positions.append(length - tile) + return positions + + +def tile_layout(height: int, width: int, tile: int, overlap: float) -> tuple[int, int, list[int], list[int]]: + """ + Layout of the low-resolution tiles of an image: the size it is replicate-padded to so that it holds at least one + tile, and the tile start positions along each side. + """ + padded_height, padded_width = max(height, tile), max(width, tile) + stride = max(1, int(tile * (1.0 - overlap))) + return ( + padded_height, + padded_width, + tile_positions(padded_height, tile, stride), + tile_positions(padded_width, tile, stride), + ) + + +class KandinskyImageSRModularPipeline(ModularPipeline): + """ + A ModularPipeline for Kandinsky ImageSR 2.0 image super-resolution. + + """ + + default_blocks_name = "KandinskyImageSRBlocks" + + @property + def vae_scale_factor(self): + vae_scale_factor = 8 + if getattr(self, "vae", None) is not None: + vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) + return vae_scale_factor + + @property + def tile_size(self): + # Output tile side in pixels: the latent size the transformer tables were computed for. + tile_size = 1024 + if getattr(self, "transformer", None) is not None: + tile_size = self.transformer.config.baked_latent_size * self.vae_scale_factor + return tile_size diff --git a/src/diffusers/modular_pipelines/modular_pipeline.py b/src/diffusers/modular_pipelines/modular_pipeline.py index dfa700af4765..05485f5a6980 100644 --- a/src/diffusers/modular_pipelines/modular_pipeline.py +++ b/src/diffusers/modular_pipelines/modular_pipeline.py @@ -209,6 +209,7 @@ def _helios_pyramid_map_fn(config_dict=None): ("cosmos3-omni", _create_default_map_fn("Cosmos3OmniModularPipeline")), ("helios", _create_default_map_fn("HeliosModularPipeline")), ("helios-pyramid", _helios_pyramid_map_fn), + ("kandinsky-imagesr", _create_default_map_fn("KandinskyImageSRModularPipeline")), ("kandinsky-s2v", _create_default_map_fn("KandinskyS2VModularPipeline")), ("kandinsky-s2v-distilled", _create_default_map_fn("KandinskyS2VDistilledModularPipeline")), ("hunyuan-video-1.5", _create_default_map_fn("HunyuanVideo15ModularPipeline")), diff --git a/src/diffusers/utils/dummy_pt_objects.py b/src/diffusers/utils/dummy_pt_objects.py index 5ba1d1e1416e..b09a680c5ac2 100644 --- a/src/diffusers/utils/dummy_pt_objects.py +++ b/src/diffusers/utils/dummy_pt_objects.py @@ -1879,6 +1879,21 @@ def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch"]) +class KandinskyImageSRTransformer3DModel(metaclass=DummyObject): + _backends = ["torch"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch"]) + + @classmethod + def from_config(cls, *args, **kwargs): + requires_backends(cls, ["torch"]) + + @classmethod + def from_pretrained(cls, *args, **kwargs): + requires_backends(cls, ["torch"]) + + class KandinskyS2VTransformer3DModel(metaclass=DummyObject): _backends = ["torch"] diff --git a/src/diffusers/utils/dummy_torch_and_transformers_objects.py b/src/diffusers/utils/dummy_torch_and_transformers_objects.py index d24ecfafff39..8547582233bc 100644 --- a/src/diffusers/utils/dummy_torch_and_transformers_objects.py +++ b/src/diffusers/utils/dummy_torch_and_transformers_objects.py @@ -512,6 +512,36 @@ def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch", "transformers"]) +class KandinskyImageSRBlocks(metaclass=DummyObject): + _backends = ["torch", "transformers"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch", "transformers"]) + + @classmethod + def from_config(cls, *args, **kwargs): + requires_backends(cls, ["torch", "transformers"]) + + @classmethod + def from_pretrained(cls, *args, **kwargs): + requires_backends(cls, ["torch", "transformers"]) + + +class KandinskyImageSRModularPipeline(metaclass=DummyObject): + _backends = ["torch", "transformers"] + + def __init__(self, *args, **kwargs): + requires_backends(self, ["torch", "transformers"]) + + @classmethod + def from_config(cls, *args, **kwargs): + requires_backends(cls, ["torch", "transformers"]) + + @classmethod + def from_pretrained(cls, *args, **kwargs): + requires_backends(cls, ["torch", "transformers"]) + + class KandinskyS2VAutoBlocks(metaclass=DummyObject): _backends = ["torch", "transformers"] diff --git a/tests/models/transformers/test_models_transformer_kandinsky_imagesr.py b/tests/models/transformers/test_models_transformer_kandinsky_imagesr.py new file mode 100644 index 000000000000..9f4c7f65f6ce --- /dev/null +++ b/tests/models/transformers/test_models_transformer_kandinsky_imagesr.py @@ -0,0 +1,123 @@ +# coding=utf-8 +# Copyright 2026 HuggingFace Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from diffusers import KandinskyImageSRTransformer3DModel +from diffusers.utils.torch_utils import randn_tensor + +from ...testing_utils import enable_full_determinism, torch_device +from ..testing_utils import ( + AttentionTesterMixin, + BaseModelTesterConfig, + MemoryTesterMixin, + ModelTesterMixin, + TorchCompileTesterMixin, + TrainingTesterMixin, +) + + +enable_full_determinism() + + +class KandinskyImageSRTransformerTesterConfig(BaseModelTesterConfig): + @property + def model_class(self): + return KandinskyImageSRTransformer3DModel + + @property + def pretrained_model_name_or_path(self): + return "kandinskylab/Kandinsky-ImageSR-2.0-Diffusers" + + @property + def pretrained_model_kwargs(self): + return {"subfolder": "transformer"} + + @property + def main_input_name(self) -> str: + return "hidden_states" + + @property + def generator(self): + return torch.Generator("cpu").manual_seed(0) + + def get_init_dict(self) -> dict: + return { + "in_visual_dim": 4, + "out_visual_dim": 4, + "time_dim": 16, + "patch_size": (1, 2, 2), + "model_dim": 16, + "ff_dim": 32, + "num_visual_blocks": 2, + # head_dim = sum(axes_dims) + "axes_dims": (2, 2, 4), + "baked_timesteps": (0.05, 0.15, 0.244), + "baked_latent_size": 8, + } + + def get_dummy_inputs(self, height: int = 8, width: int = 8) -> dict: + return { + "hidden_states": randn_tensor((1, 1, height, width, 4), generator=self.generator, device=torch_device), + "timestep": torch.tensor([150.0], device=torch_device), + } + + @property + def input_shape(self) -> tuple[int, ...]: + return (1, 8, 8, 4) + + @property + def output_shape(self) -> tuple[int, ...]: + return (1, 8, 8, 4) + + +class TestKandinskyImageSRTransformerModel(KandinskyImageSRTransformerTesterConfig, ModelTesterMixin): + def test_timestep_selects_baked_row(self): + model = self.model_class(**self.get_init_dict()).to(torch_device).eval() + num_timesteps, time_dim = model.time_embed_table.shape + with torch.no_grad(): + model.time_embed_table.copy_(torch.randn(num_timesteps, time_dim, generator=self.generator)) + for block in model.visual_transformer_blocks: + block.xattn_bias_table.copy_(torch.randn(block.xattn_bias_table.shape, generator=self.generator)) + # The out-layer modulation is zero-initialized, so it would hide the time embedding. + weight = model.out_layer.modulation.out_layer.weight + weight.copy_(torch.randn(weight.shape, generator=self.generator)) + + inputs = self.get_dummy_inputs() + output = model(**inputs).sample + nearby = model(hidden_states=inputs["hidden_states"], timestep=inputs["timestep"] + 1e-3).sample + other = model(hidden_states=inputs["hidden_states"], timestep=torch.tensor([50.0], device=torch_device)) + + assert torch.equal(output, nearby) + assert not torch.allclose(output, other.sample) + + +class TestKandinskyImageSRTransformerMemory(KandinskyImageSRTransformerTesterConfig, MemoryTesterMixin): + pass + + +class TestKandinskyImageSRTransformerTorchCompile(KandinskyImageSRTransformerTesterConfig, TorchCompileTesterMixin): + @property + def different_shapes_for_compilation(self): + return [(8, 8), (8, 16), (16, 16)] + + +class TestKandinskyImageSRTransformerTraining(KandinskyImageSRTransformerTesterConfig, TrainingTesterMixin): + def test_gradient_checkpointing_is_applied(self): + super().test_gradient_checkpointing_is_applied(expected_set={"KandinskyImageSRTransformer3DModel"}) + + +class TestKandinskyImageSRTransformerAttention(KandinskyImageSRTransformerTesterConfig, AttentionTesterMixin): + pass diff --git a/tests/modular_pipelines/kandinsky_imagesr/__init__.py b/tests/modular_pipelines/kandinsky_imagesr/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/modular_pipelines/kandinsky_imagesr/test_modular_pipeline_kandinsky_imagesr.py b/tests/modular_pipelines/kandinsky_imagesr/test_modular_pipeline_kandinsky_imagesr.py new file mode 100644 index 000000000000..ec07bf4821cf --- /dev/null +++ b/tests/modular_pipelines/kandinsky_imagesr/test_modular_pipeline_kandinsky_imagesr.py @@ -0,0 +1,163 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import numpy as np +import pytest +import torch +from PIL import Image + +from diffusers.modular_pipelines import KandinskyImageSRBlocks, KandinskyImageSRModularPipeline +from diffusers.modular_pipelines.kandinsky_imagesr.decoders import KandinskyImageSRDecodeStep + +from ..testing_utils import ( + BaseModularPipelineTesterConfig, + ModularLoadingTesterMixin, + ModularMemoryTesterMixin, + ModularPipelineTesterMixin, + ModularWorkflowTesterMixin, +) + + +class KandinskyImageSRModularPipelineTesterConfig(BaseModularPipelineTesterConfig): + pipeline_class = KandinskyImageSRModularPipeline + pipeline_blocks_class = KandinskyImageSRBlocks + # The tiny VAE downsamples 2x and the transformer is baked for 8-latent tiles, so the pipeline tiles at 16 pixels. + pretrained_model_name_or_path = "kandinskylab/tiny-kandinsky-imagesr-modular" + params = frozenset(["image", "upscale_factor", "creativity", "one_step_t", "overlap"]) + batch_params = frozenset(["image"]) + optional_params = frozenset(["output_type"]) + # The 8x12 input at 2x is two 8-pixel low-resolution tiles side by side, each an 8x8 grid of 4-channel latents. + expected_latents_shape = (2, 4, 8, 8) + expected_workflow_defaults = { + None: { + "components": { + "vae": "AutoencoderKL", + "image_processor": "VaeImageProcessor", + "transformer": "KandinskyImageSRTransformer3DModel", + "scheduler": "FlowMatchEulerDiscreteScheduler", + }, + "required_inputs": ["image"], + "inputs": { + "upscale_factor": 4, + "overlap": 0.25, + "creativity": 4, + "one_step_t": None, + "output_type": "pil", + }, + "component_configs": {"image_processor": {"do_resize": False, "do_normalize": False}}, + }, + } + + def get_dummy_inputs(self, seed=0): + return { + "image": torch.rand((3, 8, 12), generator=self.get_generator(seed)), + "upscale_factor": 2, + "output_type": "pt", + } + + +class TestKandinskyImageSRModularPipelineFast(KandinskyImageSRModularPipelineTesterConfig, ModularPipelineTesterMixin): + @pytest.mark.skip(reason="A single flow step without a denoising loop; `insert_step_callback` is not supported.") + def test_step_callback(self): + pass + + @pytest.mark.skip(reason="A single flow step without a denoising loop; `insert_step_callback` is not supported.") + def test_step_callback_early_stop(self): + pass + + @pytest.mark.parametrize("upscale_factor", [1, 2, 4]) + @pytest.mark.parametrize("shape", [(3, 8, 12), (3, 5, 7), (3, 1, 1)], ids=["two-tiles", "odd", "one-pixel"]) + def test_output_size(self, shape, upscale_factor): + # Inputs smaller than a tile or with sides that are not a multiple of it are padded and cropped back. + pipe = self.get_pipeline() + image = torch.rand(shape, generator=self.get_generator(0)) + images = pipe(image=image, upscale_factor=upscale_factor, output_type="pt", output="images") + assert images.shape == (1, 3, shape[1] * upscale_factor, shape[2] * upscale_factor) + assert torch.isfinite(images).all() + + def test_creativity_preset_matches_one_step_t(self): + pipe = self.get_pipeline() + inputs = self.get_dummy_inputs() + # Level 4 is the default for every scale; at 2x it is t = 0.15. + default = pipe(**inputs, output="images") + by_level = pipe(**inputs, creativity=4, output="images") + by_value = pipe(**inputs, one_step_t=0.15, output="images") + overridden = pipe(**inputs, creativity=0, one_step_t=0.15, output="images") + other_level = pipe(**inputs, creativity=8, output="images") + assert torch.equal(default, by_level) + assert torch.equal(default, by_value) + assert torch.equal(default, overridden) + assert not torch.equal(default, other_level) + + def test_mixed_sizes_as_pil(self): + pipe = self.get_pipeline() + images = pipe(image=[Image.new("RGB", (12, 8)), Image.new("RGB", (8, 8))], upscale_factor=2, output="images") + assert [image.size for image in images] == [(24, 16), (16, 16)] + + @pytest.mark.parametrize( + ("arguments", "match"), + [ + pytest.param({"creativity": 9}, "`creativity` must be", id="creativity-out-of-range"), + pytest.param({"creativity": 4.0}, "`creativity` must be", id="creativity-not-int"), + pytest.param({"one_step_t": 0.16}, "`one_step_t` must be", id="one-step-t-not-baked"), + pytest.param({"upscale_factor": 3}, "`upscale_factor` must be", id="upscale-factor-unsupported"), + pytest.param({"upscale_factor": 2.0}, "`upscale_factor` must be", id="upscale-factor-not-int"), + # Without overlap the zero-weight first row and column of every inner tile would stay uncovered. + pytest.param({"overlap": 0.0}, "`overlap` must be", id="overlap-zero"), + pytest.param({"output_type": "latent"}, "`output_type` must be", id="output-type-unsupported"), + pytest.param({"image": np.zeros((8, 12, 3), dtype=np.uint8)}, "floating point", id="integer-pixels"), + pytest.param({"image": torch.zeros((4, 8, 12))}, "3 channels", id="four-channels"), + pytest.param( + {"image": [torch.zeros((3, 8, 12)), torch.zeros((3, 8, 8))]}, + "different sizes", + id="mixed-sizes-as-tensor", + ), + ], + ) + def test_rejects_invalid_inputs(self, arguments, match): + pipe = self.get_pipeline() + with pytest.raises(ValueError, match=match): + pipe(**{**self.get_dummy_inputs(), **arguments}, output="images") + + @pytest.mark.parametrize( + ("num_tiles", "image_sizes", "match"), + [ + pytest.param(3, [(8, 12)], "tile latents for a 8x12 image", id="tile-count"), + pytest.param(1, [(8, 12), (8, 12)], "image sizes", id="image-count"), + ], + ) + def test_decode_rejects_latents_that_do_not_match_the_tiles(self, num_tiles, image_sizes, match): + # Decoding on its own, the latents must come from an encode step run with the same tiling inputs. + decode = KandinskyImageSRDecodeStep().init_pipeline(self.pretrained_model_name_or_path) + decode.load_components() + with pytest.raises(ValueError, match=match): + decode( + latents=[torch.zeros(num_tiles, 4, 8, 8)], image_sizes=image_sizes, upscale_factor=2, output="images" + ) + + +class TestKandinskyImageSRModularPipelineLoading( + KandinskyImageSRModularPipelineTesterConfig, ModularLoadingTesterMixin +): + pass + + +class TestKandinskyImageSRModularPipelineWorkflow( + KandinskyImageSRModularPipelineTesterConfig, ModularWorkflowTesterMixin +): + pass + + +class TestKandinskyImageSRModularPipelineMemory(KandinskyImageSRModularPipelineTesterConfig, ModularMemoryTesterMixin): + pass