Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
97ae914
·
verified ·
1 Parent(s): 89fee37

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. main/README.md +98 -0
  2. main/mod_controlnet_tile_sr_sdxl.py +1862 -0
main/README.md CHANGED
@@ -53,6 +53,7 @@ Please also check out our [Community Scripts](https://github.com/huggingface/dif
53
  | Stable Diffusion Mixture Tiling Pipeline SD 1.5 | A pipeline generates cohesive images by integrating multiple diffusion processes, each focused on a specific image region and considering boundary effects for smooth blending | [Stable Diffusion Mixture Tiling Pipeline SD 1.5](#stable-diffusion-mixture-tiling-pipeline-sd-15) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/albarji/mixture-of-diffusers) | [Álvaro B Jiménez](https://github.com/albarji/) |
54
  | Stable Diffusion Mixture Canvas Pipeline SD 1.5 | A pipeline generates cohesive images by integrating multiple diffusion processes, each focused on a specific image region and considering boundary effects for smooth blending. Works by defining a list of Text2Image region objects that detail the region of influence of each diffuser. | [Stable Diffusion Mixture Canvas Pipeline SD 1.5](#stable-diffusion-mixture-canvas-pipeline-sd-15) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/albarji/mixture-of-diffusers) | [Álvaro B Jiménez](https://github.com/albarji/) |
55
  | Stable Diffusion Mixture Tiling Pipeline SDXL | A pipeline generates cohesive images by integrating multiple diffusion processes, each focused on a specific image region and considering boundary effects for smooth blending | [Stable Diffusion Mixture Tiling Pipeline SDXL](#stable-diffusion-mixture-tiling-pipeline-sdxl) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/elismasilva/mixture-of-diffusers-sdxl-tiling) | [Eliseu Silva](https://github.com/DEVAIEXP/) |
 
56
  | FABRIC - Stable Diffusion with feedback Pipeline | pipeline supports feedback from liked and disliked images | [Stable Diffusion Fabric Pipeline](#stable-diffusion-fabric-pipeline) | [Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/stable_diffusion_fabric.ipynb)| [Shauray Singh](https://shauray8.github.io/about_shauray/) |
57
  | sketch inpaint - Inpainting with non-inpaint Stable Diffusion | sketch inpaint much like in automatic1111 | [Masked Im2Im Stable Diffusion Pipeline](#stable-diffusion-masked-im2im) | - | [Anatoly Belikov](https://github.com/noskill) |
58
  | sketch inpaint xl - Inpainting with non-inpaint Stable Diffusion | sketch inpaint much like in automatic1111 | [Masked Im2Im Stable Diffusion XL Pipeline](#stable-diffusion-xl-masked-im2im) | - | [Anatoly Belikov](https://github.com/noskill) |
@@ -2630,6 +2631,103 @@ image = pipe(
2630
 
2631
  ![mixture_tiling_results](https://huggingface.co/datasets/elismasilva/results/resolve/main/mixture_of_diffusers_sdxl_1.png)
2632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2633
  ### TensorRT Inpainting Stable Diffusion Pipeline
2634
 
2635
  The TensorRT Pipeline can be used to accelerate the Inpainting Stable Diffusion Inference run.
 
53
  | Stable Diffusion Mixture Tiling Pipeline SD 1.5 | A pipeline generates cohesive images by integrating multiple diffusion processes, each focused on a specific image region and considering boundary effects for smooth blending | [Stable Diffusion Mixture Tiling Pipeline SD 1.5](#stable-diffusion-mixture-tiling-pipeline-sd-15) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/albarji/mixture-of-diffusers) | [Álvaro B Jiménez](https://github.com/albarji/) |
54
  | Stable Diffusion Mixture Canvas Pipeline SD 1.5 | A pipeline generates cohesive images by integrating multiple diffusion processes, each focused on a specific image region and considering boundary effects for smooth blending. Works by defining a list of Text2Image region objects that detail the region of influence of each diffuser. | [Stable Diffusion Mixture Canvas Pipeline SD 1.5](#stable-diffusion-mixture-canvas-pipeline-sd-15) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/albarji/mixture-of-diffusers) | [Álvaro B Jiménez](https://github.com/albarji/) |
55
  | Stable Diffusion Mixture Tiling Pipeline SDXL | A pipeline generates cohesive images by integrating multiple diffusion processes, each focused on a specific image region and considering boundary effects for smooth blending | [Stable Diffusion Mixture Tiling Pipeline SDXL](#stable-diffusion-mixture-tiling-pipeline-sdxl) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/elismasilva/mixture-of-diffusers-sdxl-tiling) | [Eliseu Silva](https://github.com/DEVAIEXP/) |
56
+ | Stable Diffusion MoD ControlNet Tile SR Pipeline SDXL | This is an advanced pipeline that leverages ControlNet Tile and Mixture-of-Diffusers techniques, integrating tile diffusion directly into the latent space denoising process. Designed to overcome the limitations of conventional pixel-space tile processing, this pipeline delivers Super Resolution (SR) upscaling for higher-quality images, reduced processing time, and greater adaptability. | [Stable Diffusion MoD ControlNet Tile SR Pipeline SDXL](#stable-diffusion-mod-controlnet-tile-sr-pipeline-sdxl) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/elismasilva/mod-control-tile-upscaler-sdxl) | [Eliseu Silva](https://github.com/DEVAIEXP/) |
57
  | FABRIC - Stable Diffusion with feedback Pipeline | pipeline supports feedback from liked and disliked images | [Stable Diffusion Fabric Pipeline](#stable-diffusion-fabric-pipeline) | [Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/stable_diffusion_fabric.ipynb)| [Shauray Singh](https://shauray8.github.io/about_shauray/) |
58
  | sketch inpaint - Inpainting with non-inpaint Stable Diffusion | sketch inpaint much like in automatic1111 | [Masked Im2Im Stable Diffusion Pipeline](#stable-diffusion-masked-im2im) | - | [Anatoly Belikov](https://github.com/noskill) |
59
  | sketch inpaint xl - Inpainting with non-inpaint Stable Diffusion | sketch inpaint much like in automatic1111 | [Masked Im2Im Stable Diffusion XL Pipeline](#stable-diffusion-xl-masked-im2im) | - | [Anatoly Belikov](https://github.com/noskill) |
 
2631
 
2632
  ![mixture_tiling_results](https://huggingface.co/datasets/elismasilva/results/resolve/main/mixture_of_diffusers_sdxl_1.png)
2633
 
2634
+ ### Stable Diffusion MoD ControlNet Tile SR Pipeline SDXL
2635
+
2636
+ This pipeline implements the [MoD (Mixture-of-Diffusers)]("https://arxiv.org/pdf/2408.06072") tiled diffusion technique and combines it with SDXL's ControlNet Tile process to generate SR images.
2637
+
2638
+ This works better with 4x scales, but you can try adjusts parameters to higher scales.
2639
+
2640
+ ````python
2641
+ import torch
2642
+ from diffusers import DiffusionPipeline, ControlNetUnionModel, AutoencoderKL, UniPCMultistepScheduler, UNet2DConditionModel
2643
+ from diffusers.utils import load_image
2644
+ from PIL import Image
2645
+
2646
+ device = "cuda"
2647
+
2648
+ # Initialize the models and pipeline
2649
+ controlnet = ControlNetUnionModel.from_pretrained(
2650
+ "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
2651
+ ).to(device=device)
2652
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16).to(device=device)
2653
+
2654
+ model_id = "SG161222/RealVisXL_V5.0"
2655
+ pipe = DiffusionPipeline.from_pretrained(
2656
+ model_id,
2657
+ torch_dtype=torch.float16,
2658
+ vae=vae,
2659
+ controlnet=controlnet,
2660
+ custom_pipeline="mod_controlnet_tile_sr_sdxl",
2661
+ use_safetensors=True,
2662
+ variant="fp16",
2663
+ ).to(device)
2664
+
2665
+ unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet", variant="fp16", use_safetensors=True)
2666
+
2667
+ #pipe.enable_model_cpu_offload() # << Enable this if you have limited VRAM
2668
+ pipe.enable_vae_tiling() # << Enable this if you have limited VRAM
2669
+ pipe.enable_vae_slicing() # << Enable this if you have limited VRAM
2670
+
2671
+ # Set selected scheduler
2672
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
2673
+
2674
+ # Load image
2675
+ control_image = load_image("https://huggingface.co/datasets/DEVAIEXP/assets/resolve/main/1.jpg")
2676
+ original_height = control_image.height
2677
+ original_width = control_image.width
2678
+ print(f"Current resolution: H:{original_height} x W:{original_width}")
2679
+
2680
+ # Pre-upscale image for tiling
2681
+ resolution = 4096
2682
+ tile_gaussian_sigma = 0.3
2683
+ max_tile_size = 1024 # or 1280
2684
+
2685
+ current_size = max(control_image.size)
2686
+ scale_factor = max(2, resolution / current_size)
2687
+ new_size = (int(control_image.width * scale_factor), int(control_image.height * scale_factor))
2688
+ image = control_image.resize(new_size, Image.LANCZOS)
2689
+
2690
+ # Update target height and width
2691
+ target_height = image.height
2692
+ target_width = image.width
2693
+ print(f"Target resolution: H:{target_height} x W:{target_width}")
2694
+
2695
+ # Calculate overlap size
2696
+ normal_tile_overlap, border_tile_overlap = pipe.calculate_overlap(target_width, target_height)
2697
+
2698
+ # Set other params
2699
+ tile_weighting_method = pipe.TileWeightingMethod.COSINE.value
2700
+ guidance_scale = 4
2701
+ num_inference_steps = 35
2702
+ denoising_strenght = 0.65
2703
+ controlnet_strength = 1.0
2704
+ prompt = "high-quality, noise-free edges, high quality, 4k, hd, 8k"
2705
+ negative_prompt = "blurry, pixelated, noisy, low resolution, artifacts, poor details"
2706
+
2707
+ # Image generation
2708
+ generated_image = pipe(
2709
+ image=image,
2710
+ control_image=control_image,
2711
+ control_mode=[6],
2712
+ controlnet_conditioning_scale=float(controlnet_strength),
2713
+ prompt=prompt,
2714
+ negative_prompt=negative_prompt,
2715
+ normal_tile_overlap=normal_tile_overlap,
2716
+ border_tile_overlap=border_tile_overlap,
2717
+ height=target_height,
2718
+ width=target_width,
2719
+ original_size=(original_width, original_height),
2720
+ target_size=(target_width, target_height),
2721
+ guidance_scale=guidance_scale,
2722
+ strength=float(denoising_strenght),
2723
+ tile_weighting_method=tile_weighting_method,
2724
+ max_tile_size=max_tile_size,
2725
+ tile_gaussian_sigma=float(tile_gaussian_sigma),
2726
+ num_inference_steps=num_inference_steps,
2727
+ )["images"][0]
2728
+ ````
2729
+ ![Upscaled](https://huggingface.co/datasets/DEVAIEXP/assets/resolve/main/1_input_4x.png)
2730
+
2731
  ### TensorRT Inpainting Stable Diffusion Pipeline
2732
 
2733
  The TensorRT Pipeline can be used to accelerate the Inpainting Stable Diffusion Inference run.
main/mod_controlnet_tile_sr_sdxl.py ADDED
@@ -0,0 +1,1862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The DEVAIEXP Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from enum import Enum
17
+ from typing import Any, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from PIL import Image
23
+ from transformers import (
24
+ CLIPTextModel,
25
+ CLIPTextModelWithProjection,
26
+ CLIPTokenizer,
27
+ )
28
+
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.loaders import (
31
+ FromSingleFileMixin,
32
+ StableDiffusionXLLoraLoaderMixin,
33
+ TextualInversionLoaderMixin,
34
+ )
35
+ from diffusers.models import (
36
+ AutoencoderKL,
37
+ ControlNetModel,
38
+ ControlNetUnionModel,
39
+ MultiControlNetModel,
40
+ UNet2DConditionModel,
41
+ )
42
+ from diffusers.models.attention_processor import (
43
+ AttnProcessor2_0,
44
+ XFormersAttnProcessor,
45
+ )
46
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
47
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
48
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
49
+ from diffusers.schedulers import KarrasDiffusionSchedulers, LMSDiscreteScheduler
50
+ from diffusers.utils import (
51
+ USE_PEFT_BACKEND,
52
+ logging,
53
+ replace_example_docstring,
54
+ scale_lora_layers,
55
+ unscale_lora_layers,
56
+ )
57
+ from diffusers.utils.import_utils import is_invisible_watermark_available
58
+ from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
59
+
60
+
61
+ if is_invisible_watermark_available():
62
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
63
+
64
+ from diffusers.utils import is_torch_xla_available
65
+
66
+
67
+ if is_torch_xla_available():
68
+ import torch_xla.core.xla_model as xm
69
+
70
+ XLA_AVAILABLE = True
71
+ else:
72
+ XLA_AVAILABLE = False
73
+
74
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
75
+
76
+
77
+ EXAMPLE_DOC_STRING = """
78
+ Examples:
79
+ ```py
80
+ import torch
81
+ from diffusers import DiffusionPipeline, ControlNetUnionModel, AutoencoderKL, UniPCMultistepScheduler
82
+ from diffusers.utils import load_image
83
+ from PIL import Image
84
+
85
+ device = "cuda"
86
+
87
+ # Initialize the models and pipeline
88
+ controlnet = ControlNetUnionModel.from_pretrained(
89
+ "brad-twinkl/controlnet-union-sdxl-1.0-promax", torch_dtype=torch.float16
90
+ ).to(device=device)
91
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16).to(device=device)
92
+
93
+ model_id = "SG161222/RealVisXL_V5.0"
94
+ pipe = StableDiffusionXLControlNetTileSRPipeline.from_pretrained(
95
+ model_id, controlnet=controlnet, vae=vae, torch_dtype=torch.float16, use_safetensors=True, variant="fp16"
96
+ ).to(device)
97
+
98
+ pipe.enable_model_cpu_offload() # << Enable this if you have limited VRAM
99
+ pipe.enable_vae_tiling() # << Enable this if you have limited VRAM
100
+ pipe.enable_vae_slicing() # << Enable this if you have limited VRAM
101
+
102
+ # Set selected scheduler
103
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
104
+
105
+ # Load image
106
+ control_image = load_image("https://huggingface.co/datasets/DEVAIEXP/assets/resolve/main/1.jpg")
107
+ original_height = control_image.height
108
+ original_width = control_image.width
109
+ print(f"Current resolution: H:{original_height} x W:{original_width}")
110
+
111
+ # Pre-upscale image for tiling
112
+ resolution = 4096
113
+ tile_gaussian_sigma = 0.3
114
+ max_tile_size = 1024 # or 1280
115
+
116
+ current_size = max(control_image.size)
117
+ scale_factor = max(2, resolution / current_size)
118
+ new_size = (int(control_image.width * scale_factor), int(control_image.height * scale_factor))
119
+ image = control_image.resize(new_size, Image.LANCZOS)
120
+
121
+ # Update target height and width
122
+ target_height = image.height
123
+ target_width = image.width
124
+ print(f"Target resolution: H:{target_height} x W:{target_width}")
125
+
126
+ # Calculate overlap size
127
+ normal_tile_overlap, border_tile_overlap = calculate_overlap(target_width, target_height)
128
+
129
+ # Set other params
130
+ tile_weighting_method = TileWeightingMethod.COSINE.value
131
+ guidance_scale = 4
132
+ num_inference_steps = 35
133
+ denoising_strenght = 0.65
134
+ controlnet_strength = 1.0
135
+ prompt = "high-quality, noise-free edges, high quality, 4k, hd, 8k"
136
+ negative_prompt = "blurry, pixelated, noisy, low resolution, artifacts, poor details"
137
+
138
+ # Image generation
139
+ control_image = pipe(
140
+ image=image,
141
+ control_image=control_image,
142
+ control_mode=[6],
143
+ controlnet_conditioning_scale=float(controlnet_strength),
144
+ prompt=prompt,
145
+ negative_prompt=negative_prompt,
146
+ normal_tile_overlap=normal_tile_overlap,
147
+ border_tile_overlap=border_tile_overlap,
148
+ height=target_height,
149
+ width=target_width,
150
+ original_size=(original_width, original_height),
151
+ target_size=(target_width, target_height),
152
+ guidance_scale=guidance_scale,
153
+ strength=float(denoising_strenght),
154
+ tile_weighting_method=tile_weighting_method,
155
+ max_tile_size=max_tile_size,
156
+ tile_gaussian_sigma=float(tile_gaussian_sigma),
157
+ num_inference_steps=num_inference_steps,
158
+ )["images"][0]
159
+ ```
160
+ """
161
+
162
+
163
+ # This function was copied and adapted from https://huggingface.co/spaces/gokaygokay/TileUpscalerV2, licensed under Apache 2.0.
164
+ def _adaptive_tile_size(image_size, base_tile_size=512, max_tile_size=1280):
165
+ """
166
+ Calculate the adaptive tile size based on the image dimensions, ensuring the tile
167
+ respects the aspect ratio and stays within the specified size limits.
168
+ """
169
+ width, height = image_size
170
+ aspect_ratio = width / height
171
+
172
+ if aspect_ratio > 1:
173
+ # Landscape orientation
174
+ tile_width = min(width, max_tile_size)
175
+ tile_height = min(int(tile_width / aspect_ratio), max_tile_size)
176
+ else:
177
+ # Portrait or square orientation
178
+ tile_height = min(height, max_tile_size)
179
+ tile_width = min(int(tile_height * aspect_ratio), max_tile_size)
180
+
181
+ # Ensure the tile size is not smaller than the base_tile_size
182
+ tile_width = max(tile_width, base_tile_size)
183
+ tile_height = max(tile_height, base_tile_size)
184
+
185
+ return tile_width, tile_height
186
+
187
+
188
+ # Copied and adapted from https://github.com/huggingface/diffusers/blob/main/examples/community/mixture_tiling.py
189
+ def _tile2pixel_indices(
190
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, image_width, image_height
191
+ ):
192
+ """Given a tile row and column numbers returns the range of pixels affected by that tiles in the overall image
193
+
194
+ Returns a tuple with:
195
+ - Starting coordinates of rows in pixel space
196
+ - Ending coordinates of rows in pixel space
197
+ - Starting coordinates of columns in pixel space
198
+ - Ending coordinates of columns in pixel space
199
+ """
200
+ # Calculate initial indices
201
+ px_row_init = 0 if tile_row == 0 else tile_row * (tile_height - tile_row_overlap)
202
+ px_col_init = 0 if tile_col == 0 else tile_col * (tile_width - tile_col_overlap)
203
+
204
+ # Calculate end indices
205
+ px_row_end = px_row_init + tile_height
206
+ px_col_end = px_col_init + tile_width
207
+
208
+ # Ensure the last tile does not exceed the image dimensions
209
+ px_row_end = min(px_row_end, image_height)
210
+ px_col_end = min(px_col_end, image_width)
211
+
212
+ return px_row_init, px_row_end, px_col_init, px_col_end
213
+
214
+
215
+ # Copied and adapted from https://github.com/huggingface/diffusers/blob/main/examples/community/mixture_tiling.py
216
+ def _tile2latent_indices(
217
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, image_width, image_height
218
+ ):
219
+ """Given a tile row and column numbers returns the range of latents affected by that tiles in the overall image
220
+
221
+ Returns a tuple with:
222
+ - Starting coordinates of rows in latent space
223
+ - Ending coordinates of rows in latent space
224
+ - Starting coordinates of columns in latent space
225
+ - Ending coordinates of columns in latent space
226
+ """
227
+ # Get pixel indices
228
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2pixel_indices(
229
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, image_width, image_height
230
+ )
231
+
232
+ # Convert to latent space
233
+ latent_row_init = px_row_init // 8
234
+ latent_row_end = px_row_end // 8
235
+ latent_col_init = px_col_init // 8
236
+ latent_col_end = px_col_end // 8
237
+ latent_height = image_height // 8
238
+ latent_width = image_width // 8
239
+
240
+ # Ensure the last tile does not exceed the latent dimensions
241
+ latent_row_end = min(latent_row_end, latent_height)
242
+ latent_col_end = min(latent_col_end, latent_width)
243
+
244
+ return latent_row_init, latent_row_end, latent_col_init, latent_col_end
245
+
246
+
247
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
248
+ def retrieve_latents(
249
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
250
+ ):
251
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
252
+ return encoder_output.latent_dist.sample(generator)
253
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
254
+ return encoder_output.latent_dist.mode()
255
+ elif hasattr(encoder_output, "latents"):
256
+ return encoder_output.latents
257
+ else:
258
+ raise AttributeError("Could not access latents of provided encoder_output")
259
+
260
+
261
+ class StableDiffusionXLControlNetTileSRPipeline(
262
+ DiffusionPipeline,
263
+ StableDiffusionMixin,
264
+ TextualInversionLoaderMixin,
265
+ StableDiffusionXLLoraLoaderMixin,
266
+ FromSingleFileMixin,
267
+ ):
268
+ r"""
269
+ Pipeline for image-to-image generation using Stable Diffusion XL with ControlNet guidance.
270
+
271
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
272
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
273
+
274
+ The pipeline also inherits the following loading methods:
275
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
276
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
277
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
278
+
279
+ Args:
280
+ vae ([`AutoencoderKL`]):
281
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
282
+ text_encoder ([`CLIPTextModel`]):
283
+ Frozen text-encoder. Stable Diffusion uses the text portion of
284
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
285
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
286
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
287
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
288
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
289
+ specifically the
290
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
291
+ variant.
292
+ tokenizer (`CLIPTokenizer`):
293
+ Tokenizer of class
294
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
295
+ tokenizer_2 (`CLIPTokenizer`):
296
+ Second Tokenizer of class
297
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
298
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
299
+ controlnet ([`ControlNetUnionModel`]):
300
+ Provides additional conditioning to the unet during the denoising process.
301
+ scheduler ([`SchedulerMixin`]):
302
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
303
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
304
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
305
+ Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
306
+ config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
307
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
308
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
309
+ `stabilityai/stable-diffusion-xl-base-1-0`.
310
+ add_watermarker (`bool`, *optional*):
311
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
312
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
313
+ watermarker will be used.
314
+ """
315
+
316
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
317
+ _optional_components = [
318
+ "tokenizer",
319
+ "tokenizer_2",
320
+ "text_encoder",
321
+ "text_encoder_2",
322
+ ]
323
+
324
+ def __init__(
325
+ self,
326
+ vae: AutoencoderKL,
327
+ text_encoder: CLIPTextModel,
328
+ text_encoder_2: CLIPTextModelWithProjection,
329
+ tokenizer: CLIPTokenizer,
330
+ tokenizer_2: CLIPTokenizer,
331
+ unet: UNet2DConditionModel,
332
+ controlnet: ControlNetUnionModel,
333
+ scheduler: KarrasDiffusionSchedulers,
334
+ requires_aesthetics_score: bool = False,
335
+ force_zeros_for_empty_prompt: bool = True,
336
+ add_watermarker: Optional[bool] = None,
337
+ ):
338
+ super().__init__()
339
+
340
+ if not isinstance(controlnet, ControlNetUnionModel):
341
+ raise ValueError("Expected `controlnet` to be of type `ControlNetUnionModel`.")
342
+
343
+ self.register_modules(
344
+ vae=vae,
345
+ text_encoder=text_encoder,
346
+ text_encoder_2=text_encoder_2,
347
+ tokenizer=tokenizer,
348
+ tokenizer_2=tokenizer_2,
349
+ unet=unet,
350
+ controlnet=controlnet,
351
+ scheduler=scheduler,
352
+ )
353
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
354
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
355
+ self.control_image_processor = VaeImageProcessor(
356
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
357
+ )
358
+ self.mask_processor = VaeImageProcessor(
359
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True
360
+ )
361
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
362
+
363
+ if add_watermarker:
364
+ self.watermark = StableDiffusionXLWatermarker()
365
+ else:
366
+ self.watermark = None
367
+
368
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
369
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
370
+
371
+ def calculate_overlap(self, width, height, base_overlap=128):
372
+ """
373
+ Calculates dynamic overlap based on the image's aspect ratio.
374
+
375
+ Args:
376
+ width (int): Width of the image in pixels.
377
+ height (int): Height of the image in pixels.
378
+ base_overlap (int, optional): Base overlap value in pixels. Defaults to 128.
379
+
380
+ Returns:
381
+ tuple: A tuple containing:
382
+ - row_overlap (int): Overlap between tiles in consecutive rows.
383
+ - col_overlap (int): Overlap between tiles in consecutive columns.
384
+ """
385
+ ratio = height / width
386
+ if ratio < 1: # Image is wider than tall
387
+ return base_overlap // 2, base_overlap
388
+ else: # Image is taller than wide
389
+ return base_overlap, base_overlap * 2
390
+
391
+ class TileWeightingMethod(Enum):
392
+ """Mode in which the tile weights will be generated"""
393
+
394
+ COSINE = "Cosine"
395
+ GAUSSIAN = "Gaussian"
396
+
397
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
398
+ def encode_prompt(
399
+ self,
400
+ prompt: str,
401
+ prompt_2: Optional[str] = None,
402
+ device: Optional[torch.device] = None,
403
+ num_images_per_prompt: int = 1,
404
+ do_classifier_free_guidance: bool = True,
405
+ negative_prompt: Optional[str] = None,
406
+ negative_prompt_2: Optional[str] = None,
407
+ prompt_embeds: Optional[torch.Tensor] = None,
408
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
409
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
410
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
411
+ lora_scale: Optional[float] = None,
412
+ clip_skip: Optional[int] = None,
413
+ ):
414
+ r"""
415
+ Encodes the prompt into text encoder hidden states.
416
+
417
+ Args:
418
+ prompt (`str` or `List[str]`, *optional*):
419
+ prompt to be encoded
420
+ prompt_2 (`str` or `List[str]`, *optional*):
421
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
422
+ used in both text-encoders
423
+ device: (`torch.device`):
424
+ torch device
425
+ num_images_per_prompt (`int`):
426
+ number of images that should be generated per prompt
427
+ do_classifier_free_guidance (`bool`):
428
+ whether to use classifier free guidance or not
429
+ negative_prompt (`str` or `List[str]`, *optional*):
430
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
431
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
432
+ less than `1`).
433
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
434
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
435
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
436
+ prompt_embeds (`torch.Tensor`, *optional*):
437
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
438
+ provided, text embeddings will be generated from `prompt` input argument.
439
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
440
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
441
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
442
+ argument.
443
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
444
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
445
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
446
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
447
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
448
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
449
+ input argument.
450
+ lora_scale (`float`, *optional*):
451
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
452
+ clip_skip (`int`, *optional*):
453
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
454
+ the output of the pre-final layer will be used for computing the prompt embeddings.
455
+ """
456
+ device = device or self._execution_device
457
+
458
+ # set lora scale so that monkey patched LoRA
459
+ # function of text encoder can correctly access it
460
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
461
+ self._lora_scale = lora_scale
462
+
463
+ # dynamically adjust the LoRA scale
464
+ if self.text_encoder is not None:
465
+ if not USE_PEFT_BACKEND:
466
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
467
+ else:
468
+ scale_lora_layers(self.text_encoder, lora_scale)
469
+
470
+ if self.text_encoder_2 is not None:
471
+ if not USE_PEFT_BACKEND:
472
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
473
+ else:
474
+ scale_lora_layers(self.text_encoder_2, lora_scale)
475
+
476
+ prompt = [prompt] if isinstance(prompt, str) else prompt
477
+
478
+ if prompt is not None:
479
+ batch_size = len(prompt)
480
+ else:
481
+ batch_size = prompt_embeds.shape[0]
482
+
483
+ # Define tokenizers and text encoders
484
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
485
+ text_encoders = (
486
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
487
+ )
488
+ dtype = text_encoders[0].dtype
489
+ if prompt_embeds is None:
490
+ prompt_2 = prompt_2 or prompt
491
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
492
+
493
+ # textual inversion: process multi-vector tokens if necessary
494
+ prompt_embeds_list = []
495
+ prompts = [prompt, prompt_2]
496
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
497
+ if isinstance(self, TextualInversionLoaderMixin):
498
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
499
+
500
+ text_inputs = tokenizer(
501
+ prompt,
502
+ padding="max_length",
503
+ max_length=tokenizer.model_max_length,
504
+ truncation=True,
505
+ return_tensors="pt",
506
+ )
507
+
508
+ text_input_ids = text_inputs.input_ids
509
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
510
+
511
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
512
+ text_input_ids, untruncated_ids
513
+ ):
514
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
515
+ logger.warning(
516
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
517
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
518
+ )
519
+ text_encoder.to(dtype)
520
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
521
+
522
+ # We are only ALWAYS interested in the pooled output of the final text encoder
523
+ if pooled_prompt_embeds is None and prompt_embeds[0].ndim == 2:
524
+ pooled_prompt_embeds = prompt_embeds[0]
525
+
526
+ if clip_skip is None:
527
+ prompt_embeds = prompt_embeds.hidden_states[-2]
528
+ else:
529
+ # "2" because SDXL always indexes from the penultimate layer.
530
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
531
+
532
+ prompt_embeds_list.append(prompt_embeds)
533
+
534
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
535
+
536
+ # get unconditional embeddings for classifier free guidance
537
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
538
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
539
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
540
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
541
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
542
+ negative_prompt = negative_prompt or ""
543
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
544
+
545
+ # normalize str to list
546
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
547
+ negative_prompt_2 = (
548
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
549
+ )
550
+
551
+ uncond_tokens: List[str]
552
+ if prompt is not None and type(prompt) is not type(negative_prompt):
553
+ raise TypeError(
554
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
555
+ f" {type(prompt)}."
556
+ )
557
+ elif batch_size != len(negative_prompt):
558
+ raise ValueError(
559
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
560
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
561
+ " the batch size of `prompt`."
562
+ )
563
+ else:
564
+ uncond_tokens = [negative_prompt, negative_prompt_2]
565
+
566
+ negative_prompt_embeds_list = []
567
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
568
+ if isinstance(self, TextualInversionLoaderMixin):
569
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
570
+
571
+ max_length = prompt_embeds.shape[1]
572
+ uncond_input = tokenizer(
573
+ negative_prompt,
574
+ padding="max_length",
575
+ max_length=max_length,
576
+ truncation=True,
577
+ return_tensors="pt",
578
+ )
579
+
580
+ negative_prompt_embeds = text_encoder(
581
+ uncond_input.input_ids.to(device),
582
+ output_hidden_states=True,
583
+ )
584
+
585
+ # We are only ALWAYS interested in the pooled output of the final text encoder
586
+ if negative_pooled_prompt_embeds is None and negative_prompt_embeds[0].ndim == 2:
587
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
588
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
589
+
590
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
591
+
592
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
593
+
594
+ if self.text_encoder_2 is not None:
595
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
596
+ else:
597
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
598
+
599
+ bs_embed, seq_len, _ = prompt_embeds.shape
600
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
601
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
602
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
603
+
604
+ if do_classifier_free_guidance:
605
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
606
+ seq_len = negative_prompt_embeds.shape[1]
607
+
608
+ if self.text_encoder_2 is not None:
609
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
610
+ else:
611
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
612
+
613
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
614
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
615
+
616
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
617
+ bs_embed * num_images_per_prompt, -1
618
+ )
619
+ if do_classifier_free_guidance:
620
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
621
+ bs_embed * num_images_per_prompt, -1
622
+ )
623
+
624
+ if self.text_encoder is not None:
625
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
626
+ # Retrieve the original scale by scaling back the LoRA layers
627
+ unscale_lora_layers(self.text_encoder, lora_scale)
628
+
629
+ if self.text_encoder_2 is not None:
630
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
631
+ # Retrieve the original scale by scaling back the LoRA layers
632
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
633
+
634
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
635
+
636
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
637
+ def prepare_extra_step_kwargs(self, generator, eta):
638
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
639
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
640
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
641
+ # and should be between [0, 1]
642
+
643
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
644
+ extra_step_kwargs = {}
645
+ if accepts_eta:
646
+ extra_step_kwargs["eta"] = eta
647
+
648
+ # check if the scheduler accepts generator
649
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
650
+ if accepts_generator:
651
+ extra_step_kwargs["generator"] = generator
652
+ return extra_step_kwargs
653
+
654
+ def check_inputs(
655
+ self,
656
+ prompt,
657
+ height,
658
+ width,
659
+ image,
660
+ strength,
661
+ num_inference_steps,
662
+ normal_tile_overlap,
663
+ border_tile_overlap,
664
+ max_tile_size,
665
+ tile_gaussian_sigma,
666
+ tile_weighting_method,
667
+ controlnet_conditioning_scale=1.0,
668
+ control_guidance_start=0.0,
669
+ control_guidance_end=1.0,
670
+ ):
671
+ if height % 8 != 0 or width % 8 != 0:
672
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
673
+
674
+ if prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
675
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
676
+
677
+ if strength < 0 or strength > 1:
678
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
679
+ if num_inference_steps is None:
680
+ raise ValueError("`num_inference_steps` cannot be None.")
681
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
682
+ raise ValueError(
683
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
684
+ f" {type(num_inference_steps)}."
685
+ )
686
+ if normal_tile_overlap is None:
687
+ raise ValueError("`normal_tile_overlap` cannot be None.")
688
+ elif not isinstance(normal_tile_overlap, int) or normal_tile_overlap < 64:
689
+ raise ValueError(
690
+ f"`normal_tile_overlap` has to be greater than 64 but is {normal_tile_overlap} of type"
691
+ f" {type(normal_tile_overlap)}."
692
+ )
693
+ if border_tile_overlap is None:
694
+ raise ValueError("`border_tile_overlap` cannot be None.")
695
+ elif not isinstance(border_tile_overlap, int) or border_tile_overlap < 128:
696
+ raise ValueError(
697
+ f"`border_tile_overlap` has to be greater than 128 but is {border_tile_overlap} of type"
698
+ f" {type(border_tile_overlap)}."
699
+ )
700
+ if max_tile_size is None:
701
+ raise ValueError("`max_tile_size` cannot be None.")
702
+ elif not isinstance(max_tile_size, int) or max_tile_size not in (1024, 1280):
703
+ raise ValueError(
704
+ f"`max_tile_size` has to be in 1024 or 1280 but is {max_tile_size} of type" f" {type(max_tile_size)}."
705
+ )
706
+ if tile_gaussian_sigma is None:
707
+ raise ValueError("`tile_gaussian_sigma` cannot be None.")
708
+ elif not isinstance(tile_gaussian_sigma, float) or tile_gaussian_sigma <= 0:
709
+ raise ValueError(
710
+ f"`tile_gaussian_sigma` has to be a positive float but is {tile_gaussian_sigma} of type"
711
+ f" {type(tile_gaussian_sigma)}."
712
+ )
713
+ if tile_weighting_method is None:
714
+ raise ValueError("`tile_weighting_method` cannot be None.")
715
+ elif not isinstance(tile_weighting_method, str) or tile_weighting_method not in [
716
+ t.value for t in self.TileWeightingMethod
717
+ ]:
718
+ raise ValueError(
719
+ f"`tile_weighting_method` has to be a string in ({[t.value for t in self.TileWeightingMethod]}) but is {tile_weighting_method} of type"
720
+ f" {type(tile_weighting_method)}."
721
+ )
722
+
723
+ # Check `image`
724
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
725
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
726
+ )
727
+ if (
728
+ isinstance(self.controlnet, ControlNetModel)
729
+ or is_compiled
730
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
731
+ ):
732
+ self.check_image(image, prompt)
733
+ elif (
734
+ isinstance(self.controlnet, ControlNetUnionModel)
735
+ or is_compiled
736
+ and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
737
+ ):
738
+ self.check_image(image, prompt)
739
+ else:
740
+ assert False
741
+
742
+ # Check `controlnet_conditioning_scale`
743
+ if (
744
+ isinstance(self.controlnet, ControlNetUnionModel)
745
+ or is_compiled
746
+ and isinstance(self.controlnet._orig_mod, ControlNetUnionModel)
747
+ ) or (
748
+ isinstance(self.controlnet, MultiControlNetModel)
749
+ or is_compiled
750
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
751
+ ):
752
+ if not isinstance(controlnet_conditioning_scale, float):
753
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
754
+ elif (
755
+ isinstance(self.controlnet, MultiControlNetModel)
756
+ or is_compiled
757
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
758
+ ):
759
+ if isinstance(controlnet_conditioning_scale, list):
760
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
761
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
762
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
763
+ self.controlnet.nets
764
+ ):
765
+ raise ValueError(
766
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
767
+ " the same length as the number of controlnets"
768
+ )
769
+ else:
770
+ assert False
771
+
772
+ if not isinstance(control_guidance_start, (tuple, list)):
773
+ control_guidance_start = [control_guidance_start]
774
+
775
+ if not isinstance(control_guidance_end, (tuple, list)):
776
+ control_guidance_end = [control_guidance_end]
777
+
778
+ if len(control_guidance_start) != len(control_guidance_end):
779
+ raise ValueError(
780
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
781
+ )
782
+
783
+ for start, end in zip(control_guidance_start, control_guidance_end):
784
+ if start >= end:
785
+ raise ValueError(
786
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
787
+ )
788
+ if start < 0.0:
789
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
790
+ if end > 1.0:
791
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
792
+
793
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.check_image
794
+ def check_image(self, image, prompt):
795
+ image_is_pil = isinstance(image, Image.Image)
796
+ image_is_tensor = isinstance(image, torch.Tensor)
797
+ image_is_np = isinstance(image, np.ndarray)
798
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], Image.Image)
799
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
800
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
801
+
802
+ if (
803
+ not image_is_pil
804
+ and not image_is_tensor
805
+ and not image_is_np
806
+ and not image_is_pil_list
807
+ and not image_is_tensor_list
808
+ and not image_is_np_list
809
+ ):
810
+ raise TypeError(
811
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
812
+ )
813
+
814
+ if image_is_pil:
815
+ image_batch_size = 1
816
+ else:
817
+ image_batch_size = len(image)
818
+
819
+ if prompt is not None and isinstance(prompt, str):
820
+ prompt_batch_size = 1
821
+ elif prompt is not None and isinstance(prompt, list):
822
+ prompt_batch_size = len(prompt)
823
+
824
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
825
+ raise ValueError(
826
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
827
+ )
828
+
829
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.prepare_image
830
+ def prepare_control_image(
831
+ self,
832
+ image,
833
+ width,
834
+ height,
835
+ batch_size,
836
+ num_images_per_prompt,
837
+ device,
838
+ dtype,
839
+ do_classifier_free_guidance=False,
840
+ guess_mode=False,
841
+ ):
842
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
843
+ image_batch_size = image.shape[0]
844
+
845
+ if image_batch_size == 1:
846
+ repeat_by = batch_size
847
+ else:
848
+ # image batch size is the same as prompt batch size
849
+ repeat_by = num_images_per_prompt
850
+
851
+ image = image.repeat_interleave(repeat_by, dim=0)
852
+
853
+ image = image.to(device=device, dtype=dtype)
854
+
855
+ if do_classifier_free_guidance and not guess_mode:
856
+ image = torch.cat([image] * 2)
857
+
858
+ return image
859
+
860
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
861
+ def get_timesteps(self, num_inference_steps, strength):
862
+ # get the original timestep using init_timestep
863
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
864
+
865
+ t_start = max(num_inference_steps - init_timestep, 0)
866
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
867
+ if hasattr(self.scheduler, "set_begin_index"):
868
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
869
+
870
+ return timesteps, num_inference_steps - t_start
871
+
872
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.prepare_latents
873
+ def prepare_latents(
874
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
875
+ ):
876
+ if not isinstance(image, (torch.Tensor, Image.Image, list)):
877
+ raise ValueError(
878
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
879
+ )
880
+
881
+ latents_mean = latents_std = None
882
+ if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
883
+ latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
884
+ if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
885
+ latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
886
+
887
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
888
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
889
+ self.text_encoder_2.to("cpu")
890
+ torch.cuda.empty_cache()
891
+
892
+ image = image.to(device=device, dtype=dtype)
893
+
894
+ batch_size = batch_size * num_images_per_prompt
895
+
896
+ if image.shape[1] == 4:
897
+ init_latents = image
898
+
899
+ else:
900
+ # make sure the VAE is in float32 mode, as it overflows in float16
901
+ if self.vae.config.force_upcast:
902
+ image = image.float()
903
+ self.vae.to(dtype=torch.float32)
904
+
905
+ if isinstance(generator, list) and len(generator) != batch_size:
906
+ raise ValueError(
907
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
908
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
909
+ )
910
+
911
+ elif isinstance(generator, list):
912
+ if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
913
+ image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
914
+ elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
915
+ raise ValueError(
916
+ f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
917
+ )
918
+
919
+ init_latents = [
920
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
921
+ for i in range(batch_size)
922
+ ]
923
+ init_latents = torch.cat(init_latents, dim=0)
924
+ else:
925
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
926
+
927
+ if self.vae.config.force_upcast:
928
+ self.vae.to(dtype)
929
+
930
+ init_latents = init_latents.to(dtype)
931
+ if latents_mean is not None and latents_std is not None:
932
+ latents_mean = latents_mean.to(device=device, dtype=dtype)
933
+ latents_std = latents_std.to(device=device, dtype=dtype)
934
+ init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
935
+ else:
936
+ init_latents = self.vae.config.scaling_factor * init_latents
937
+
938
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
939
+ # expand init_latents for batch_size
940
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
941
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
942
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
943
+ raise ValueError(
944
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
945
+ )
946
+ else:
947
+ init_latents = torch.cat([init_latents], dim=0)
948
+
949
+ if add_noise:
950
+ shape = init_latents.shape
951
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
952
+ # get latents
953
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
954
+
955
+ latents = init_latents
956
+
957
+ return latents
958
+
959
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline._get_add_time_ids
960
+ def _get_add_time_ids(
961
+ self,
962
+ original_size,
963
+ crops_coords_top_left,
964
+ target_size,
965
+ aesthetic_score,
966
+ negative_aesthetic_score,
967
+ negative_original_size,
968
+ negative_crops_coords_top_left,
969
+ negative_target_size,
970
+ dtype,
971
+ text_encoder_projection_dim=None,
972
+ ):
973
+ if self.config.requires_aesthetics_score:
974
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
975
+ add_neg_time_ids = list(
976
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
977
+ )
978
+ else:
979
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
980
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
981
+
982
+ passed_add_embed_dim = (
983
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
984
+ )
985
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
986
+
987
+ if (
988
+ expected_add_embed_dim > passed_add_embed_dim
989
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
990
+ ):
991
+ raise ValueError(
992
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
993
+ )
994
+ elif (
995
+ expected_add_embed_dim < passed_add_embed_dim
996
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
997
+ ):
998
+ raise ValueError(
999
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
1000
+ )
1001
+ elif expected_add_embed_dim != passed_add_embed_dim:
1002
+ raise ValueError(
1003
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
1004
+ )
1005
+
1006
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
1007
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
1008
+
1009
+ return add_time_ids, add_neg_time_ids
1010
+
1011
+ def _generate_cosine_weights(self, tile_width, tile_height, nbatches, device, dtype):
1012
+ """
1013
+ Generates cosine weights as a PyTorch tensor for blending tiles.
1014
+
1015
+ Args:
1016
+ tile_width (int): Width of the tile in pixels.
1017
+ tile_height (int): Height of the tile in pixels.
1018
+ nbatches (int): Number of batches.
1019
+ device (torch.device): Device where the tensor will be allocated (e.g., 'cuda' or 'cpu').
1020
+ dtype (torch.dtype): Data type of the tensor (e.g., torch.float32).
1021
+
1022
+ Returns:
1023
+ torch.Tensor: A tensor containing cosine weights for blending tiles, expanded to match batch and channel dimensions.
1024
+ """
1025
+ # Convert tile dimensions to latent space
1026
+ latent_width = tile_width // 8
1027
+ latent_height = tile_height // 8
1028
+
1029
+ # Generate x and y coordinates in latent space
1030
+ x = np.arange(0, latent_width)
1031
+ y = np.arange(0, latent_height)
1032
+
1033
+ # Calculate midpoints
1034
+ midpoint_x = (latent_width - 1) / 2
1035
+ midpoint_y = (latent_height - 1) / 2
1036
+
1037
+ # Compute cosine probabilities for x and y
1038
+ x_probs = np.cos(np.pi * (x - midpoint_x) / latent_width)
1039
+ y_probs = np.cos(np.pi * (y - midpoint_y) / latent_height)
1040
+
1041
+ # Create a 2D weight matrix using the outer product
1042
+ weights_np = np.outer(y_probs, x_probs)
1043
+
1044
+ # Convert to a PyTorch tensor with the correct device and dtype
1045
+ weights_torch = torch.tensor(weights_np, device=device, dtype=dtype)
1046
+
1047
+ # Expand for batch and channel dimensions
1048
+ tile_weights_expanded = torch.tile(weights_torch, (nbatches, self.unet.config.in_channels, 1, 1))
1049
+
1050
+ return tile_weights_expanded
1051
+
1052
+ def _generate_gaussian_weights(self, tile_width, tile_height, nbatches, device, dtype, sigma=0.05):
1053
+ """
1054
+ Generates Gaussian weights as a PyTorch tensor for blending tiles in latent space.
1055
+
1056
+ Args:
1057
+ tile_width (int): Width of the tile in pixels.
1058
+ tile_height (int): Height of the tile in pixels.
1059
+ nbatches (int): Number of batches.
1060
+ device (torch.device): Device where the tensor will be allocated (e.g., 'cuda' or 'cpu').
1061
+ dtype (torch.dtype): Data type of the tensor (e.g., torch.float32).
1062
+ sigma (float, optional): Standard deviation of the Gaussian distribution. Controls the smoothness of the weights. Defaults to 0.05.
1063
+
1064
+ Returns:
1065
+ torch.Tensor: A tensor containing Gaussian weights for blending tiles, expanded to match batch and channel dimensions.
1066
+ """
1067
+ # Convert tile dimensions to latent space
1068
+ latent_width = tile_width // 8
1069
+ latent_height = tile_height // 8
1070
+
1071
+ # Generate Gaussian weights in latent space
1072
+ x = np.linspace(-1, 1, latent_width)
1073
+ y = np.linspace(-1, 1, latent_height)
1074
+ xx, yy = np.meshgrid(x, y)
1075
+ gaussian_weight = np.exp(-(xx**2 + yy**2) / (2 * sigma**2))
1076
+
1077
+ # Convert to a PyTorch tensor with the correct device and dtype
1078
+ weights_torch = torch.tensor(gaussian_weight, device=device, dtype=dtype)
1079
+
1080
+ # Expand for batch and channel dimensions
1081
+ weights_expanded = weights_torch.unsqueeze(0).unsqueeze(0) # Add batch and channel dimensions
1082
+ weights_expanded = weights_expanded.expand(nbatches, -1, -1, -1) # Expand to the number of batches
1083
+
1084
+ return weights_expanded
1085
+
1086
+ def _get_num_tiles(self, height, width, tile_height, tile_width, normal_tile_overlap, border_tile_overlap):
1087
+ """
1088
+ Calculates the number of tiles needed to cover an image, choosing the appropriate formula based on the
1089
+ ratio between the image size and the tile size.
1090
+
1091
+ This function automatically selects between two formulas:
1092
+ 1. A universal formula for typical cases (image-to-tile ratio <= 6:1).
1093
+ 2. A specialized formula with border tile overlap for larger or atypical cases (image-to-tile ratio > 6:1).
1094
+
1095
+ Args:
1096
+ height (int): Height of the image in pixels.
1097
+ width (int): Width of the image in pixels.
1098
+ tile_height (int): Height of each tile in pixels.
1099
+ tile_width (int): Width of each tile in pixels.
1100
+ normal_tile_overlap (int): Overlap between tiles in pixels for normal (non-border) tiles.
1101
+ border_tile_overlap (int): Overlap between tiles in pixels for border tiles.
1102
+
1103
+ Returns:
1104
+ tuple: A tuple containing:
1105
+ - grid_rows (int): Number of rows in the tile grid.
1106
+ - grid_cols (int): Number of columns in the tile grid.
1107
+
1108
+ Notes:
1109
+ - The function uses the universal formula (without border_tile_overlap) for typical cases where the
1110
+ image-to-tile ratio is 6:1 or smaller.
1111
+ - For larger or atypical cases (image-to-tile ratio > 6:1), it uses a specialized formula that includes
1112
+ border_tile_overlap to ensure complete coverage of the image, especially at the edges.
1113
+ """
1114
+ # Calculate the ratio between the image size and the tile size
1115
+ height_ratio = height / tile_height
1116
+ width_ratio = width / tile_width
1117
+
1118
+ # If the ratio is greater than 6:1, use the formula with border_tile_overlap
1119
+ if height_ratio > 6 or width_ratio > 6:
1120
+ grid_rows = int(np.ceil((height - border_tile_overlap) / (tile_height - normal_tile_overlap))) + 1
1121
+ grid_cols = int(np.ceil((width - border_tile_overlap) / (tile_width - normal_tile_overlap))) + 1
1122
+ else:
1123
+ # Otherwise, use the universal formula
1124
+ grid_rows = int(np.ceil((height - normal_tile_overlap) / (tile_height - normal_tile_overlap)))
1125
+ grid_cols = int(np.ceil((width - normal_tile_overlap) / (tile_width - normal_tile_overlap)))
1126
+
1127
+ return grid_rows, grid_cols
1128
+
1129
+ def prepare_tiles(
1130
+ self,
1131
+ grid_rows,
1132
+ grid_cols,
1133
+ tile_weighting_method,
1134
+ tile_width,
1135
+ tile_height,
1136
+ normal_tile_overlap,
1137
+ border_tile_overlap,
1138
+ width,
1139
+ height,
1140
+ tile_sigma,
1141
+ batch_size,
1142
+ device,
1143
+ dtype,
1144
+ ):
1145
+ """
1146
+ Processes image tiles by dynamically adjusting overlap and calculating Gaussian or cosine weights.
1147
+
1148
+ Args:
1149
+ grid_rows (int): Number of rows in the tile grid.
1150
+ grid_cols (int): Number of columns in the tile grid.
1151
+ tile_weighting_method (str): Method for weighting tiles. Options: "Gaussian" or "Cosine".
1152
+ tile_width (int): Width of each tile in pixels.
1153
+ tile_height (int): Height of each tile in pixels.
1154
+ normal_tile_overlap (int): Overlap between tiles in pixels for normal tiles.
1155
+ border_tile_overlap (int): Overlap between tiles in pixels for border tiles.
1156
+ width (int): Width of the image in pixels.
1157
+ height (int): Height of the image in pixels.
1158
+ tile_sigma (float): Sigma parameter for Gaussian weighting.
1159
+ batch_size (int): Batch size for weight tiles.
1160
+ device (torch.device): Device where tensors will be allocated (e.g., 'cuda' or 'cpu').
1161
+ dtype (torch.dtype): Data type of the tensors (e.g., torch.float32).
1162
+
1163
+ Returns:
1164
+ tuple: A tuple containing:
1165
+ - tile_weights (np.ndarray): Array of weights for each tile.
1166
+ - tile_row_overlaps (np.ndarray): Array of row overlaps for each tile.
1167
+ - tile_col_overlaps (np.ndarray): Array of column overlaps for each tile.
1168
+ """
1169
+
1170
+ # Create arrays to store dynamic overlaps and weights
1171
+ tile_row_overlaps = np.full((grid_rows, grid_cols), normal_tile_overlap)
1172
+ tile_col_overlaps = np.full((grid_rows, grid_cols), normal_tile_overlap)
1173
+ tile_weights = np.empty((grid_rows, grid_cols), dtype=object) # Stores Gaussian or cosine weights
1174
+
1175
+ # Iterate over tiles to adjust overlap and calculate weights
1176
+ for row in range(grid_rows):
1177
+ for col in range(grid_cols):
1178
+ # Calculate the size of the current tile
1179
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2pixel_indices(
1180
+ row, col, tile_width, tile_height, normal_tile_overlap, normal_tile_overlap, width, height
1181
+ )
1182
+ current_tile_width = px_col_end - px_col_init
1183
+ current_tile_height = px_row_end - px_row_init
1184
+ sigma = tile_sigma
1185
+
1186
+ # Adjust overlap for smaller tiles
1187
+ if current_tile_width < tile_width:
1188
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2pixel_indices(
1189
+ row, col, tile_width, tile_height, border_tile_overlap, border_tile_overlap, width, height
1190
+ )
1191
+ current_tile_width = px_col_end - px_col_init
1192
+ tile_col_overlaps[row, col] = border_tile_overlap
1193
+ sigma = tile_sigma * 1.2
1194
+ if current_tile_height < tile_height:
1195
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2pixel_indices(
1196
+ row, col, tile_width, tile_height, border_tile_overlap, border_tile_overlap, width, height
1197
+ )
1198
+ current_tile_height = px_row_end - px_row_init
1199
+ tile_row_overlaps[row, col] = border_tile_overlap
1200
+ sigma = tile_sigma * 1.2
1201
+
1202
+ # Calculate weights for the current tile
1203
+ if tile_weighting_method == self.TileWeightingMethod.COSINE.value:
1204
+ tile_weights[row, col] = self._generate_cosine_weights(
1205
+ tile_width=current_tile_width,
1206
+ tile_height=current_tile_height,
1207
+ nbatches=batch_size,
1208
+ device=device,
1209
+ dtype=torch.float32,
1210
+ )
1211
+ else:
1212
+ tile_weights[row, col] = self._generate_gaussian_weights(
1213
+ tile_width=current_tile_width,
1214
+ tile_height=current_tile_height,
1215
+ nbatches=batch_size,
1216
+ device=device,
1217
+ dtype=dtype,
1218
+ sigma=sigma,
1219
+ )
1220
+
1221
+ return tile_weights, tile_row_overlaps, tile_col_overlaps
1222
+
1223
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
1224
+ def upcast_vae(self):
1225
+ dtype = self.vae.dtype
1226
+ self.vae.to(dtype=torch.float32)
1227
+ use_torch_2_0_or_xformers = isinstance(
1228
+ self.vae.decoder.mid_block.attentions[0].processor,
1229
+ (
1230
+ AttnProcessor2_0,
1231
+ XFormersAttnProcessor,
1232
+ ),
1233
+ )
1234
+ # if xformers or torch_2_0 is used attention block does not need
1235
+ # to be in float32 which can save lots of memory
1236
+ if use_torch_2_0_or_xformers:
1237
+ self.vae.post_quant_conv.to(dtype)
1238
+ self.vae.decoder.conv_in.to(dtype)
1239
+ self.vae.decoder.mid_block.to(dtype)
1240
+
1241
+ @property
1242
+ def guidance_scale(self):
1243
+ return self._guidance_scale
1244
+
1245
+ @property
1246
+ def clip_skip(self):
1247
+ return self._clip_skip
1248
+
1249
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1250
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1251
+ # corresponds to doing no classifier free guidance.
1252
+ @property
1253
+ def do_classifier_free_guidance(self):
1254
+ return self._guidance_scale > 1
1255
+
1256
+ @property
1257
+ def cross_attention_kwargs(self):
1258
+ return self._cross_attention_kwargs
1259
+
1260
+ @property
1261
+ def num_timesteps(self):
1262
+ return self._num_timesteps
1263
+
1264
+ @property
1265
+ def interrupt(self):
1266
+ return self._interrupt
1267
+
1268
+ @torch.no_grad()
1269
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1270
+ def __call__(
1271
+ self,
1272
+ prompt: Union[str, List[str]] = None,
1273
+ image: PipelineImageInput = None,
1274
+ control_image: PipelineImageInput = None,
1275
+ height: Optional[int] = None,
1276
+ width: Optional[int] = None,
1277
+ strength: float = 0.9999,
1278
+ num_inference_steps: int = 50,
1279
+ guidance_scale: float = 5.0,
1280
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1281
+ num_images_per_prompt: Optional[int] = 1,
1282
+ eta: float = 0.0,
1283
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1284
+ latents: Optional[torch.Tensor] = None,
1285
+ output_type: Optional[str] = "pil",
1286
+ return_dict: bool = True,
1287
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1288
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
1289
+ guess_mode: bool = False,
1290
+ control_guidance_start: Union[float, List[float]] = 0.0,
1291
+ control_guidance_end: Union[float, List[float]] = 1.0,
1292
+ control_mode: Optional[Union[int, List[int]]] = None,
1293
+ original_size: Tuple[int, int] = None,
1294
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1295
+ target_size: Tuple[int, int] = None,
1296
+ negative_original_size: Optional[Tuple[int, int]] = None,
1297
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1298
+ negative_target_size: Optional[Tuple[int, int]] = None,
1299
+ aesthetic_score: float = 6.0,
1300
+ negative_aesthetic_score: float = 2.5,
1301
+ clip_skip: Optional[int] = None,
1302
+ normal_tile_overlap: int = 64,
1303
+ border_tile_overlap: int = 128,
1304
+ max_tile_size: int = 1024,
1305
+ tile_gaussian_sigma: float = 0.05,
1306
+ tile_weighting_method: str = "Cosine",
1307
+ **kwargs,
1308
+ ):
1309
+ r"""
1310
+ Function invoked when calling the pipeline for generation.
1311
+
1312
+ Args:
1313
+ prompt (`str` or `List[str]`, *optional*):
1314
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1315
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`, *optional*):
1316
+ The initial image to be used as the starting point for the image generation process. Can also accept
1317
+ image latents as `image`, if passing latents directly, they will not be encoded again.
1318
+ control_image (`PipelineImageInput`, *optional*):
1319
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance for Unet.
1320
+ If the type is specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also
1321
+ be accepted as an image. The dimensions of the output image default to `image`'s dimensions. If height
1322
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
1323
+ init, images must be passed as a list such that each element of the list can be correctly batched for
1324
+ input to a single ControlNet.
1325
+ height (`int`, *optional*):
1326
+ The height in pixels of the generated image. If not provided, defaults to the height of `control_image`.
1327
+ width (`int`, *optional*):
1328
+ The width in pixels of the generated image. If not provided, defaults to the width of `control_image`.
1329
+ strength (`float`, *optional*, defaults to 0.9999):
1330
+ Indicates the extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
1331
+ starting point, and more noise is added the higher the `strength`. The number of denoising steps depends
1332
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum, and the denoising
1333
+ process runs for the full number of iterations specified in `num_inference_steps`.
1334
+ num_inference_steps (`int`, *optional*, defaults to 50):
1335
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1336
+ expense of slower inference.
1337
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1338
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1339
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf).
1340
+ Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages generating
1341
+ images closely linked to the text `prompt`, usually at the expense of lower image quality.
1342
+ negative_prompt (`str` or `List[str]`, *optional*):
1343
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1344
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1345
+ less than `1`).
1346
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1347
+ The number of images to generate per prompt.
1348
+ eta (`float`, *optional*, defaults to 0.0):
1349
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1350
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1351
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1352
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1353
+ to make generation deterministic.
1354
+ latents (`torch.Tensor`, *optional*):
1355
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1356
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1357
+ tensor will be generated by sampling using the supplied random `generator`.
1358
+ output_type (`str`, *optional*, defaults to `"pil"`):
1359
+ The output format of the generated image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/):
1360
+ `PIL.Image.Image` or `np.array`.
1361
+ return_dict (`bool`, *optional*, defaults to `True`):
1362
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1363
+ plain tuple.
1364
+ cross_attention_kwargs (`dict`, *optional*):
1365
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1366
+ `self.processor` in
1367
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1368
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1369
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
1370
+ to the residual in the original UNet. If multiple ControlNets are specified in init, you can set the
1371
+ corresponding scale as a list.
1372
+ guess_mode (`bool`, *optional*, defaults to `False`):
1373
+ In this mode, the ControlNet encoder will try to recognize the content of the input image even if
1374
+ you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
1375
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
1376
+ The percentage of total steps at which the ControlNet starts applying.
1377
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
1378
+ The percentage of total steps at which the ControlNet stops applying.
1379
+ control_mode (`int` or `List[int]`, *optional*):
1380
+ The mode of ControlNet guidance. Can be used to specify different behaviors for multiple ControlNets.
1381
+ original_size (`Tuple[int, int]`, *optional*):
1382
+ If `original_size` is not the same as `target_size`, the image will appear to be down- or upsampled.
1383
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning.
1384
+ crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to (0, 0)):
1385
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1386
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1387
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning.
1388
+ target_size (`Tuple[int, int]`, *optional*):
1389
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1390
+ not specified, it will default to `(height, width)`. Part of SDXL's micro-conditioning.
1391
+ negative_original_size (`Tuple[int, int]`, *optional*):
1392
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1393
+ micro-conditioning.
1394
+ negative_crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to (0, 0)):
1395
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1396
+ micro-conditioning.
1397
+ negative_target_size (`Tuple[int, int]`, *optional*):
1398
+ To negatively condition the generation process based on a target image resolution. It should be the same
1399
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning.
1400
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1401
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1402
+ Part of SDXL's micro-conditioning.
1403
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1404
+ Used to simulate an aesthetic score of the generated image by influencing the negative text condition.
1405
+ Part of SDXL's micro-conditioning.
1406
+ clip_skip (`int`, *optional*):
1407
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1408
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1409
+ normal_tile_overlap (`int`, *optional*, defaults to 64):
1410
+ Number of overlapping pixels between tiles in consecutive rows.
1411
+ border_tile_overlap (`int`, *optional*, defaults to 128):
1412
+ Number of overlapping pixels between tiles at the borders.
1413
+ max_tile_size (`int`, *optional*, defaults to 1024):
1414
+ Maximum size of a tile in pixels.
1415
+ tile_gaussian_sigma (`float`, *optional*, defaults to 0.3):
1416
+ Sigma parameter for Gaussian weighting of tiles.
1417
+ tile_weighting_method (`str`, *optional*, defaults to "Cosine"):
1418
+ Method for weighting tiles. Options: "Cosine" or "Gaussian".
1419
+
1420
+ Examples:
1421
+
1422
+ Returns:
1423
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1424
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple`
1425
+ containing the output images.
1426
+ """
1427
+
1428
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1429
+
1430
+ # align format for control guidance
1431
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1432
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1433
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1434
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1435
+
1436
+ if not isinstance(control_image, list):
1437
+ control_image = [control_image]
1438
+ else:
1439
+ control_image = control_image.copy()
1440
+
1441
+ if control_mode is None or isinstance(control_mode, list) and len(control_mode) == 0:
1442
+ raise ValueError("The value for `control_mode` is expected!")
1443
+
1444
+ if not isinstance(control_mode, list):
1445
+ control_mode = [control_mode]
1446
+
1447
+ if len(control_image) != len(control_mode):
1448
+ raise ValueError("Expected len(control_image) == len(control_mode)")
1449
+
1450
+ num_control_type = controlnet.config.num_control_type
1451
+
1452
+ # 0. Set internal use parameters
1453
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1454
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1455
+ original_size = original_size or (height, width)
1456
+ target_size = target_size or (height, width)
1457
+ negative_original_size = negative_original_size or original_size
1458
+ negative_target_size = negative_target_size or target_size
1459
+ control_type = [0 for _ in range(num_control_type)]
1460
+ control_type = torch.Tensor(control_type)
1461
+ self._guidance_scale = guidance_scale
1462
+ self._clip_skip = clip_skip
1463
+ self._cross_attention_kwargs = cross_attention_kwargs
1464
+ self._interrupt = False
1465
+ batch_size = 1
1466
+ device = self._execution_device
1467
+ global_pool_conditions = controlnet.config.global_pool_conditions
1468
+ guess_mode = guess_mode or global_pool_conditions
1469
+
1470
+ # 1. Check inputs
1471
+ for _image, control_idx in zip(control_image, control_mode):
1472
+ control_type[control_idx] = 1
1473
+ self.check_inputs(
1474
+ prompt,
1475
+ height,
1476
+ width,
1477
+ _image,
1478
+ strength,
1479
+ num_inference_steps,
1480
+ normal_tile_overlap,
1481
+ border_tile_overlap,
1482
+ max_tile_size,
1483
+ tile_gaussian_sigma,
1484
+ tile_weighting_method,
1485
+ controlnet_conditioning_scale,
1486
+ control_guidance_start,
1487
+ control_guidance_end,
1488
+ )
1489
+
1490
+ # 2 Get tile width and tile height size
1491
+ tile_width, tile_height = _adaptive_tile_size((width, height), max_tile_size=max_tile_size)
1492
+
1493
+ # 2.1 Calculate the number of tiles needed
1494
+ grid_rows, grid_cols = self._get_num_tiles(
1495
+ height, width, tile_height, tile_width, normal_tile_overlap, border_tile_overlap
1496
+ )
1497
+
1498
+ # 2.2 Expand prompt to number of tiles
1499
+ if not isinstance(prompt, list):
1500
+ prompt = [[prompt] * grid_cols] * grid_rows
1501
+
1502
+ # 2.3 Update height and width tile size by tile size and tile overlap size
1503
+ width = (grid_cols - 1) * (tile_width - normal_tile_overlap) + min(
1504
+ tile_width, width - (grid_cols - 1) * (tile_width - normal_tile_overlap)
1505
+ )
1506
+ height = (grid_rows - 1) * (tile_height - normal_tile_overlap) + min(
1507
+ tile_height, height - (grid_rows - 1) * (tile_height - normal_tile_overlap)
1508
+ )
1509
+
1510
+ # 3. Encode input prompt
1511
+ text_encoder_lora_scale = (
1512
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1513
+ )
1514
+ text_embeddings = [
1515
+ [
1516
+ self.encode_prompt(
1517
+ prompt=col,
1518
+ device=device,
1519
+ num_images_per_prompt=num_images_per_prompt,
1520
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1521
+ negative_prompt=negative_prompt,
1522
+ prompt_embeds=None,
1523
+ negative_prompt_embeds=None,
1524
+ pooled_prompt_embeds=None,
1525
+ negative_pooled_prompt_embeds=None,
1526
+ lora_scale=text_encoder_lora_scale,
1527
+ clip_skip=self.clip_skip,
1528
+ )
1529
+ for col in row
1530
+ ]
1531
+ for row in prompt
1532
+ ]
1533
+
1534
+ # 4. Prepare latent image
1535
+ image_tensor = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
1536
+
1537
+ # 4.1 Prepare controlnet_conditioning_image
1538
+ control_image = self.prepare_control_image(
1539
+ image=image,
1540
+ width=width,
1541
+ height=height,
1542
+ batch_size=batch_size * num_images_per_prompt,
1543
+ num_images_per_prompt=num_images_per_prompt,
1544
+ device=device,
1545
+ dtype=controlnet.dtype,
1546
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1547
+ guess_mode=guess_mode,
1548
+ )
1549
+ control_type = (
1550
+ control_type.reshape(1, -1)
1551
+ .to(device, dtype=controlnet.dtype)
1552
+ .repeat(batch_size * num_images_per_prompt * 2, 1)
1553
+ )
1554
+
1555
+ # 5. Prepare timesteps
1556
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
1557
+ extra_set_kwargs = {}
1558
+ if accepts_offset:
1559
+ extra_set_kwargs["offset"] = 1
1560
+ self.scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
1561
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength)
1562
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1563
+ self._num_timesteps = len(timesteps)
1564
+
1565
+ # 6. Prepare latent variables
1566
+ dtype = text_embeddings[0][0][0].dtype
1567
+ if latents is None:
1568
+ latents = self.prepare_latents(
1569
+ image_tensor,
1570
+ latent_timestep,
1571
+ batch_size,
1572
+ num_images_per_prompt,
1573
+ dtype,
1574
+ device,
1575
+ generator,
1576
+ True,
1577
+ )
1578
+
1579
+ # if we use LMSDiscreteScheduler, let's make sure latents are multiplied by sigmas
1580
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
1581
+ latents = latents * self.scheduler.sigmas[0]
1582
+
1583
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1584
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1585
+
1586
+ # 8. Create tensor stating which controlnets to keep
1587
+ controlnet_keep = []
1588
+ for i in range(len(timesteps)):
1589
+ controlnet_keep.append(
1590
+ 1.0
1591
+ - float(i / len(timesteps) < control_guidance_start or (i + 1) / len(timesteps) > control_guidance_end)
1592
+ )
1593
+
1594
+ # 8.1 Prepare added time ids & embeddings
1595
+ # text_embeddings order: prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
1596
+ embeddings_and_added_time = []
1597
+ crops_coords_top_left = negative_crops_coords_top_left = (tile_width, tile_height)
1598
+ for row in range(grid_rows):
1599
+ addition_embed_type_row = []
1600
+ for col in range(grid_cols):
1601
+ # extract generated values
1602
+ prompt_embeds = text_embeddings[row][col][0]
1603
+ negative_prompt_embeds = text_embeddings[row][col][1]
1604
+ pooled_prompt_embeds = text_embeddings[row][col][2]
1605
+ negative_pooled_prompt_embeds = text_embeddings[row][col][3]
1606
+
1607
+ if negative_original_size is None:
1608
+ negative_original_size = original_size
1609
+ if negative_target_size is None:
1610
+ negative_target_size = target_size
1611
+ add_text_embeds = pooled_prompt_embeds
1612
+
1613
+ if self.text_encoder_2 is None:
1614
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1615
+ else:
1616
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1617
+
1618
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1619
+ original_size,
1620
+ crops_coords_top_left,
1621
+ target_size,
1622
+ aesthetic_score,
1623
+ negative_aesthetic_score,
1624
+ negative_original_size,
1625
+ negative_crops_coords_top_left,
1626
+ negative_target_size,
1627
+ dtype=prompt_embeds.dtype,
1628
+ text_encoder_projection_dim=text_encoder_projection_dim,
1629
+ )
1630
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1631
+
1632
+ if self.do_classifier_free_guidance:
1633
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1634
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1635
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1636
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1637
+
1638
+ prompt_embeds = prompt_embeds.to(device)
1639
+ add_text_embeds = add_text_embeds.to(device)
1640
+ add_time_ids = add_time_ids.to(device)
1641
+ addition_embed_type_row.append((prompt_embeds, add_text_embeds, add_time_ids))
1642
+
1643
+ embeddings_and_added_time.append(addition_embed_type_row)
1644
+
1645
+ # 9. Prepare tiles weights and latent overlaps size to denoising process
1646
+ tile_weights, tile_row_overlaps, tile_col_overlaps = self.prepare_tiles(
1647
+ grid_rows,
1648
+ grid_cols,
1649
+ tile_weighting_method,
1650
+ tile_width,
1651
+ tile_height,
1652
+ normal_tile_overlap,
1653
+ border_tile_overlap,
1654
+ width,
1655
+ height,
1656
+ tile_gaussian_sigma,
1657
+ batch_size,
1658
+ device,
1659
+ dtype,
1660
+ )
1661
+
1662
+ # 10. Denoising loop
1663
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1664
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1665
+ for i, t in enumerate(timesteps):
1666
+ # Diffuse each tile
1667
+ noise_preds = []
1668
+ for row in range(grid_rows):
1669
+ noise_preds_row = []
1670
+ for col in range(grid_cols):
1671
+ if self.interrupt:
1672
+ continue
1673
+ tile_row_overlap = tile_row_overlaps[row, col]
1674
+ tile_col_overlap = tile_col_overlaps[row, col]
1675
+
1676
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2latent_indices(
1677
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, width, height
1678
+ )
1679
+
1680
+ tile_latents = latents[:, :, px_row_init:px_row_end, px_col_init:px_col_end]
1681
+
1682
+ # expand the latents if we are doing classifier free guidance
1683
+ latent_model_input = (
1684
+ torch.cat([tile_latents] * 2)
1685
+ if self.do_classifier_free_guidance
1686
+ else tile_latents # 1, 4, ...
1687
+ )
1688
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1689
+
1690
+ # predict the noise residual
1691
+ added_cond_kwargs = {
1692
+ "text_embeds": embeddings_and_added_time[row][col][1],
1693
+ "time_ids": embeddings_and_added_time[row][col][2],
1694
+ }
1695
+
1696
+ # controlnet(s) inference
1697
+ if guess_mode and self.do_classifier_free_guidance:
1698
+ # Infer ControlNet only for the conditional batch.
1699
+ control_model_input = tile_latents
1700
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1701
+ controlnet_prompt_embeds = embeddings_and_added_time[row][col][0].chunk(2)[1]
1702
+ controlnet_added_cond_kwargs = {
1703
+ "text_embeds": embeddings_and_added_time[row][col][1].chunk(2)[1],
1704
+ "time_ids": embeddings_and_added_time[row][col][2].chunk(2)[1],
1705
+ }
1706
+ else:
1707
+ control_model_input = latent_model_input
1708
+ controlnet_prompt_embeds = embeddings_and_added_time[row][col][0]
1709
+ controlnet_added_cond_kwargs = added_cond_kwargs
1710
+
1711
+ if isinstance(controlnet_keep[i], list):
1712
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1713
+ else:
1714
+ controlnet_cond_scale = controlnet_conditioning_scale
1715
+ if isinstance(controlnet_cond_scale, list):
1716
+ controlnet_cond_scale = controlnet_cond_scale[0]
1717
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1718
+
1719
+ px_row_init_pixel, px_row_end_pixel, px_col_init_pixel, px_col_end_pixel = _tile2pixel_indices(
1720
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, width, height
1721
+ )
1722
+
1723
+ tile_control_image = control_image[
1724
+ :, :, px_row_init_pixel:px_row_end_pixel, px_col_init_pixel:px_col_end_pixel
1725
+ ]
1726
+
1727
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1728
+ control_model_input,
1729
+ t,
1730
+ encoder_hidden_states=controlnet_prompt_embeds,
1731
+ controlnet_cond=[tile_control_image],
1732
+ control_type=control_type,
1733
+ control_type_idx=control_mode,
1734
+ conditioning_scale=cond_scale,
1735
+ guess_mode=guess_mode,
1736
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1737
+ return_dict=False,
1738
+ )
1739
+
1740
+ if guess_mode and self.do_classifier_free_guidance:
1741
+ # Inferred ControlNet only for the conditional batch.
1742
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1743
+ # add 0 to the unconditional batch to keep it unchanged.
1744
+ down_block_res_samples = [
1745
+ torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples
1746
+ ]
1747
+ mid_block_res_sample = torch.cat(
1748
+ [torch.zeros_like(mid_block_res_sample), mid_block_res_sample]
1749
+ )
1750
+
1751
+ # predict the noise residual
1752
+ with torch.amp.autocast(device.type, dtype=dtype, enabled=dtype != self.unet.dtype):
1753
+ noise_pred = self.unet(
1754
+ latent_model_input,
1755
+ t,
1756
+ encoder_hidden_states=embeddings_and_added_time[row][col][0],
1757
+ cross_attention_kwargs=self.cross_attention_kwargs,
1758
+ down_block_additional_residuals=down_block_res_samples,
1759
+ mid_block_additional_residual=mid_block_res_sample,
1760
+ added_cond_kwargs=added_cond_kwargs,
1761
+ return_dict=False,
1762
+ )[0]
1763
+
1764
+ # perform guidance
1765
+ if self.do_classifier_free_guidance:
1766
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1767
+ noise_pred_tile = noise_pred_uncond + guidance_scale * (
1768
+ noise_pred_text - noise_pred_uncond
1769
+ )
1770
+ noise_preds_row.append(noise_pred_tile)
1771
+ noise_preds.append(noise_preds_row)
1772
+
1773
+ # Stitch noise predictions for all tiles
1774
+ noise_pred = torch.zeros(latents.shape, device=device)
1775
+ contributors = torch.zeros(latents.shape, device=device)
1776
+
1777
+ # Add each tile contribution to overall latents
1778
+ for row in range(grid_rows):
1779
+ for col in range(grid_cols):
1780
+ tile_row_overlap = tile_row_overlaps[row, col]
1781
+ tile_col_overlap = tile_col_overlaps[row, col]
1782
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2latent_indices(
1783
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, width, height
1784
+ )
1785
+ tile_weights_resized = tile_weights[row, col]
1786
+
1787
+ noise_pred[:, :, px_row_init:px_row_end, px_col_init:px_col_end] += (
1788
+ noise_preds[row][col] * tile_weights_resized
1789
+ )
1790
+ contributors[:, :, px_row_init:px_row_end, px_col_init:px_col_end] += tile_weights_resized
1791
+
1792
+ # Average overlapping areas with more than 1 contributor
1793
+ noise_pred /= contributors
1794
+ noise_pred = noise_pred.to(dtype)
1795
+
1796
+ # compute the previous noisy sample x_t -> x_t-1
1797
+ latents_dtype = latents.dtype
1798
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1799
+ if latents.dtype != latents_dtype:
1800
+ if torch.backends.mps.is_available():
1801
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1802
+ latents = latents.to(latents_dtype)
1803
+
1804
+ # update progress bar
1805
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1806
+ progress_bar.update()
1807
+
1808
+ if XLA_AVAILABLE:
1809
+ xm.mark_step()
1810
+
1811
+ # If we do sequential model offloading, let's offload unet and controlnet
1812
+ # manually for max memory savings
1813
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1814
+ self.unet.to("cpu")
1815
+ self.controlnet.to("cpu")
1816
+ torch.cuda.empty_cache()
1817
+
1818
+ if not output_type == "latent":
1819
+ # make sure the VAE is in float32 mode, as it overflows in float16
1820
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1821
+
1822
+ if needs_upcasting:
1823
+ self.upcast_vae()
1824
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1825
+
1826
+ # unscale/denormalize the latents
1827
+ # denormalize with the mean and std if available and not None
1828
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1829
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1830
+ if has_latents_mean and has_latents_std:
1831
+ latents_mean = (
1832
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1833
+ )
1834
+ latents_std = (
1835
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1836
+ )
1837
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1838
+ else:
1839
+ latents = latents / self.vae.config.scaling_factor
1840
+
1841
+ image = self.vae.decode(latents, return_dict=False)[0]
1842
+
1843
+ # cast back to fp16 if needed
1844
+ if needs_upcasting:
1845
+ self.vae.to(dtype=torch.float16)
1846
+
1847
+ # apply watermark if available
1848
+ if self.watermark is not None:
1849
+ image = self.watermark.apply_watermark(image)
1850
+
1851
+ image = self.image_processor.postprocess(image, output_type=output_type)
1852
+ else:
1853
+ image = latents
1854
+
1855
+ # Offload all models
1856
+ self.maybe_free_model_hooks()
1857
+
1858
+ result = StableDiffusionXLPipelineOutput(images=image)
1859
+ if not return_dict:
1860
+ return (image,)
1861
+
1862
+ return result