From 0bebe514b1c38074cef0ebf3aa33238591f75d2c Mon Sep 17 00:00:00 2001 From: Irina Tolstykh Date: Tue, 1 Dec 2026 18:49:26 +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 | 102 +++++ 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/pipelines/__init__.py | 2 + .../pipelines/kandinsky_imagesr/__init__.py | 23 + .../pipeline_kandinsky_imagesr.py | 294 +++++++++++++ .../kandinsky_imagesr/pipeline_output.py | 21 + src/diffusers/utils/dummy_pt_objects.py | 45 ++ ...st_models_transformer_kandinsky_imagesr.py | 123 ++++++ tests/pipelines/kandinsky_imagesr/__init__.py | 0 .../test_pipeline_kandinsky_imagesr.py | 154 +++++++ 16 files changed, 1223 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/pipelines/kandinsky_imagesr/__init__.py create mode 100644 src/diffusers/pipelines/kandinsky_imagesr/pipeline_kandinsky_imagesr.py create mode 100644 src/diffusers/pipelines/kandinsky_imagesr/pipeline_output.py create mode 100644 tests/models/transformers/test_models_transformer_kandinsky_imagesr.py create mode 100644 tests/pipelines/kandinsky_imagesr/__init__.py create mode 100644 tests/pipelines/kandinsky_imagesr/test_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..1b7dc0868612 --- /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 [`KandinskyImageSRPipeline`] 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..2d4da391507d --- /dev/null +++ b/docs/source/en/api/pipelines/kandinsky_imagesr.md @@ -0,0 +1,102 @@ + + +# 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. + +## 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 KandinskyImageSRPipeline +from diffusers.utils import load_image + +pipe = KandinskyImageSRPipeline.from_pretrained( + "kandinskylab/Kandinsky-ImageSR-2.0-Diffusers", dtype=torch.bfloat16 +) +pipe.to("cuda") + +image = load_image("input.png") +pipe(image, upscale_factor=4, creativity=4).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 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. + +## 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`]. Pass the +transformer to the pipeline, which supplies the VAE and the scheduler. + +```python +import torch +from diffusers import GGUFQuantizationConfig, KandinskyImageSRPipeline, KandinskyImageSRTransformer3DModel + +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 = KandinskyImageSRPipeline.from_pretrained( + "kandinskylab/Kandinsky-ImageSR-2.0-Diffusers", transformer=transformer, dtype=torch.bfloat16 +) +pipe.to("cuda") +``` + +## KandinskyImageSRPipeline + +[[autodoc]] KandinskyImageSRPipeline + - all + - __call__ + +## KandinskyImageSRPipelineOutput + +[[autodoc]] pipelines.kandinsky_imagesr.pipeline_output.KandinskyImageSRPipelineOutput diff --git a/src/diffusers/__init__.py b/src/diffusers/__init__.py index 4690e8bd197f..c271f8a1878a 100644 --- a/src/diffusers/__init__.py +++ b/src/diffusers/__init__.py @@ -337,6 +337,7 @@ "Kandinsky6SRTransformer3DModel", "Kandinsky6SRVAE", "Kandinsky6Transformer3DModel", + "KandinskyImageSRTransformer3DModel", "KandinskyS2VTransformer3DModel", "Krea2Transformer2DModel", "LatteTransformer3DModel", @@ -461,6 +462,8 @@ "DiffusionPipeline", "DiTPipeline", "ImagePipelineOutput", + "KandinskyImageSRPipeline", + "KandinskyImageSRPipelineOutput", "KarrasVePipeline", "LDMPipeline", "LDMSuperResolutionPipeline", @@ -1268,6 +1271,7 @@ Kandinsky6SRTransformer3DModel, Kandinsky6SRVAE, Kandinsky6Transformer3DModel, + KandinskyImageSRTransformer3DModel, KandinskyS2VTransformer3DModel, Krea2Transformer2DModel, LatteTransformer3DModel, @@ -1389,6 +1393,8 @@ DiffusionPipeline, DiTPipeline, ImagePipelineOutput, + KandinskyImageSRPipeline, + KandinskyImageSRPipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, 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/pipelines/__init__.py b/src/diffusers/pipelines/__init__.py index 33e8f812e721..dc4d6b6e4331 100644 --- a/src/diffusers/pipelines/__init__.py +++ b/src/diffusers/pipelines/__init__.py @@ -50,6 +50,7 @@ _import_structure["ddpm"] = ["DDPMPipeline"] _import_structure["rfd4_proteina"] = ["RFD4ProteinaPipeline"] _import_structure["dit"] = ["DiTPipeline"] + _import_structure["kandinsky_imagesr"] = ["KandinskyImageSRPipeline", "KandinskyImageSRPipelineOutput"] _import_structure["latent_diffusion"].extend(["LDMSuperResolutionPipeline"]) _import_structure["pipeline_utils"] = [ "AudioPipelineOutput", @@ -550,6 +551,7 @@ ScoreSdeVePipeline, ) from .dit import DiTPipeline + from .kandinsky_imagesr import KandinskyImageSRPipeline, KandinskyImageSRPipelineOutput from .latent_diffusion import LDMSuperResolutionPipeline from .pipeline_utils import ( AudioPipelineOutput, diff --git a/src/diffusers/pipelines/kandinsky_imagesr/__init__.py b/src/diffusers/pipelines/kandinsky_imagesr/__init__.py new file mode 100644 index 000000000000..b189ccdbb244 --- /dev/null +++ b/src/diffusers/pipelines/kandinsky_imagesr/__init__.py @@ -0,0 +1,23 @@ +from typing import TYPE_CHECKING + +from ...utils import DIFFUSERS_SLOW_IMPORT, _LazyModule + + +_import_structure = { + "pipeline_kandinsky_imagesr": ["KandinskyImageSRPipeline"], + "pipeline_output": ["KandinskyImageSRPipelineOutput"], +} + +if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT: + from .pipeline_kandinsky_imagesr import KandinskyImageSRPipeline + from .pipeline_output import KandinskyImageSRPipelineOutput + +else: + import sys + + sys.modules[__name__] = _LazyModule( + __name__, + globals()["__file__"], + _import_structure, + module_spec=__spec__, + ) diff --git a/src/diffusers/pipelines/kandinsky_imagesr/pipeline_kandinsky_imagesr.py b/src/diffusers/pipelines/kandinsky_imagesr/pipeline_kandinsky_imagesr.py new file mode 100644 index 000000000000..a3d2b86c095f --- /dev/null +++ b/src/diffusers/pipelines/kandinsky_imagesr/pipeline_kandinsky_imagesr.py @@ -0,0 +1,294 @@ +# 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 numpy as np +import torch +import torch.nn.functional as F + +from ...image_processor import PipelineImageInput, VaeImageProcessor +from ...models import AutoencoderKL, KandinskyImageSRTransformer3DModel +from ...schedulers import FlowMatchEulerDiscreteScheduler +from ...utils import replace_example_docstring +from ..pipeline_utils import DiffusionPipeline +from .pipeline_output import KandinskyImageSRPipelineOutput + + +EXAMPLE_DOC_STRING = """ + Examples: + ```python + >>> import torch + >>> from diffusers import KandinskyImageSRPipeline + >>> from diffusers.utils import load_image + + >>> pipe = KandinskyImageSRPipeline.from_pretrained( + ... "kandinskylab/Kandinsky-ImageSR-2.0-Diffusers", dtype=torch.bfloat16 + ... ) + >>> pipe.to("cuda") + + >>> image = load_image( + ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg" + ... ) + >>> upscaled = pipe(image, upscale_factor=4, creativity=4).images[0] + >>> upscaled.save("astronaut_x4.png") + ``` +""" + +# 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), +} +DEFAULT_CREATIVITY = 4 + + +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 _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 KandinskyImageSRPipeline(DiffusionPipeline): + r""" + Pipeline for image super-resolution with Kandinsky ImageSR 2.0. + + The image is split into overlapping low-resolution tiles. Each tile is bicubically upscaled to the transformer tile + size, encoded with the VAE, corrected by a single flow step of the transformer from timestep `t` to `0`, and + decoded. The decoded tiles are blended back with boundary-aware Hann windows. The same model enhances an image at + its original resolution (`upscale_factor=1`) or upscales it by 2 or 4. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods + implemented for all pipelines (downloading, saving, running on a particular device, etc.). + + Args: + transformer ([`KandinskyImageSRTransformer3DModel`]): + Transformer that predicts the flow velocity of the low-quality tile latents. + vae ([`AutoencoderKL`]): + Variational auto-encoder used to encode the tiles and decode the corrected latents. + scheduler ([`FlowMatchEulerDiscreteScheduler`]): + Scheduler that takes the flow step from `t` to `0`. + """ + + model_cpu_offload_seq = "transformer->vae" + + def __init__( + self, + transformer: KandinskyImageSRTransformer3DModel, + vae: AutoencoderKL, + scheduler: FlowMatchEulerDiscreteScheduler, + ) -> None: + super().__init__() + self.register_modules(transformer=transformer, vae=vae, scheduler=scheduler) + + self.vae_scale_factor = ( + 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) is not None else 8 + ) + self.tile_size = ( + self.transformer.config.baked_latent_size * self.vae_scale_factor + if getattr(self, "transformer", None) is not None + else 1024 + ) + # Images keep their exact size and stay in [0, 1]; the pipeline pads and normalizes the tiles itself. + self.image_processor = VaeImageProcessor(do_resize=False, do_normalize=False, do_convert_rgb=True) + + def check_inputs(self, image, upscale_factor, creativity, one_step_t, overlap, output_type): + for item in image if isinstance(image, list) else [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." + ) + 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}.") + if creativity is not None and one_step_t is not None: + raise ValueError("Pass either `creativity` or `one_step_t`, not both.") + if creativity is not None and (type(creativity) is not int or not 0 <= creativity <= 8): + raise ValueError(f"`creativity` must be an integer from 0 to 8 but is {creativity!r}.") + baked_timesteps = self.transformer.config.baked_timesteps + if one_step_t is not None and not any(abs(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" {one_step_t}." + ) + # Every inner tile's first row and column has zero blending weight, so neighbouring tiles must overlap. + if not 0.0 < overlap < 1.0: + raise ValueError(f"`overlap` must be in (0, 1) but is {overlap}.") + if output_type not in ("pil", "np", "pt"): + raise ValueError(f"`output_type` must be 'pil', 'np' or 'pt' but is {output_type!r}.") + + def encode_image(self, image: torch.Tensor) -> torch.Tensor: + r""" + 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=self.vae.dtype) + latents = self.vae.encode(image).latent_dist.mode() + return latents.float() * self.vae.config.scaling_factor + + def decode_latents(self, latents: torch.Tensor) -> torch.Tensor: + r"""Decodes scaled VAE latents into a `(batch_size, 3, height, width)` image in `[0, 1]`.""" + image = self.vae.decode((latents / self.vae.config.scaling_factor).to(self.vae.dtype), return_dict=False)[0] + return (image.float().clamp(-1.0, 1.0) + 1.0) * 0.5 + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + image: PipelineImageInput, + upscale_factor: int = 4, + creativity: int | None = None, + one_step_t: float | None = None, + overlap: float = 0.25, + output_type: str = "pil", + return_dict: bool = True, + ) -> KandinskyImageSRPipelineOutput | tuple: + r""" + The call function to the pipeline for super-resolution. + + Args: + image (`PipelineImageInput`): + 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. Images may have different sizes when `output_type="pil"`. + upscale_factor (`int`, defaults to `4`): + Output scale: `1` enhances the image at its original resolution, `2` and `4` upscale it. + creativity (`int`, *optional*): + Calibrated strength level from `0` to `8`; defaults to `4`. Lower levels preserve fine text and + details, higher levels synthesize more texture. Mutually exclusive with `one_step_t`. + one_step_t (`float`, *optional*): + Raw flow timestep in `(0, 1)`. Must be one of `transformer.config.baked_timesteps`. + overlap (`float`, defaults to `0.25`): + Overlap between neighbouring low-resolution tiles as a fraction of the tile size, in `(0, 1)`. + output_type (`str`, defaults to `"pil"`): + The output format of the images: `"pil"`, `"np"` or `"pt"`. + return_dict (`bool`, defaults to `True`): + Whether or not to return a [`KandinskyImageSRPipelineOutput`] instead of a plain tuple. + + Examples: + + Returns: + [`KandinskyImageSRPipelineOutput`] or `tuple`: + The super-resolved images; a one-element tuple when `return_dict=False`. + """ + # 1. Check inputs and pick the flow timestep + self.check_inputs(image, upscale_factor, creativity, one_step_t, overlap, output_type) + if one_step_t is None: + level = DEFAULT_CREATIVITY if creativity is None else creativity + one_step_t = CREATIVITY_TIMESTEPS[upscale_factor][level] + device = self._execution_device + + # 2. Preprocess every image into a `(1, 3, height, width)` tensor in [0, 1] at its original size + images = image if isinstance(image, list) else [image] + images = [pixels for item in images for pixels in self.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}.") + if output_type != "pil" and len({pixels.shape for pixels in images}) > 1: + raise ValueError("Images of different sizes can only be returned with `output_type='pil'`.") + + lq_tile_size = self.tile_size // upscale_factor + stride = max(1, int(lq_tile_size * (1.0 - overlap))) + outputs = [] + for pixels in images: + pixels = pixels.to(device=device, dtype=torch.float32) + height, width = pixels.shape[-2:] + # Images smaller than one tile are replicate-padded and cropped back after blending. + pad_height, pad_width = max(0, lq_tile_size - height), max(0, lq_tile_size - width) + pixels = F.pad(pixels, (0, pad_width, 0, pad_height), mode="replicate") + tops = _tile_positions(pixels.shape[-2], lq_tile_size, stride) + lefts = _tile_positions(pixels.shape[-1], lq_tile_size, stride) + tile_grid = [(top, left) for top in tops for left in lefts] + + # 3. Encode every tile, bicubically upscaled to the transformer tile size + lq_latents = [] + for top, left in tile_grid: + tile = pixels[:, :, top : top + lq_tile_size, left : left + lq_tile_size] + if upscale_factor != 1: + tile = F.interpolate(tile, size=(self.tile_size,) * 2, mode="bicubic", align_corners=False) + lq_latents.append(self.encode_image(tile.clamp(0.0, 1.0))) + + # 4. Correct every tile latent with one flow step from `one_step_t` to 0 + latents = [] + with self.progress_bar(total=len(tile_grid)) as progress_bar: + for lq_latent in lq_latents: + self.scheduler.set_timesteps(sigmas=[one_step_t], device=device) + timestep = self.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(self.transformer.dtype) + velocity = self.transformer( + hidden_states=hidden_states, timestep=timestep.expand(1), return_dict=False + )[0] + velocity = velocity.squeeze(1).permute(0, 3, 1, 2).float() + latents.append(self.scheduler.step(velocity, timestep, lq_latent, return_dict=False)[0]) + progress_bar.update() + del lq_latents + + # 5. Decode the tiles and blend them into the output canvas + canvas_height, canvas_width = pixels.shape[-2] * upscale_factor, pixels.shape[-1] * 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) + for (top, left), latent in zip(tile_grid, latents): + window = _boundary_aware_window( + self.tile_size, + self.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 + self.tile_size), slice(left, left + self.tile_size)) + image_acc[tile_area] += self.decode_latents(latent) * window + weight_acc[tile_area] += window + image_out = image_acc / weight_acc.clamp_min(1e-6) + outputs.append(image_out[:, :, : height * upscale_factor, : width * upscale_factor]) + + # 6. Postprocess + if output_type == "pil": + images = [self.image_processor.postprocess(output, output_type="pil")[0] for output in outputs] + else: + images = self.image_processor.postprocess(torch.cat(outputs), output_type=output_type) + + # Offload all models + self.maybe_free_model_hooks() + + if not return_dict: + return (images,) + return KandinskyImageSRPipelineOutput(images=images) diff --git a/src/diffusers/pipelines/kandinsky_imagesr/pipeline_output.py b/src/diffusers/pipelines/kandinsky_imagesr/pipeline_output.py new file mode 100644 index 000000000000..0150b3019cbf --- /dev/null +++ b/src/diffusers/pipelines/kandinsky_imagesr/pipeline_output.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass + +import numpy as np +import PIL.Image +import torch + +from ...utils import BaseOutput + + +@dataclass +class KandinskyImageSRPipelineOutput(BaseOutput): + r""" + Output class for the Kandinsky ImageSR pipeline. + + Args: + images (`list[PIL.Image.Image]`, `np.ndarray` or `torch.Tensor`): + The super-resolved images: a list of PIL images, a NumPy array of shape `(batch_size, height, width, 3)`, + or a tensor of shape `(batch_size, 3, height, width)`. + """ + + images: list[PIL.Image.Image] | np.ndarray | torch.Tensor diff --git a/src/diffusers/utils/dummy_pt_objects.py b/src/diffusers/utils/dummy_pt_objects.py index 5ba1d1e1416e..0537da075af8 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"] @@ -3516,6 +3531,36 @@ def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch"]) +class KandinskyImageSRPipeline(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 KandinskyImageSRPipelineOutput(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 KarrasVePipeline(metaclass=DummyObject): _backends = ["torch"] 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/pipelines/kandinsky_imagesr/__init__.py b/tests/pipelines/kandinsky_imagesr/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/pipelines/kandinsky_imagesr/test_pipeline_kandinsky_imagesr.py b/tests/pipelines/kandinsky_imagesr/test_pipeline_kandinsky_imagesr.py new file mode 100644 index 000000000000..172737cbefd4 --- /dev/null +++ b/tests/pipelines/kandinsky_imagesr/test_pipeline_kandinsky_imagesr.py @@ -0,0 +1,154 @@ +# Copyright 2026 The Kandinsky Team and The HuggingFace Team. +# +# 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 diffusers import ( + AutoencoderKL, + FlowMatchEulerDiscreteScheduler, + KandinskyImageSRPipeline, + KandinskyImageSRTransformer3DModel, +) + +from ...testing_utils import assert_tensors_close, torch_device +from ..testing_utils import BasePipelineTesterConfig, MemoryTesterMixin, PipelineTesterMixin + + +# Every timestep the released transformer has a table row for. +BAKED_TIMESTEPS = ( + 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, +) # fmt: skip + + +class KandinskyImageSRPipelineTesterConfig(BasePipelineTesterConfig): + pipeline_class = KandinskyImageSRPipeline + required_input_params_in_call_signature = frozenset(["image", "upscale_factor"]) + batch_input_params = frozenset(["image"]) + optional_input_params = frozenset(["creativity", "one_step_t", "overlap", "output_type", "return_dict"]) + # (channels, height, width) for output_type="pt": the 8x12 input upscaled 2x. + output_shape = (3, 16, 24) + + def get_dummy_components(self): + torch.manual_seed(0) + # A 4-pixel latent grid per 8-latent tile: with the 2x VAE below, the pipeline tiles at 16 pixels. + transformer = KandinskyImageSRTransformer3DModel( + 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, + axes_dims=(2, 2, 4), + baked_timesteps=BAKED_TIMESTEPS, + baked_latent_size=8, + ) + # The tables are zeros at init, which would bypass attention and the feed-forward entirely. + with torch.no_grad(): + for name, table in transformer.named_buffers(): + if name.endswith("_table"): + table.copy_(torch.randn_like(table) * 0.1) + + torch.manual_seed(0) + vae = AutoencoderKL( + in_channels=3, + out_channels=3, + down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D"), + up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D"), + block_out_channels=(4, 8), + layers_per_block=1, + latent_channels=4, + norm_num_groups=2, + sample_size=16, + use_quant_conv=False, + use_post_quant_conv=False, + ) + + scheduler = FlowMatchEulerDiscreteScheduler(shift=1.0) + + return {"transformer": transformer, "vae": vae, "scheduler": scheduler} + + def get_dummy_inputs(self): + return { + "image": torch.rand((3, 8, 12), generator=self.get_generator(0)), + "upscale_factor": 2, + "output_type": "pt", + } + + +class TestKandinskyImageSRPipeline(KandinskyImageSRPipelineTesterConfig, PipelineTesterMixin): + # The pipeline is deterministic and takes no `generator`, which the mixin versions of the two batch tests always + # pass, so they are restated here without it. + def test_inference_batch_consistent(self): + pipe = self.get_pipeline().to(torch_device) + inputs = self.get_dummy_inputs() + output = pipe(**{**inputs, "image": self.batch_input(inputs["image"], 2)}) + assert len(output[0]) == 2 + + def test_inference_batch_single_identical(self): + pipe = self.get_pipeline().to(torch_device) + inputs = self.get_dummy_inputs() + single = pipe(**inputs)[0] + batched = pipe(**{**inputs, "image": self.batch_input(inputs["image"], 3)})[0] + assert batched.shape[0] == 3 + assert_tensors_close(batched[0], single[0], atol=1e-4, msg="Batched output differs from single.") + + def test_kandinsky_imagesr_scales(self): + pipe = self.get_pipeline().to(torch_device) + # Inputs smaller than a tile or with sides that are not a multiple of it are padded and cropped back. + for shape in ((3, 8, 12), (3, 5, 7), (3, 1, 1)): + image = torch.rand(shape, generator=self.get_generator(0)) + for upscale_factor in (1, 2, 4): + images = pipe(image=image, upscale_factor=upscale_factor, output_type="pt").images + expected = (1, 3, shape[1] * upscale_factor, shape[2] * upscale_factor) + assert images.shape == expected, f"unexpected shape for {shape} at x{upscale_factor}" + assert not torch.isnan(images).any() + + def test_kandinsky_imagesr_creativity_matches_one_step_t(self): + pipe = self.get_pipeline().to(torch_device) + # Level 4 is the default for every scale; at 2x it is t = 0.15. + by_level = pipe(**self.get_dummy_inputs(), creativity=4).images + by_value = pipe(**self.get_dummy_inputs(), one_step_t=0.15).images + default = pipe(**self.get_dummy_inputs()).images + assert torch.equal(by_level, by_value) + assert torch.equal(by_level, default) + + @pytest.mark.parametrize( + "arguments", + [ + pytest.param({"creativity": 9}, id="creativity-out-of-range"), + pytest.param({"creativity": 4.0}, id="creativity-not-int"), + pytest.param({"creativity": 1, "one_step_t": 0.15}, id="creativity-and-one-step-t"), + pytest.param({"one_step_t": 0.16}, id="one-step-t-not-baked"), + pytest.param({"upscale_factor": 3}, id="upscale-factor-unsupported"), + pytest.param({"upscale_factor": 2.0}, 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}, id="overlap-zero"), + pytest.param({"output_type": "latent"}, id="output-type-unsupported"), + pytest.param({"image": np.zeros((8, 12, 3), dtype=np.uint8)}, id="integer-pixels"), + pytest.param({"image": torch.zeros((4, 8, 12))}, id="four-channels"), + pytest.param({"image": [torch.zeros((3, 8, 12)), torch.zeros((3, 8, 8))]}, id="mixed-sizes-as-tensor"), + ], + ) + def test_kandinsky_imagesr_rejects_invalid_inputs(self, arguments): + pipe = self.get_pipeline().to(torch_device) + with pytest.raises(ValueError): + pipe(**{**self.get_dummy_inputs(), **arguments}) + + +class TestKandinskyImageSRPipelineMemory(KandinskyImageSRPipelineTesterConfig, MemoryTesterMixin): + pass