fffiloni commited on
Commit
fe72a39
1 Parent(s): 08a4276

Upload 4 files

Browse files
Files changed (4) hide show
  1. accdiffusion_sdxl.py +1655 -0
  2. requirements.txt +13 -0
  3. utils.py +885 -0
  4. watermark.py +36 -0
accdiffusion_sdxl.py ADDED
@@ -0,0 +1,1655 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ import argparse
15
+ import inspect
16
+ import os
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+ import matplotlib.pyplot as plt
19
+ from PIL import Image
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import numpy as np
24
+ import random
25
+ import warnings
26
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
27
+ from utils import *
28
+
29
+ from diffusers.image_processor import VaeImageProcessor
30
+ from diffusers.loaders import (
31
+ FromSingleFileMixin,
32
+ LoraLoaderMixin,
33
+ TextualInversionLoaderMixin,
34
+ )
35
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
36
+ from diffusers.models.attention_processor import (
37
+ AttnProcessor2_0,
38
+ LoRAAttnProcessor2_0,
39
+ LoRAXFormersAttnProcessor,
40
+ XFormersAttnProcessor,
41
+ )
42
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
43
+ from diffusers.schedulers import KarrasDiffusionSchedulers
44
+ from diffusers.utils import (
45
+ is_accelerate_available,
46
+ is_accelerate_version,
47
+ is_invisible_watermark_available,
48
+ logging,
49
+ replace_example_docstring,
50
+ )
51
+ from diffusers.utils.torch_utils import randn_tensor
52
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
53
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
54
+ from accelerate.utils import set_seed
55
+ from tqdm import tqdm
56
+ if is_invisible_watermark_available():
57
+ from .watermark import StableDiffusionXLWatermarker
58
+
59
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
60
+
61
+ EXAMPLE_DOC_STRING = """
62
+ Examples:
63
+ ```py
64
+ >>> import torch
65
+ >>> from diffusers import StableDiffusionXLPipeline
66
+
67
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
68
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
69
+ ... )
70
+ >>> pipe = pipe.to("cuda")
71
+
72
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
73
+ >>> image = pipe(prompt).images[0]
74
+ ```
75
+ """
76
+
77
+
78
+
79
+ def gaussian_kernel(kernel_size=3, sigma=1.0, channels=3):
80
+ x_coord = torch.arange(kernel_size)
81
+ gaussian_1d = torch.exp(-(x_coord - (kernel_size - 1) / 2) ** 2 / (2 * sigma ** 2))
82
+ gaussian_1d = gaussian_1d / gaussian_1d.sum()
83
+ gaussian_2d = gaussian_1d[:, None] * gaussian_1d[None, :]
84
+ kernel = gaussian_2d[None, None, :, :].repeat(channels, 1, 1, 1)
85
+
86
+ return kernel
87
+
88
+ def gaussian_filter(latents, kernel_size=3, sigma=1.0):
89
+ channels = latents.shape[1]
90
+ kernel = gaussian_kernel(kernel_size, sigma, channels).to(latents.device, latents.dtype)
91
+ blurred_latents = F.conv2d(latents, kernel, padding=kernel_size//2, groups=channels)
92
+ return blurred_latents
93
+
94
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
95
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
96
+ """
97
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
98
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
99
+ """
100
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
101
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
102
+ # rescale the results from guidance (fixes overexposure)
103
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
104
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
105
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
106
+ return noise_cfg
107
+
108
+
109
+ class AccDiffusionSDXLPipeline(DiffusionPipeline, FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin):
110
+ """
111
+ Pipeline for text-to-image generation using Stable Diffusion XL.
112
+
113
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
114
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
115
+
116
+ In addition the pipeline inherits the following loading methods:
117
+ - *LoRA*: [`StableDiffusionXLPipeline.load_lora_weights`]
118
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
119
+
120
+ as well as the following saving methods:
121
+ - *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
122
+
123
+ Args:
124
+ vae ([`AutoencoderKL`]):
125
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
126
+ text_encoder ([`CLIPTextModel`]):
127
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
128
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
129
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
130
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
131
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
132
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
133
+ specifically the
134
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
135
+ variant.
136
+ tokenizer (`CLIPTokenizer`):
137
+ Tokenizer of class
138
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
139
+ tokenizer_2 (`CLIPTokenizer`):
140
+ Second Tokenizer of class
141
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
142
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
143
+ scheduler ([`SchedulerMixin`]):
144
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
145
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
146
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
147
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
148
+ `stabilityai/stable-diffusion-xl-base-1-0`.
149
+ add_watermarker (`bool`, *optional*):
150
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
151
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
152
+ watermarker will be used.
153
+ """
154
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
155
+
156
+ def __init__(
157
+ self,
158
+ vae: AutoencoderKL,
159
+ text_encoder: CLIPTextModel,
160
+ text_encoder_2: CLIPTextModelWithProjection,
161
+ tokenizer: CLIPTokenizer,
162
+ tokenizer_2: CLIPTokenizer,
163
+ unet: UNet2DConditionModel,
164
+ scheduler: KarrasDiffusionSchedulers,
165
+ force_zeros_for_empty_prompt: bool = True,
166
+ add_watermarker: Optional[bool] = None,
167
+ ):
168
+ super().__init__()
169
+
170
+ self.register_modules(
171
+ vae=vae,
172
+ text_encoder=text_encoder,
173
+ text_encoder_2=text_encoder_2,
174
+ tokenizer=tokenizer,
175
+ tokenizer_2=tokenizer_2,
176
+ unet=unet,
177
+ scheduler=scheduler,
178
+ )
179
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
180
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
181
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
182
+ self.default_sample_size = self.unet.config.sample_size
183
+
184
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
185
+
186
+ if add_watermarker:
187
+ self.watermark = StableDiffusionXLWatermarker()
188
+ else:
189
+ self.watermark = None
190
+
191
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
192
+ def enable_vae_slicing(self):
193
+ r"""
194
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
195
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
196
+ """
197
+ self.vae.enable_slicing()
198
+
199
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
200
+ def disable_vae_slicing(self):
201
+ r"""
202
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
203
+ computing decoding in one step.
204
+ """
205
+ self.vae.disable_slicing()
206
+
207
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
208
+ def enable_vae_tiling(self):
209
+ r"""
210
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
211
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
212
+ processing larger images.
213
+ """
214
+ self.vae.enable_tiling()
215
+
216
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
217
+ def disable_vae_tiling(self):
218
+ r"""
219
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
220
+ computing decoding in one step.
221
+ """
222
+ self.vae.disable_tiling()
223
+
224
+ def encode_prompt(
225
+ self,
226
+ prompt: str,
227
+ prompt_2: Optional[str] = None,
228
+ device: Optional[torch.device] = None,
229
+ num_images_per_prompt: int = 1,
230
+ do_classifier_free_guidance: bool = True,
231
+ negative_prompt: Optional[str] = None,
232
+ negative_prompt_2: Optional[str] = None,
233
+ prompt_embeds: Optional[torch.FloatTensor] = None,
234
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
235
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
236
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
237
+ lora_scale: Optional[float] = None,
238
+ ):
239
+ r"""
240
+ Encodes the prompt into text encoder hidden states.
241
+
242
+ Args:
243
+ prompt (`str` or `List[str]`, *optional*):
244
+ prompt to be encoded
245
+ prompt_2 (`str` or `List[str]`, *optional*):
246
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
247
+ used in both text-encoders
248
+ device: (`torch.device`):
249
+ torch device
250
+ num_images_per_prompt (`int`):
251
+ number of images that should be generated per prompt
252
+ do_classifier_free_guidance (`bool`):
253
+ whether to use classifier free guidance or not
254
+ negative_prompt (`str` or `List[str]`, *optional*):
255
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
256
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
257
+ less than `1`).
258
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
259
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
260
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
261
+ prompt_embeds (`torch.FloatTensor`, *optional*):
262
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
263
+ provided, text embeddings will be generated from `prompt` input argument.
264
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
265
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
266
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
267
+ argument.
268
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
269
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
270
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
271
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
272
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
273
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
274
+ input argument.
275
+ lora_scale (`float`, *optional*):
276
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
277
+ """
278
+ device = device or self._execution_device
279
+
280
+ # set lora scale so that monkey patched LoRA
281
+ # function of text encoder can correctly access it
282
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
283
+ self._lora_scale = lora_scale
284
+
285
+ # dynamically adjust the LoRA scale
286
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
287
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
288
+
289
+ if prompt is not None and isinstance(prompt, str):
290
+ batch_size = 1
291
+ elif prompt is not None and isinstance(prompt, list):
292
+ batch_size = len(prompt)
293
+ else:
294
+ batch_size = prompt_embeds.shape[0]
295
+
296
+ # Define tokenizers and text encoders
297
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
298
+ text_encoders = (
299
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
300
+ )
301
+
302
+ if prompt_embeds is None:
303
+ prompt_2 = prompt_2 or prompt
304
+ # textual inversion: procecss multi-vector tokens if necessary
305
+ prompt_embeds_list = []
306
+ prompts = [prompt, prompt_2]
307
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
308
+ if isinstance(self, TextualInversionLoaderMixin):
309
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
310
+
311
+ text_inputs = tokenizer(
312
+ prompt,
313
+ padding="max_length",
314
+ max_length=tokenizer.model_max_length,
315
+ truncation=True,
316
+ return_tensors="pt",
317
+ )
318
+
319
+ text_input_ids = text_inputs.input_ids
320
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
321
+
322
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
323
+ text_input_ids, untruncated_ids
324
+ ):
325
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
326
+ logger.warning(
327
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
328
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
329
+ )
330
+
331
+ prompt_embeds = text_encoder(
332
+ text_input_ids.to(device),
333
+ output_hidden_states=True,
334
+ )
335
+
336
+ # We are only ALWAYS interested in the pooled output of the final text encoder
337
+ pooled_prompt_embeds = prompt_embeds[0]
338
+ prompt_embeds = prompt_embeds.hidden_states[-2]
339
+
340
+ prompt_embeds_list.append(prompt_embeds)
341
+
342
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
343
+
344
+ # get unconditional embeddings for classifier free guidance
345
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
346
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
347
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
348
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
349
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
350
+ negative_prompt = negative_prompt or ""
351
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
352
+
353
+ uncond_tokens: List[str]
354
+ if prompt is not None and type(prompt) is not type(negative_prompt):
355
+ raise TypeError(
356
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
357
+ f" {type(prompt)}."
358
+ )
359
+ elif isinstance(negative_prompt, str):
360
+ uncond_tokens = [negative_prompt, negative_prompt_2]
361
+ elif batch_size != len(negative_prompt):
362
+ raise ValueError(
363
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
364
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
365
+ " the batch size of `prompt`."
366
+ )
367
+ else:
368
+ uncond_tokens = [negative_prompt, negative_prompt_2]
369
+
370
+ negative_prompt_embeds_list = []
371
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
372
+ if isinstance(self, TextualInversionLoaderMixin):
373
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
374
+
375
+ max_length = prompt_embeds.shape[1]
376
+ uncond_input = tokenizer(
377
+ negative_prompt,
378
+ padding="max_length",
379
+ max_length=max_length,
380
+ truncation=True,
381
+ return_tensors="pt",
382
+ )
383
+
384
+ negative_prompt_embeds = text_encoder(
385
+ uncond_input.input_ids.to(device),
386
+ output_hidden_states=True,
387
+ )
388
+ # We are only ALWAYS interested in the pooled output of the final text encoder
389
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
390
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
391
+
392
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
393
+
394
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
395
+
396
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
397
+ bs_embed, seq_len, _ = prompt_embeds.shape
398
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
399
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
400
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
401
+
402
+ if do_classifier_free_guidance:
403
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
404
+ seq_len = negative_prompt_embeds.shape[1]
405
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
406
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
407
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
408
+
409
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
410
+ bs_embed * num_images_per_prompt, -1
411
+ )
412
+ if do_classifier_free_guidance:
413
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
414
+ bs_embed * num_images_per_prompt, -1
415
+ )
416
+
417
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
418
+
419
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
420
+ def prepare_extra_step_kwargs(self, generator, eta):
421
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
422
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
423
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
424
+ # and should be between [0, 1]
425
+
426
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
427
+ extra_step_kwargs = {}
428
+ if accepts_eta:
429
+ extra_step_kwargs["eta"] = eta
430
+
431
+ # check if the scheduler accepts generator
432
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
433
+ if accepts_generator:
434
+ extra_step_kwargs["generator"] = generator
435
+ return extra_step_kwargs
436
+
437
+ def check_inputs(
438
+ self,
439
+ prompt,
440
+ prompt_2,
441
+ height,
442
+ width,
443
+ callback_steps,
444
+ negative_prompt=None,
445
+ negative_prompt_2=None,
446
+ prompt_embeds=None,
447
+ negative_prompt_embeds=None,
448
+ pooled_prompt_embeds=None,
449
+ negative_pooled_prompt_embeds=None,
450
+ num_images_per_prompt=None,
451
+ ):
452
+ if height % 8 != 0 or width % 8 != 0:
453
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
454
+
455
+ if (callback_steps is None) or (
456
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
457
+ ):
458
+ raise ValueError(
459
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
460
+ f" {type(callback_steps)}."
461
+ )
462
+
463
+ if prompt is not None and prompt_embeds is not None:
464
+ raise ValueError(
465
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
466
+ " only forward one of the two."
467
+ )
468
+ elif prompt_2 is not None and prompt_embeds is not None:
469
+ raise ValueError(
470
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
471
+ " only forward one of the two."
472
+ )
473
+ elif prompt is None and prompt_embeds is None:
474
+ raise ValueError(
475
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
476
+ )
477
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
478
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
479
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
480
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
481
+
482
+ if negative_prompt is not None and negative_prompt_embeds is not None:
483
+ raise ValueError(
484
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
485
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
486
+ )
487
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
488
+ raise ValueError(
489
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
490
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
491
+ )
492
+
493
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
494
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
495
+ raise ValueError(
496
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
497
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
498
+ f" {negative_prompt_embeds.shape}."
499
+ )
500
+
501
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
502
+ raise ValueError(
503
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
504
+ )
505
+
506
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
507
+ raise ValueError(
508
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
509
+ )
510
+
511
+ if max(height, width) % 1024 != 0:
512
+ raise ValueError(f"the larger one of `height` and `width` has to be divisible by 1024 but are {height} and {width}.")
513
+
514
+ if num_images_per_prompt != 1:
515
+ warnings.warn("num_images_per_prompt != 1 is not supported by AccDiffusion and will be ignored.")
516
+ num_images_per_prompt = 1
517
+
518
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
519
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
520
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
521
+ if isinstance(generator, list) and len(generator) != batch_size:
522
+ raise ValueError(
523
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
524
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
525
+ )
526
+
527
+ if latents is None:
528
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
529
+ else:
530
+ latents = latents.to(device)
531
+
532
+ # scale the initial noise by the standard deviation required by the scheduler
533
+ latents = latents * self.scheduler.init_noise_sigma
534
+ return latents
535
+
536
+ def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
537
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
538
+
539
+ passed_add_embed_dim = (
540
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
541
+ )
542
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
543
+
544
+ if expected_add_embed_dim != passed_add_embed_dim:
545
+ raise ValueError(
546
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. \
547
+ The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
548
+ )
549
+
550
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
551
+ return add_time_ids
552
+
553
+ def get_views(self, height, width, window_size=128, stride=64, random_jitter=False):
554
+ # Here, we define the mappings F_i (see Eq. 7 in the MultiDiffusion paper https://arxiv.org/abs/2302.08113)
555
+ # if panorama's height/width < window_size, num_blocks of height/width should return 1
556
+ height //= self.vae_scale_factor
557
+ width //= self.vae_scale_factor
558
+ num_blocks_height = int((height - window_size) / stride - 1e-6) + 2 if height > window_size else 1
559
+ num_blocks_width = int((width - window_size) / stride - 1e-6) + 2 if width > window_size else 1
560
+ total_num_blocks = int(num_blocks_height * num_blocks_width)
561
+ views = []
562
+ for i in range(total_num_blocks):
563
+ h_start = int((i // num_blocks_width) * stride)
564
+ h_end = h_start + window_size
565
+ w_start = int((i % num_blocks_width) * stride)
566
+ w_end = w_start + window_size
567
+
568
+ if h_end > height:
569
+ h_start = int(h_start + height - h_end)
570
+ h_end = int(height)
571
+ if w_end > width:
572
+ w_start = int(w_start + width - w_end)
573
+ w_end = int(width)
574
+ if h_start < 0:
575
+ h_end = int(h_end - h_start)
576
+ h_start = 0
577
+ if w_start < 0:
578
+ w_end = int(w_end - w_start)
579
+ w_start = 0
580
+
581
+ if random_jitter:
582
+ jitter_range = (window_size - stride) // 4
583
+ w_jitter = 0
584
+ h_jitter = 0
585
+ if (w_start != 0) and (w_end != width):
586
+ w_jitter = random.randint(-jitter_range, jitter_range)
587
+ elif (w_start == 0) and (w_end != width):
588
+ w_jitter = random.randint(-jitter_range, 0)
589
+ elif (w_start != 0) and (w_end == width):
590
+ w_jitter = random.randint(0, jitter_range)
591
+
592
+ if (h_start != 0) and (h_end != height):
593
+ h_jitter = random.randint(-jitter_range, jitter_range)
594
+ elif (h_start == 0) and (h_end != height):
595
+ h_jitter = random.randint(-jitter_range, 0)
596
+ elif (h_start != 0) and (h_end == height):
597
+ h_jitter = random.randint(0, jitter_range)
598
+ # When using jitter, the noise will be padded by jitterrange, so we need to add it to the view.
599
+ h_start = h_start + h_jitter + jitter_range
600
+ h_end = h_end + h_jitter + jitter_range
601
+ w_start = w_start + w_jitter + jitter_range
602
+ w_end = w_end + w_jitter + jitter_range
603
+
604
+ views.append((h_start, h_end, w_start, w_end))
605
+ return views
606
+
607
+
608
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
609
+ def upcast_vae(self):
610
+ dtype = self.vae.dtype
611
+ self.vae.to(dtype=torch.float32)
612
+ use_torch_2_0_or_xformers = isinstance(
613
+ self.vae.decoder.mid_block.attentions[0].processor,
614
+ (
615
+ AttnProcessor2_0,
616
+ XFormersAttnProcessor,
617
+ LoRAXFormersAttnProcessor,
618
+ LoRAAttnProcessor2_0,
619
+ ),
620
+ )
621
+ # if xformers or torch_2_0 is used attention block does not need
622
+ # to be in float32 which can save lots of memory
623
+ if use_torch_2_0_or_xformers:
624
+ self.vae.post_quant_conv.to(dtype)
625
+ self.vae.decoder.conv_in.to(dtype)
626
+ self.vae.decoder.mid_block.to(dtype)
627
+
628
+
629
+ def register_attention_control(self, controller):
630
+ attn_procs = {}
631
+ cross_att_count = 0
632
+ ori_attn_processors = self.unet.attn_processors
633
+ for name in self.unet.attn_processors.keys():
634
+ if name.startswith("mid_block"):
635
+ place_in_unet = "mid"
636
+ elif name.startswith("up_blocks"):
637
+ place_in_unet = "up"
638
+ elif name.startswith("down_blocks"):
639
+ place_in_unet = "down"
640
+ else:
641
+ continue
642
+ cross_att_count += 1
643
+ attn_procs[name] = P2PCrossAttnProcessor(controller=controller, place_in_unet=place_in_unet)
644
+
645
+ self.unet.set_attn_processor(attn_procs)
646
+ controller.num_att_layers = cross_att_count
647
+ return ori_attn_processors
648
+
649
+ def recover_attention_control(self, ori_attn_processors):
650
+ self.unet.set_attn_processor(ori_attn_processors)
651
+
652
+
653
+
654
+ # Overrride to properly handle the loading and unloading of the additional text encoder.
655
+ def load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
656
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
657
+ # it here explicitly to be able to tell that it's coming from an SDXL
658
+ # pipeline.
659
+
660
+ # Remove any existing hooks.
661
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
662
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
663
+ else:
664
+ raise ImportError("Offloading requires `accelerate v0.17.0` or higher.")
665
+
666
+ is_model_cpu_offload = False
667
+ is_sequential_cpu_offload = False
668
+ recursive = False
669
+ for _, component in self.components.items():
670
+ if isinstance(component, torch.nn.Module):
671
+ if hasattr(component, "_hf_hook"):
672
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
673
+ is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
674
+ logger.info(
675
+ "Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
676
+ )
677
+ recursive = is_sequential_cpu_offload
678
+ remove_hook_from_module(component, recurse=recursive)
679
+ state_dict, network_alphas = self.lora_state_dict(
680
+ pretrained_model_name_or_path_or_dict,
681
+ unet_config=self.unet.config,
682
+ **kwargs,
683
+ )
684
+ self.load_lora_into_unet(state_dict, network_alphas=network_alphas, unet=self.unet)
685
+
686
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
687
+ if len(text_encoder_state_dict) > 0:
688
+ self.load_lora_into_text_encoder(
689
+ text_encoder_state_dict,
690
+ network_alphas=network_alphas,
691
+ text_encoder=self.text_encoder,
692
+ prefix="text_encoder",
693
+ lora_scale=self.lora_scale,
694
+ )
695
+
696
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
697
+ if len(text_encoder_2_state_dict) > 0:
698
+ self.load_lora_into_text_encoder(
699
+ text_encoder_2_state_dict,
700
+ network_alphas=network_alphas,
701
+ text_encoder=self.text_encoder_2,
702
+ prefix="text_encoder_2",
703
+ lora_scale=self.lora_scale,
704
+ )
705
+
706
+ # Offload back.
707
+ if is_model_cpu_offload:
708
+ self.enable_model_cpu_offload()
709
+ elif is_sequential_cpu_offload:
710
+ self.enable_sequential_cpu_offload()
711
+
712
+ @classmethod
713
+ def save_lora_weights(
714
+ self,
715
+ save_directory: Union[str, os.PathLike],
716
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
717
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
718
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
719
+ is_main_process: bool = True,
720
+ weight_name: str = None,
721
+ save_function: Callable = None,
722
+ safe_serialization: bool = True,
723
+ ):
724
+ state_dict = {}
725
+
726
+ def pack_weights(layers, prefix):
727
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
728
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
729
+ return layers_state_dict
730
+
731
+ if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
732
+ raise ValueError(
733
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
734
+ )
735
+
736
+ if unet_lora_layers:
737
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
738
+
739
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
740
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
741
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
742
+
743
+ self.write_lora_layers(
744
+ state_dict=state_dict,
745
+ save_directory=save_directory,
746
+ is_main_process=is_main_process,
747
+ weight_name=weight_name,
748
+ save_function=save_function,
749
+ safe_serialization=safe_serialization,
750
+ )
751
+
752
+ def _remove_text_encoder_monkey_patch(self):
753
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
754
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
755
+
756
+ @torch.no_grad()
757
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
758
+ def __call__(
759
+ self,
760
+ prompt: Union[str, List[str]] = None,
761
+ prompt_2: Optional[Union[str, List[str]]] = None,
762
+ height: Optional[int] = None,
763
+ width: Optional[int] = None,
764
+ num_inference_steps: int = 50,
765
+ denoising_end: Optional[float] = None,
766
+ guidance_scale: float = 5.0,
767
+ negative_prompt: Optional[Union[str, List[str]]] = None,
768
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
769
+ num_images_per_prompt: Optional[int] = 1,
770
+ eta: float = 0.0,
771
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
772
+ latents: Optional[torch.FloatTensor] = None,
773
+ prompt_embeds: Optional[torch.FloatTensor] = None,
774
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
775
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
776
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
777
+ output_type: Optional[str] = "pil",
778
+ return_dict: bool = False,
779
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
780
+ callback_steps: int = 1,
781
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
782
+ guidance_rescale: float = 0.0,
783
+ original_size: Optional[Tuple[int, int]] = None,
784
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
785
+ target_size: Optional[Tuple[int, int]] = None,
786
+ negative_original_size: Optional[Tuple[int, int]] = None,
787
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
788
+ negative_target_size: Optional[Tuple[int, int]] = None,
789
+ ################### AccDiffusion specific parameters ####################
790
+ image_lr: Optional[torch.FloatTensor] = None,
791
+ view_batch_size: int = 16,
792
+ multi_decoder: bool = True,
793
+ stride: Optional[int] = 64,
794
+ cosine_scale_1: Optional[float] = 3.,
795
+ cosine_scale_2: Optional[float] = 1.,
796
+ cosine_scale_3: Optional[float] = 1.,
797
+ sigma: Optional[float] = 1.0,
798
+ lowvram: bool = False,
799
+ multi_guidance_scale: Optional[float] = 7.5,
800
+ use_guassian: bool = True,
801
+ upscale_mode: Union[str, List[str]] = 'bicubic_latent',
802
+ use_multidiffusion: bool = True,
803
+ use_dilated_sampling : bool = True,
804
+ use_skip_residual: bool = True,
805
+ use_progressive_upscaling: bool = True,
806
+ shuffle: bool = False,
807
+ result_path: str = './outputs/AccDiffusion',
808
+ debug: bool = False,
809
+ use_md_prompt: bool = False,
810
+ attn_res=None,
811
+ save_attention_map: bool = False,
812
+ seed: Optional[int] = None,
813
+ c : Optional[float] = 0.3,
814
+ ):
815
+ r"""
816
+ Function invoked when calling the pipeline for generation.
817
+
818
+ Args:
819
+ prompt (`str` or `List[str]`, *optional*):
820
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
821
+ instead.
822
+ prompt_2 (`str` or `List[str]`, *optional*):
823
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
824
+ used in both text-encoders
825
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
826
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
827
+ Anything below 512 pixels won't work well for
828
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
829
+ and checkpoints that are not specifically fine-tuned on low resolutions.
830
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
831
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
832
+ Anything below 512 pixels won't work well for
833
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
834
+ and checkpoints that are not specifically fine-tuned on low resolutions.
835
+ num_inference_steps (`int`, *optional*, defaults to 50):
836
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
837
+ expense of slower inference.
838
+ denoising_end (`float`, *optional*):
839
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
840
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
841
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
842
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
843
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
844
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
845
+ guidance_scale (`float`, *optional*, defaults to 5.0):
846
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
847
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
848
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
849
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
850
+ usually at the expense of lower image quality.
851
+ negative_prompt (`str` or `List[str]`, *optional*):
852
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
853
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
854
+ less than `1`).
855
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
856
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
857
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
858
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
859
+ The number of images to generate per prompt.
860
+ eta (`float`, *optional*, defaults to 0.0):
861
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
862
+ [`schedulers.DDIMScheduler`], will be ignored for others.
863
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
864
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
865
+ to make generation deterministic.
866
+ latents (`torch.FloatTensor`, *optional*):
867
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
868
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
869
+ tensor will ge generated by sampling using the supplied random `generator`.
870
+ prompt_embeds (`torch.FloatTensor`, *optional*):
871
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
872
+ provided, text embeddings will be generated from `prompt` input argument.
873
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
874
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
875
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
876
+ argument.
877
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
878
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
879
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
880
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
881
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
882
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
883
+ input argument.
884
+ output_type (`str`, *optional*, defaults to `"pil"`):
885
+ The output format of the generate image. Choose between
886
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
887
+ return_dict (`bool`, *optional*, defaults to `True`):
888
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
889
+ of a plain tuple.
890
+ callback (`Callable`, *optional*):
891
+ A function that will be called every `callback_steps` steps during inference. The function will be
892
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
893
+ callback_steps (`int`, *optional*, defaults to 1):
894
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
895
+ called at every step.
896
+ cross_attention_kwargs (`dict`, *optional*):
897
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
898
+ `self.processor` in
899
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
900
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
901
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
902
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
903
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
904
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
905
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
906
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
907
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
908
+ explained in section 2.2 of
909
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
910
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
911
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
912
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
913
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
914
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
915
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
916
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
917
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
918
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
919
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
920
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
921
+ micro-conditioning as explained in section 2.2 of
922
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
923
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
924
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
925
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
926
+ micro-conditioning as explained in section 2.2 of
927
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
928
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
929
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
930
+ To negatively condition the generation process based on a target image resolution. It should be as same
931
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
932
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
933
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
934
+ ################### AccDiffusion specific parameters ####################
935
+ # We build AccDiffusion based on Demofusion pipeline (see paper: https://arxiv.org/pdf/2311.16973.pdf)
936
+ image_lr (`torch.FloatTensor`, *optional*, , defaults to None):
937
+ Low-resolution image input for upscaling.
938
+ view_batch_size (`int`, defaults to 16):
939
+ The batch size for multiple denoising paths. Typically, a larger batch size can result in higher
940
+ efficiency but comes with increased GPU memory requirements.
941
+ multi_decoder (`bool`, defaults to True):
942
+ Determine whether to use a tiled decoder. Generally, when the resolution exceeds 3072x3072,
943
+ a tiled decoder becomes necessary.
944
+ stride (`int`, defaults to 64):
945
+ The stride of moving local patches. A smaller stride is better for alleviating seam issues,
946
+ but it also introduces additional computational overhead and inference time.
947
+ cosine_scale_1 (`float`, defaults to 3):
948
+ Control the strength of skip-residual. For specific impacts, please refer to Appendix C
949
+ in the DemoFusion paper. (see paper : https://arxiv.org/pdf/2311.16973.pdf)
950
+ cosine_scale_2 (`float`, defaults to 1):
951
+ Control the strength of dilated sampling. For specific impacts, please refer to Appendix C
952
+ in the DemoFusion paper.(see paper : https://arxiv.org/pdf/2311.16973.pdf)
953
+ cosine_scale_3 (`float`, defaults to 1):
954
+ Control the strength of the gaussion filter. For specific impacts, please refer to Appendix C
955
+ in the DemoFusion paper.(see paper : https://arxiv.org/pdf/2311.16973.pdf)
956
+ sigma (`float`, defaults to 1):
957
+ The standard value of the gaussian filter.
958
+ show_image (`bool`, defaults to False):
959
+ Determine whether to show intermediate results during generation.
960
+ lowvram (`bool`, defaults to False):
961
+ Try to fit in 8 Gb of VRAM, with xformers installed.
962
+
963
+ Examples:
964
+
965
+ Returns:
966
+ a `list` with the generated images at each phase.
967
+ """
968
+
969
+ if debug :
970
+ num_inference_steps = 1
971
+
972
+ # 0. Default height and width to unet
973
+ height = height or self.default_sample_size * self.vae_scale_factor
974
+ width = width or self.default_sample_size * self.vae_scale_factor
975
+
976
+ x1_size = self.default_sample_size * self.vae_scale_factor
977
+
978
+ height_scale = height / x1_size
979
+ width_scale = width / x1_size
980
+ scale_num = int(max(height_scale, width_scale))
981
+ aspect_ratio = min(height_scale, width_scale) / max(height_scale, width_scale)
982
+
983
+ original_size = original_size or (height, width)
984
+ target_size = target_size or (height, width)
985
+
986
+ if attn_res is None:
987
+ attn_res = int(np.ceil(self.default_sample_size * self.vae_scale_factor / 32)), int(np.ceil(self.default_sample_size * self.vae_scale_factor / 32))
988
+ self.attn_res = attn_res
989
+
990
+ if lowvram:
991
+ attention_map_device = torch.device("cpu")
992
+ else:
993
+ attention_map_device = self.device
994
+
995
+ self.controller = create_controller(
996
+ prompt, cross_attention_kwargs, num_inference_steps, tokenizer=self.tokenizer, device=attention_map_device, attn_res=self.attn_res
997
+ )
998
+
999
+ if save_attention_map or use_md_prompt:
1000
+ ori_attn_processors = self.register_attention_control(self.controller) # add attention controller
1001
+
1002
+ # 1. Check inputs. Raise error if not correct
1003
+ self.check_inputs(
1004
+ prompt,
1005
+ prompt_2,
1006
+ height,
1007
+ width,
1008
+ callback_steps,
1009
+ negative_prompt,
1010
+ negative_prompt_2,
1011
+ prompt_embeds,
1012
+ negative_prompt_embeds,
1013
+ pooled_prompt_embeds,
1014
+ negative_pooled_prompt_embeds,
1015
+ num_images_per_prompt,
1016
+ )
1017
+
1018
+ # 2. Define call parameters
1019
+ if prompt is not None and isinstance(prompt, str):
1020
+ batch_size = 1
1021
+ elif prompt is not None and isinstance(prompt, list):
1022
+ batch_size = len(prompt)
1023
+ else:
1024
+ batch_size = prompt_embeds.shape[0]
1025
+
1026
+ device = self._execution_device
1027
+ self.lowvram = lowvram
1028
+ if self.lowvram:
1029
+ self.vae.cpu()
1030
+ self.unet.cpu()
1031
+ self.text_encoder.to(device)
1032
+ self.text_encoder_2.to(device)
1033
+ # image_lr.cpu()
1034
+
1035
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1036
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1037
+ # corresponds to doing no classifier free guidance.
1038
+ do_classifier_free_guidance = guidance_scale > 1.0
1039
+
1040
+ # 3. Encode input prompt
1041
+ text_encoder_lora_scale = (
1042
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1043
+ )
1044
+
1045
+ (
1046
+ prompt_embeds,
1047
+ negative_prompt_embeds,
1048
+ pooled_prompt_embeds,
1049
+ negative_pooled_prompt_embeds,
1050
+ ) = self.encode_prompt(
1051
+ prompt=prompt,
1052
+ prompt_2=prompt_2,
1053
+ device=device,
1054
+ num_images_per_prompt=num_images_per_prompt,
1055
+ do_classifier_free_guidance=do_classifier_free_guidance,
1056
+ negative_prompt=negative_prompt,
1057
+ negative_prompt_2=negative_prompt_2,
1058
+ prompt_embeds=prompt_embeds,
1059
+ negative_prompt_embeds=negative_prompt_embeds,
1060
+ pooled_prompt_embeds=pooled_prompt_embeds,
1061
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1062
+ lora_scale=text_encoder_lora_scale,
1063
+ )
1064
+
1065
+ # 4. Prepare timesteps
1066
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1067
+
1068
+ timesteps = self.scheduler.timesteps
1069
+
1070
+ # 5. Prepare latent variables
1071
+ num_channels_latents = self.unet.config.in_channels
1072
+ latents = self.prepare_latents(
1073
+ batch_size * num_images_per_prompt,
1074
+ num_channels_latents,
1075
+ height // scale_num,
1076
+ width // scale_num,
1077
+ prompt_embeds.dtype,
1078
+ device,
1079
+ generator,
1080
+ latents,
1081
+ )
1082
+
1083
+
1084
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1085
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1086
+
1087
+ # 7. Prepare added time ids & embeddings
1088
+ add_text_embeds = pooled_prompt_embeds
1089
+
1090
+ add_time_ids = self._get_add_time_ids(
1091
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
1092
+ )
1093
+
1094
+ if negative_original_size is not None and negative_target_size is not None:
1095
+ negative_add_time_ids = self._get_add_time_ids(
1096
+ negative_original_size,
1097
+ negative_crops_coords_top_left,
1098
+ negative_target_size,
1099
+ dtype=prompt_embeds.dtype,
1100
+ )
1101
+ else:
1102
+ negative_add_time_ids = add_time_ids
1103
+
1104
+ if do_classifier_free_guidance:
1105
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0).to(device)
1106
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0).to(device)
1107
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0).to(device).repeat(batch_size * num_images_per_prompt, 1)
1108
+
1109
+ del negative_prompt_embeds, negative_pooled_prompt_embeds, negative_add_time_ids
1110
+
1111
+ # 8. Denoising loop
1112
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1113
+
1114
+
1115
+ # 7.1 Apply denoising_end
1116
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
1117
+ discrete_timestep_cutoff = int(
1118
+ round(
1119
+ self.scheduler.config.num_train_timesteps
1120
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
1121
+ )
1122
+ )
1123
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1124
+ timesteps = timesteps[:num_inference_steps]
1125
+
1126
+ output_images = []
1127
+
1128
+ ###################################################### Phase Initialization ########################################################
1129
+
1130
+ if self.lowvram:
1131
+ self.text_encoder.cpu()
1132
+ self.text_encoder_2.cpu()
1133
+
1134
+ if image_lr == None:
1135
+ print("### Phase 1 Denoising ###")
1136
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1137
+ for i, t in enumerate(timesteps):
1138
+
1139
+ if self.lowvram:
1140
+ self.vae.cpu()
1141
+ self.unet.to(device)
1142
+
1143
+ latents_for_view = latents
1144
+
1145
+ # expand the latents if we are doing classifier free guidance
1146
+ latent_model_input = (
1147
+ latents.repeat_interleave(2, dim=0)
1148
+ if do_classifier_free_guidance
1149
+ else latents
1150
+ )
1151
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1152
+
1153
+ # predict the noise residual
1154
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1155
+
1156
+ noise_pred = self.unet(
1157
+ latent_model_input,
1158
+ t,
1159
+ encoder_hidden_states=prompt_embeds,
1160
+ # cross_attention_kwargs=cross_attention_kwargs,
1161
+ added_cond_kwargs=added_cond_kwargs,
1162
+ return_dict=False,
1163
+ )[0]
1164
+
1165
+ # perform guidance
1166
+ if do_classifier_free_guidance:
1167
+ noise_pred_uncond, noise_pred_text = noise_pred[::2], noise_pred[1::2]
1168
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1169
+
1170
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1171
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1172
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1173
+
1174
+ # compute the previous noisy sample x_t -> x_t-1
1175
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1176
+
1177
+ # # step callback
1178
+ # latents = self.controller.step_callback(latents)
1179
+ if t == 1 and use_md_prompt:
1180
+ # show_cross_attention(tokenizer=self.tokenizer, prompts=[prompt], attention_store=self.controller, res=self.attn_res[0], from_where=["up","down"], select=0, t=int(t))
1181
+ md_prompts, views_attention = get_multidiffusion_prompts(tokenizer=self.tokenizer, prompts=[prompt], threthod=c,attention_store=self.controller, height=height//scale_num, width =width//scale_num, from_where=["up","down"], random_jitter=True, scale_num=scale_num)
1182
+
1183
+ # call the callback, if provided
1184
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1185
+ progress_bar.update()
1186
+ if callback is not None and i % callback_steps == 0:
1187
+ step_idx = i // getattr(self.scheduler, "order", 1)
1188
+ callback(step_idx, t, latents)
1189
+
1190
+ del latents_for_view, latent_model_input, noise_pred, noise_pred_text, noise_pred_uncond
1191
+ if use_md_prompt or save_attention_map:
1192
+ self.recover_attention_control(ori_attn_processors=ori_attn_processors) # recover attention controller
1193
+ del self.controller
1194
+ torch.cuda.empty_cache()
1195
+ else:
1196
+ print("### Encoding Real Image ###")
1197
+ latents = self.vae.encode(image_lr)
1198
+ latents = latents.latent_dist.sample() * self.vae.config.scaling_factor
1199
+
1200
+ anchor_mean = latents.mean()
1201
+ anchor_std = latents.std()
1202
+ if self.lowvram:
1203
+ latents = latents.cpu()
1204
+ torch.cuda.empty_cache()
1205
+ if not output_type == "latent":
1206
+ # make sure the VAE is in float32 mode, as it overflows in float16
1207
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1208
+
1209
+ if self.lowvram:
1210
+ needs_upcasting = False # use madebyollin/sdxl-vae-fp16-fix in lowvram mode!
1211
+ self.unet.cpu()
1212
+ self.vae.to(device)
1213
+
1214
+ if needs_upcasting:
1215
+ self.upcast_vae()
1216
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1217
+ if self.lowvram and multi_decoder:
1218
+ current_width_height = self.unet.config.sample_size * self.vae_scale_factor
1219
+ image = self.tiled_decode(latents, current_width_height, current_width_height)
1220
+ else:
1221
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1222
+ # cast back to fp16 if needed
1223
+ if needs_upcasting:
1224
+ self.vae.to(dtype=torch.float16)
1225
+ torch.cuda.empty_cache()
1226
+
1227
+ image = self.image_processor.postprocess(image, output_type=output_type)
1228
+ if not os.path.exists(f'{result_path}'):
1229
+ os.makedirs(f'{result_path}')
1230
+
1231
+ image_lr_save_path = f'{result_path}/{image[0].size[0]}_{image[0].size[1]}.png'
1232
+ image[0].save(image_lr_save_path)
1233
+ output_images.append(image[0])
1234
+
1235
+ ####################################################### Phase Upscaling #####################################################
1236
+ if use_progressive_upscaling:
1237
+ if image_lr == None:
1238
+ starting_scale = 2
1239
+ else:
1240
+ starting_scale = 1
1241
+ else:
1242
+ starting_scale = scale_num
1243
+
1244
+ for current_scale_num in range(starting_scale, scale_num + 1):
1245
+ if self.lowvram:
1246
+ latents = latents.to(device)
1247
+ self.unet.to(device)
1248
+ torch.cuda.empty_cache()
1249
+
1250
+ current_height = self.unet.config.sample_size * self.vae_scale_factor * current_scale_num
1251
+ current_width = self.unet.config.sample_size * self.vae_scale_factor * current_scale_num
1252
+
1253
+ if height > width:
1254
+ current_width = int(current_width * aspect_ratio)
1255
+ else:
1256
+ current_height = int(current_height * aspect_ratio)
1257
+
1258
+
1259
+ if upscale_mode == "bicubic_latent" or debug:
1260
+ latents = F.interpolate(latents.to(device), size=(int(current_height / self.vae_scale_factor), int(current_width / self.vae_scale_factor)), mode='bicubic')
1261
+ else:
1262
+ raise NotImplementedError
1263
+
1264
+ print("### Phase {} Denoising ###".format(current_scale_num))
1265
+ ############################################# noise inverse #############################################
1266
+ noise_latents = []
1267
+ noise = torch.randn_like(latents)
1268
+ for timestep in timesteps:
1269
+ noise_latent = self.scheduler.add_noise(latents, noise, timestep.unsqueeze(0))
1270
+ noise_latents.append(noise_latent)
1271
+ latents = noise_latents[0]
1272
+
1273
+ ############################################# denoise #############################################
1274
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1275
+ for i, t in enumerate(timesteps):
1276
+ count = torch.zeros_like(latents)
1277
+ value = torch.zeros_like(latents)
1278
+ cosine_factor = 0.5 * (1 + torch.cos(torch.pi * (self.scheduler.config.num_train_timesteps - t) / self.scheduler.config.num_train_timesteps)).cpu()
1279
+ if use_skip_residual:
1280
+ c1 = cosine_factor ** cosine_scale_1
1281
+ latents = latents * (1 - c1) + noise_latents[i] * c1
1282
+
1283
+ if use_multidiffusion:
1284
+ ############################################# MultiDiffusion #############################################
1285
+ if use_md_prompt:
1286
+ md_prompt_embeds_list = []
1287
+ md_add_text_embeds_list = []
1288
+ for md_prompt in md_prompts[current_scale_num]:
1289
+ (
1290
+ md_prompt_embeds,
1291
+ md_negative_prompt_embeds,
1292
+ md_pooled_prompt_embeds,
1293
+ md_negative_pooled_prompt_embeds,
1294
+ ) = self.encode_prompt(
1295
+ prompt=md_prompt,
1296
+ prompt_2=prompt_2,
1297
+ device=device,
1298
+ num_images_per_prompt=num_images_per_prompt,
1299
+ do_classifier_free_guidance=do_classifier_free_guidance,
1300
+ negative_prompt=negative_prompt,
1301
+ negative_prompt_2=negative_prompt_2,
1302
+ prompt_embeds=None,
1303
+ negative_prompt_embeds=None,
1304
+ pooled_prompt_embeds=None,
1305
+ negative_pooled_prompt_embeds=None,
1306
+ lora_scale=text_encoder_lora_scale,
1307
+ )
1308
+ md_prompt_embeds_list.append(torch.cat([md_negative_prompt_embeds, md_prompt_embeds], dim=0).to(device))
1309
+ md_add_text_embeds_list.append(torch.cat([md_negative_pooled_prompt_embeds, md_pooled_prompt_embeds], dim=0).to(device))
1310
+ del md_negative_prompt_embeds, md_negative_pooled_prompt_embeds
1311
+
1312
+ if use_md_prompt:
1313
+ random_jitter = True
1314
+ views = [(h_start*4, h_end*4, w_start*4, w_end*4) for h_start, h_end, w_start, w_end in views_attention[current_scale_num]]
1315
+ else:
1316
+ random_jitter = True
1317
+ views = self.get_views(current_height, current_width, stride=stride, window_size=self.unet.config.sample_size, random_jitter=random_jitter)
1318
+
1319
+ views_batch = [views[i : i + view_batch_size] for i in range(0, len(views), view_batch_size)]
1320
+
1321
+ if use_md_prompt:
1322
+ views_prompt_embeds_input = [md_prompt_embeds_list[i : i + view_batch_size] for i in range(0, len(views), view_batch_size)]
1323
+ views_add_text_embeds_input = [md_add_text_embeds_list[i : i + view_batch_size] for i in range(0, len(views), view_batch_size)]
1324
+
1325
+ if random_jitter:
1326
+ jitter_range = int((self.unet.config.sample_size - stride) // 4)
1327
+ latents_ = F.pad(latents, (jitter_range, jitter_range, jitter_range, jitter_range), 'constant', 0)
1328
+ else:
1329
+ latents_ = latents
1330
+
1331
+ count_local = torch.zeros_like(latents_)
1332
+ value_local = torch.zeros_like(latents_)
1333
+
1334
+ for j, batch_view in enumerate(views_batch):
1335
+ vb_size = len(batch_view)
1336
+ # get the latents corresponding to the current view coordinates
1337
+ latents_for_view = torch.cat(
1338
+ [
1339
+ latents_[:, :, h_start:h_end, w_start:w_end]
1340
+ for h_start, h_end, w_start, w_end in batch_view
1341
+ ]
1342
+ )
1343
+
1344
+ # expand the latents if we are doing classifier free guidance
1345
+ latent_model_input = latents_for_view
1346
+ latent_model_input = (
1347
+ latent_model_input.repeat_interleave(2, dim=0)
1348
+ if do_classifier_free_guidance
1349
+ else latent_model_input
1350
+ )
1351
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1352
+
1353
+ add_time_ids_input = []
1354
+ for h_start, h_end, w_start, w_end in batch_view:
1355
+ add_time_ids_ = add_time_ids.clone()
1356
+ add_time_ids_[:, 2] = h_start * self.vae_scale_factor
1357
+ add_time_ids_[:, 3] = w_start * self.vae_scale_factor
1358
+ add_time_ids_input.append(add_time_ids_)
1359
+ add_time_ids_input = torch.cat(add_time_ids_input)
1360
+
1361
+ if not use_md_prompt:
1362
+ prompt_embeds_input = torch.cat([prompt_embeds] * vb_size)
1363
+ add_text_embeds_input = torch.cat([add_text_embeds] * vb_size)
1364
+ # predict the noise residual
1365
+ added_cond_kwargs = {"text_embeds": add_text_embeds_input, "time_ids": add_time_ids_input}
1366
+ noise_pred = self.unet(
1367
+ latent_model_input,
1368
+ t,
1369
+ encoder_hidden_states=prompt_embeds_input,
1370
+ # cross_attention_kwargs=cross_attention_kwargs,
1371
+ added_cond_kwargs=added_cond_kwargs,
1372
+ return_dict=False,
1373
+ )[0]
1374
+ else:
1375
+ md_prompt_embeds_input = torch.cat(views_prompt_embeds_input[j])
1376
+ md_add_text_embeds_input = torch.cat(views_add_text_embeds_input[j])
1377
+ md_added_cond_kwargs = {"text_embeds": md_add_text_embeds_input, "time_ids": add_time_ids_input}
1378
+ noise_pred = self.unet(
1379
+ latent_model_input,
1380
+ t,
1381
+ encoder_hidden_states=md_prompt_embeds_input,
1382
+ # cross_attention_kwargs=cross_attention_kwargs,
1383
+ added_cond_kwargs=md_added_cond_kwargs,
1384
+ return_dict=False,
1385
+ )[0]
1386
+
1387
+ if do_classifier_free_guidance:
1388
+ noise_pred_uncond, noise_pred_text = noise_pred[::2], noise_pred[1::2]
1389
+ noise_pred = noise_pred_uncond + multi_guidance_scale * (noise_pred_text - noise_pred_uncond)
1390
+
1391
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1392
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1393
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1394
+
1395
+ # compute the previous noisy sample x_t -> x_t-1
1396
+ self.scheduler._init_step_index(t)
1397
+ latents_denoised_batch = self.scheduler.step(
1398
+ noise_pred, t, latents_for_view, **extra_step_kwargs, return_dict=False)[0]
1399
+
1400
+ # extract value from batch
1401
+ for latents_view_denoised, (h_start, h_end, w_start, w_end) in zip(
1402
+ latents_denoised_batch.chunk(vb_size), batch_view
1403
+ ):
1404
+ value_local[:, :, h_start:h_end, w_start:w_end] += latents_view_denoised
1405
+ count_local[:, :, h_start:h_end, w_start:w_end] += 1
1406
+
1407
+ if random_jitter:
1408
+ value_local = value_local[: ,:, jitter_range: jitter_range + current_height // self.vae_scale_factor, jitter_range: jitter_range + current_width // self.vae_scale_factor]
1409
+ count_local = count_local[: ,:, jitter_range: jitter_range + current_height // self.vae_scale_factor, jitter_range: jitter_range + current_width // self.vae_scale_factor]
1410
+
1411
+ if i != (len(timesteps) - 1):
1412
+ noise_index = i + 1
1413
+ else:
1414
+ noise_index = i
1415
+
1416
+ value_local = torch.where(count_local == 0, noise_latents[noise_index], value_local)
1417
+ count_local = torch.where(count_local == 0, torch.ones_like(count_local), count_local)
1418
+ if use_dilated_sampling:
1419
+ c2 = cosine_factor ** cosine_scale_2
1420
+ value += value_local / count_local * (1 - c2)
1421
+ count += torch.ones_like(value_local) * (1 - c2)
1422
+ else:
1423
+ value += value_local / count_local
1424
+ count += torch.ones_like(value_local)
1425
+
1426
+ if use_dilated_sampling:
1427
+ ############################################# Dilated Sampling #############################################
1428
+ views = [[h, w] for h in range(current_scale_num) for w in range(current_scale_num)]
1429
+ views_batch = [views[i : i + view_batch_size] for i in range(0, len(views), view_batch_size)]
1430
+
1431
+ h_pad = (current_scale_num - (latents.size(2) % current_scale_num)) % current_scale_num
1432
+ w_pad = (current_scale_num - (latents.size(3) % current_scale_num)) % current_scale_num
1433
+ latents_ = F.pad(latents, (w_pad, 0, h_pad, 0), 'constant', 0)
1434
+
1435
+ count_global = torch.zeros_like(latents_)
1436
+ value_global = torch.zeros_like(latents_)
1437
+
1438
+ if use_guassian:
1439
+ c3 = 0.99 * cosine_factor ** cosine_scale_3 + 1e-2
1440
+ std_, mean_ = latents_.std(), latents_.mean()
1441
+ latents_gaussian = gaussian_filter(latents_, kernel_size=(2*current_scale_num-1), sigma=sigma*c3)
1442
+ latents_gaussian = (latents_gaussian - latents_gaussian.mean()) / latents_gaussian.std() * std_ + mean_
1443
+ else:
1444
+ latents_gaussian = latents_
1445
+
1446
+ for j, batch_view in enumerate(views_batch):
1447
+
1448
+ latents_for_view = torch.cat(
1449
+ [
1450
+ latents_[:, :, h::current_scale_num, w::current_scale_num]
1451
+ for h, w in batch_view
1452
+ ]
1453
+ )
1454
+
1455
+ latents_for_view_gaussian = torch.cat(
1456
+ [
1457
+ latents_gaussian[:, :, h::current_scale_num, w::current_scale_num]
1458
+ for h, w in batch_view
1459
+ ]
1460
+ )
1461
+
1462
+ if shuffle:
1463
+ ######## window interaction ########
1464
+ shape = latents_for_view.shape
1465
+ shuffle_index = torch.stack([torch.randperm(shape[0]) for _ in range(latents_for_view.reshape(-1).shape[0]//shape[0])])
1466
+
1467
+ shuffle_index = shuffle_index.view(shape[1],shape[2],shape[3],shape[0])
1468
+ original_index = torch.zeros_like(shuffle_index).scatter_(3, shuffle_index, torch.arange(shape[0]).repeat(shape[1], shape[2], shape[3], 1))
1469
+
1470
+ shuffle_index = shuffle_index.permute(3,0,1,2).to(device)
1471
+ original_index = original_index.permute(3,0,1,2).to(device)
1472
+ latents_for_view_gaussian = latents_for_view_gaussian.gather(0, shuffle_index)
1473
+
1474
+ vb_size = latents_for_view.size(0)
1475
+
1476
+ # expand the latents if we are doing classifier free guidance
1477
+ latent_model_input = latents_for_view_gaussian
1478
+ latent_model_input = (
1479
+ latent_model_input.repeat_interleave(2, dim=0)
1480
+ if do_classifier_free_guidance
1481
+ else latent_model_input
1482
+ )
1483
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1484
+
1485
+ prompt_embeds_input = torch.cat([prompt_embeds] * vb_size)
1486
+ add_text_embeds_input = torch.cat([add_text_embeds] * vb_size)
1487
+ add_time_ids_input = torch.cat([add_time_ids] * vb_size)
1488
+
1489
+ # predict the noise residual
1490
+ added_cond_kwargs = {"text_embeds": add_text_embeds_input, "time_ids": add_time_ids_input}
1491
+ noise_pred = self.unet(
1492
+ latent_model_input,
1493
+ t,
1494
+ encoder_hidden_states=prompt_embeds_input,
1495
+ # cross_attention_kwargs=cross_attention_kwargs,
1496
+ added_cond_kwargs=added_cond_kwargs,
1497
+ return_dict=False,
1498
+ )[0]
1499
+
1500
+ if do_classifier_free_guidance:
1501
+ noise_pred_uncond, noise_pred_text = noise_pred[::2], noise_pred[1::2]
1502
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1503
+
1504
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1505
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1506
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1507
+
1508
+ if shuffle:
1509
+ ## recover
1510
+ noise_pred = noise_pred.gather(0, original_index)
1511
+
1512
+ # compute the previous noisy sample x_t -> x_t-1
1513
+ self.scheduler._init_step_index(t)
1514
+ latents_denoised_batch = self.scheduler.step(noise_pred, t, latents_for_view, **extra_step_kwargs, return_dict=False)[0]
1515
+
1516
+ # extract value from batch
1517
+ for latents_view_denoised, (h, w) in zip(
1518
+ latents_denoised_batch.chunk(vb_size), batch_view
1519
+ ):
1520
+ value_global[:, :, h::current_scale_num, w::current_scale_num] += latents_view_denoised
1521
+ count_global[:, :, h::current_scale_num, w::current_scale_num] += 1
1522
+
1523
+ value_global = value_global[: ,:, h_pad:, w_pad:]
1524
+
1525
+ if use_multidiffusion:
1526
+ c2 = cosine_factor ** cosine_scale_2
1527
+ value += value_global * c2
1528
+ count += torch.ones_like(value_global) * c2
1529
+ else:
1530
+ value += value_global
1531
+ count += torch.ones_like(value_global)
1532
+
1533
+ latents = torch.where(count > 0, value / count, value)
1534
+
1535
+ # call the callback, if provided
1536
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1537
+ progress_bar.update()
1538
+ if callback is not None and i % callback_steps == 0:
1539
+ step_idx = i // getattr(self.scheduler, "order", 1)
1540
+ callback(step_idx, t, latents)
1541
+
1542
+ #########################################################################################################################################
1543
+
1544
+ latents = (latents - latents.mean()) / latents.std() * anchor_std + anchor_mean
1545
+ if self.lowvram:
1546
+ latents = latents.cpu()
1547
+ torch.cuda.empty_cache()
1548
+ if not output_type == "latent":
1549
+ # make sure the VAE is in float32 mode, as it overflows in float16
1550
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1551
+ if self.lowvram:
1552
+ needs_upcasting = False # use madebyollin/sdxl-vae-fp16-fix in lowvram mode!
1553
+ self.unet.cpu()
1554
+ self.vae.to(device)
1555
+
1556
+ if needs_upcasting:
1557
+ self.upcast_vae()
1558
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1559
+
1560
+ print("### Phase {} Decoding ###".format(current_scale_num))
1561
+ if current_height > 2048 or current_width > 2048:
1562
+ # image = self.tiled_decode(latents, current_height, current_width)
1563
+ self.enable_vae_tiling()
1564
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1565
+ else:
1566
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1567
+
1568
+ image = self.image_processor.postprocess(image, output_type=output_type)
1569
+ image[0].save(f'{result_path}/AccDiffusion_{current_scale_num}.png')
1570
+
1571
+ output_images.append(image[0])
1572
+
1573
+ # cast back to fp16 if needed
1574
+ if needs_upcasting:
1575
+ self.vae.to(dtype=torch.float16)
1576
+ else:
1577
+ image = latents
1578
+
1579
+ # Offload all models
1580
+ self.maybe_free_model_hooks()
1581
+
1582
+ return output_images
1583
+
1584
+
1585
+ if __name__ == "__main__":
1586
+ parser = argparse.ArgumentParser()
1587
+ ### AccDiffusion PARAMETERS ###
1588
+ parser.add_argument('--model_ckpt',default='stabilityai/stable-diffusion-xl-base-1.0')
1589
+ parser.add_argument('--seed', type=int, default=42)
1590
+ parser.add_argument('--prompt', default="Astronaut on Mars During sunset.")
1591
+ parser.add_argument('--negative_prompt', default="blurry, ugly, duplicate, poorly drawn, deformed, mosaic")
1592
+ parser.add_argument('--cosine_scale_1', default=3, type=float, help="cosine scale 1")
1593
+ parser.add_argument('--cosine_scale_2', default=1, type=float, help="cosine scale 2")
1594
+ parser.add_argument('--cosine_scale_3', default=1, type=float, help="cosine scale 3")
1595
+ parser.add_argument('--sigma', default=0.8, type=float, help="sigma")
1596
+ parser.add_argument('--multi_decoder', default=True, type=bool, help="multi decoder or not")
1597
+ parser.add_argument('--num_inference_steps', default=50, type=int, help="num inference steps")
1598
+ parser.add_argument('--resolution', default='1024,1024', help="target resolution")
1599
+ parser.add_argument('--use_multidiffusion', default=False, action='store_true', help="use multidiffusion or not")
1600
+ parser.add_argument('--use_guassian', default=False, action='store_true', help="use guassian or not")
1601
+ parser.add_argument('--use_dilated_sampling', default=False, action='store_true', help="use dilated sampling or not")
1602
+ parser.add_argument('--use_progressive_upscaling', default=False, action='store_true', help="use progressive upscaling or not")
1603
+ parser.add_argument('--shuffle', default=False, action='store_true', help="shuffle or not")
1604
+ parser.add_argument('--use_skip_residual', default=False, action='store_true', help="use skip_residual or not")
1605
+ parser.add_argument('--save_attention_map', default=False, action='store_true', help="save attention map or not")
1606
+ parser.add_argument('--multi_guidance_scale', default=7.5, type=float, help="multi guidance scale")
1607
+ parser.add_argument('--upscale_mode', default="bicubic_latent", help="bicubic_image or bicubic_latent ")
1608
+ parser.add_argument('--use_md_prompt', default=False, action='store_true', help="use md prompt or not")
1609
+ parser.add_argument('--view_batch_size', default=16, type=int, help="view_batch_size")
1610
+ parser.add_argument('--stride', default=64, type=int, help="stride")
1611
+ parser.add_argument('--c', default=0.3, type=float, help="threshold")
1612
+ ## others ##
1613
+ parser.add_argument('--debug', default=False, action='store_true')
1614
+ parser.add_argument('--experiment_name', default="AccDiffusion")
1615
+
1616
+ args = parser.parse_args()
1617
+
1618
+
1619
+ set_seed(args.seed)
1620
+ width,height = list(map(int, args.resolution.split(',')))
1621
+ pipe = AccDiffusionSDXLPipeline.from_pretrained(args.model_ckpt, torch_dtype=torch.float16).to("cuda")
1622
+ generator = torch.Generator(device='cuda')
1623
+ generator = generator.manual_seed(args.seed)
1624
+ cross_attention_kwargs = {"edit_type": "visualize",
1625
+ "n_self_replace": 0.4,
1626
+ "n_cross_replace": {"default_": 1.0, "confetti": 0.8},
1627
+ }
1628
+
1629
+ if os.path.isfile(args.prompt):
1630
+ with open(args.prompt, "r") as file:
1631
+ prompts = file.read().strip()
1632
+ prompts = prompts.split("\n")
1633
+ else:
1634
+ prompts = [args.prompt]
1635
+
1636
+ seed = args.seed
1637
+ generator = generator.manual_seed(seed)
1638
+ for prompt in tqdm(prompts):
1639
+ print(f"Prompt: {prompt}")
1640
+ images = pipe(prompt, negative_prompt=args.negative_prompt, generator=generator,
1641
+ width=width, height=height, view_batch_size=args.view_batch_size, stride=args.stride,
1642
+ cross_attention_kwargs=cross_attention_kwargs,
1643
+ num_inference_steps=args.num_inference_steps,
1644
+ guidance_scale = 7.5, multi_guidance_scale = args.multi_guidance_scale,
1645
+ cosine_scale_1=args.cosine_scale_1, cosine_scale_2=args.cosine_scale_2, cosine_scale_3=args.cosine_scale_3,
1646
+ sigma=args.sigma, use_guassian=args.use_guassian,
1647
+ multi_decoder=args.multi_decoder,
1648
+ upscale_mode=args.upscale_mode, use_multidiffusion=args.use_multidiffusion,
1649
+ use_skip_residual=args.use_skip_residual, use_progressive_upscaling=args.use_progressive_upscaling,
1650
+ use_dilated_sampling=args.use_dilated_sampling,
1651
+ shuffle=args.shuffle, result_path=f"./output/{args.experiment_name}/{prompt}/{width}_{height}_{seed}/",
1652
+ debug=args.debug, save_attention_map=args.save_attention_map, use_md_prompt=args.use_md_prompt, c=args.c
1653
+ )
1654
+
1655
+
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diffusers~=0.21.4
2
+ torch~=2.1.0
3
+ scipy~=1.11.3
4
+ omegaconf~=2.3.0
5
+ accelerate~=0.23.0
6
+ transformers~=4.34.0
7
+ tqdm
8
+ einops
9
+ matplotlib
10
+ gradio
11
+ gradio_imageslider
12
+ opencv-python
13
+ torchvision
utils.py ADDED
@@ -0,0 +1,885 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import os
3
+ import cv2
4
+ import abc
5
+ from typing import Dict, List, Optional, Tuple, Union
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from diffusers.models.attention import Attention
10
+ from PIL import Image
11
+ import random
12
+ import matplotlib.pyplot as plt
13
+ import pdb
14
+ import math
15
+ from PIL import Image
16
+
17
+
18
+
19
+ class P2PCrossAttnProcessor:
20
+ def __init__(self, controller, place_in_unet):
21
+ super().__init__()
22
+ self.controller = controller
23
+ self.place_in_unet = place_in_unet
24
+
25
+ def __call__(self, attn: Attention, hidden_states, encoder_hidden_states=None, attention_mask=None):
26
+ batch_size, sequence_length, _ = hidden_states.shape
27
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
28
+
29
+ query = attn.to_q(hidden_states)
30
+
31
+ is_cross = encoder_hidden_states is not None
32
+ encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
33
+ key = attn.to_k(encoder_hidden_states)
34
+ value = attn.to_v(encoder_hidden_states)
35
+
36
+ query = attn.head_to_batch_dim(query)
37
+ key = attn.head_to_batch_dim(key)
38
+ value = attn.head_to_batch_dim(value)
39
+
40
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
41
+
42
+ # one line change
43
+ self.controller(attention_probs, is_cross, self.place_in_unet)
44
+
45
+ hidden_states = torch.bmm(attention_probs, value)
46
+ hidden_states = attn.batch_to_head_dim(hidden_states)
47
+
48
+ # linear proj
49
+ hidden_states = attn.to_out[0](hidden_states)
50
+ # dropout
51
+ hidden_states = attn.to_out[1](hidden_states)
52
+
53
+ return hidden_states
54
+
55
+
56
+ def create_controller(
57
+ prompts: List[str], cross_attention_kwargs: Dict, num_inference_steps: int, tokenizer, device, attn_res
58
+ ) -> AttentionControl:
59
+ edit_type = cross_attention_kwargs.get("edit_type", None)
60
+ local_blend_words = cross_attention_kwargs.get("local_blend_words", None)
61
+ equalizer_words = cross_attention_kwargs.get("equalizer_words", None)
62
+ equalizer_strengths = cross_attention_kwargs.get("equalizer_strengths", None)
63
+ n_cross_replace = cross_attention_kwargs.get("n_cross_replace", 0.4)
64
+ n_self_replace = cross_attention_kwargs.get("n_self_replace", 0.4)
65
+
66
+ if edit_type == 'visualize':
67
+ return AttentionStore(device=device)
68
+
69
+ # only replace
70
+ if edit_type == "replace" and local_blend_words is None:
71
+ return AttentionReplace(
72
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, tokenizer=tokenizer, device=device, attn_res=attn_res
73
+ )
74
+
75
+ # replace + localblend
76
+ if edit_type == "replace" and local_blend_words is not None:
77
+ lb = LocalBlend(prompts, local_blend_words, tokenizer=tokenizer, device=device, attn_res=attn_res)
78
+ return AttentionReplace(
79
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, lb, tokenizer=tokenizer, device=device, attn_res=attn_res
80
+ )
81
+
82
+ # only refine
83
+ if edit_type == "refine" and local_blend_words is None:
84
+ return AttentionRefine(
85
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, tokenizer=tokenizer, device=device, attn_res=attn_res
86
+ )
87
+
88
+ # refine + localblend
89
+ if edit_type == "refine" and local_blend_words is not None:
90
+ lb = LocalBlend(prompts, local_blend_words, tokenizer=tokenizer, device=device, attn_res=attn_res)
91
+ return AttentionRefine(
92
+ prompts, num_inference_steps, n_cross_replace, n_self_replace, lb, tokenizer=tokenizer, device=device, attn_res=attn_res
93
+ )
94
+
95
+ # only reweight
96
+ if edit_type == "reweight" and local_blend_words is None:
97
+ assert (
98
+ equalizer_words is not None and equalizer_strengths is not None
99
+ ), "To use reweight edit, please specify equalizer_words and equalizer_strengths."
100
+ assert len(equalizer_words) == len(
101
+ equalizer_strengths
102
+ ), "equalizer_words and equalizer_strengths must be of same length."
103
+ equalizer = get_equalizer(prompts[1], equalizer_words, equalizer_strengths, tokenizer=tokenizer)
104
+ return AttentionReweight(
105
+ prompts,
106
+ num_inference_steps,
107
+ n_cross_replace,
108
+ n_self_replace,
109
+ tokenizer=tokenizer,
110
+ device=device,
111
+ equalizer=equalizer,
112
+ attn_res=attn_res,
113
+ )
114
+
115
+ # reweight and localblend
116
+ if edit_type == "reweight" and local_blend_words:
117
+ assert (
118
+ equalizer_words is not None and equalizer_strengths is not None
119
+ ), "To use reweight edit, please specify equalizer_words and equalizer_strengths."
120
+ assert len(equalizer_words) == len(
121
+ equalizer_strengths
122
+ ), "equalizer_words and equalizer_strengths must be of same length."
123
+ equalizer = get_equalizer(prompts[1], equalizer_words, equalizer_strengths, tokenizer=tokenizer)
124
+ lb = LocalBlend(prompts, local_blend_words, tokenizer=tokenizer, device=device, attn_res=attn_res)
125
+ return AttentionReweight(
126
+ prompts,
127
+ num_inference_steps,
128
+ n_cross_replace,
129
+ n_self_replace,
130
+ tokenizer=tokenizer,
131
+ device=device,
132
+ equalizer=equalizer,
133
+ attn_res=attn_res,
134
+ local_blend=lb,
135
+ )
136
+
137
+ raise ValueError(f"Edit type {edit_type} not recognized. Use one of: replace, refine, reweight.")
138
+
139
+
140
+ class AttentionControl(abc.ABC):
141
+ def step_callback(self, x_t):
142
+ return x_t
143
+
144
+ def between_steps(self):
145
+ return
146
+
147
+ @property
148
+ def num_uncond_att_layers(self):
149
+ return 0
150
+
151
+ @abc.abstractmethod
152
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
153
+ raise NotImplementedError
154
+
155
+ def __call__(self, attn, is_cross: bool, place_in_unet: str):
156
+ if self.cur_att_layer >= self.num_uncond_att_layers:
157
+ h = attn.shape[0]
158
+ attn[h // 2 :] = self.forward(attn[h // 2 :], is_cross, place_in_unet)
159
+ self.cur_att_layer += 1
160
+ if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
161
+ self.cur_att_layer = 0
162
+ self.cur_step += 1
163
+ self.between_steps()
164
+ return attn
165
+
166
+ def reset(self):
167
+ self.cur_step = 0
168
+ self.cur_att_layer = 0
169
+
170
+ def __init__(self, attn_res=None):
171
+ self.cur_step = 0
172
+ self.num_att_layers = -1
173
+ self.cur_att_layer = 0
174
+ self.attn_res = attn_res
175
+
176
+
177
+
178
+ class EmptyControl(AttentionControl):
179
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
180
+ return attn
181
+
182
+
183
+ class AttentionStore(AttentionControl):
184
+ @staticmethod
185
+ def get_empty_store():
186
+ return {"down_cross": [], "mid_cross": [], "up_cross": [], "down_self": [], "mid_self": [], "up_self": []}
187
+
188
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
189
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
190
+ if attn.shape[1] <= 32**2: # avoid memory overhead
191
+ if self.device.type != 'cuda':
192
+ attn = attn.cpu()
193
+ self.step_store[key].append(attn)
194
+ return attn
195
+
196
+ def between_steps(self):
197
+ if len(self.attention_store) == 0:
198
+ self.attention_store = self.step_store
199
+ else:
200
+ for key in self.attention_store:
201
+ for i in range(len(self.attention_store[key])):
202
+ self.attention_store[key][i] += self.step_store[key][i]
203
+ self.step_store = self.get_empty_store()
204
+
205
+ def get_average_attention(self):
206
+ average_attention = {
207
+ key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store
208
+ }
209
+ return average_attention
210
+
211
+ def reset(self):
212
+ super(AttentionStore, self).reset()
213
+ self.step_store = self.get_empty_store()
214
+ self.attention_store = {}
215
+
216
+ def __init__(self, attn_res=None, device='cuda'):
217
+ super(AttentionStore, self).__init__(attn_res)
218
+ self.step_store = self.get_empty_store()
219
+ self.attention_store = {}
220
+ self.device = device
221
+
222
+
223
+
224
+ class LocalBlend:
225
+ def __call__(self, x_t, attention_store):
226
+ # note that this code works on the latent level!
227
+ k = 1
228
+ # maps = attention_store["down_cross"][2:4] + attention_store["up_cross"][:3] # These are the numbers because we want to take layers that are 256 x 256, I think this can be changed to something smarter...like, get all attentions where thesecond dim is self.attn_res[0] * self.attn_res[1] in up and down cross.
229
+ maps = [m for m in attention_store["down_cross"] + attention_store["mid_cross"] + attention_store["up_cross"] if m.shape[1] == self.attn_res[0] * self.attn_res[1]]
230
+ maps = [item.reshape(self.alpha_layers.shape[0], -1, 1, self.attn_res[0], self.attn_res[1], self.max_num_words) for item in maps]
231
+ maps = torch.cat(maps, dim=1)
232
+ maps = (maps * self.alpha_layers).sum(-1).mean(1) # since alpha_layers is all 0s except where we edit, the product zeroes out all but what we change. Then, the sum adds the values of the original and what we edit. Then, we average across dim=1, which is the number of layers.
233
+ mask = F.max_pool2d(maps, (k * 2 + 1, k * 2 + 1), (1, 1), padding=(k, k))
234
+ mask = F.interpolate(mask, size=(x_t.shape[2:]))
235
+ mask = mask / mask.max(2, keepdims=True)[0].max(3, keepdims=True)[0]
236
+ mask = mask.gt(self.threshold)
237
+
238
+ mask = mask[:1] + mask[1:]
239
+ mask = mask.to(torch.float16)
240
+
241
+ x_t = x_t[:1] + mask * (x_t - x_t[:1]) # x_t[:1] is the original image. mask*(x_t - x_t[:1]) zeroes out the original image and removes the difference between the original and each image we are generating (mostly just one). Then, it applies the mask on the image. That is, it's only keeping the cells we want to generate.
242
+ return x_t
243
+
244
+ def __init__(
245
+ self, prompts: List[str], words: [List[List[str]]], tokenizer, device, threshold=0.3, attn_res=None
246
+ ):
247
+ self.max_num_words = 77
248
+ self.attn_res = attn_res
249
+
250
+ alpha_layers = torch.zeros(len(prompts), 1, 1, 1, 1, self.max_num_words)
251
+ for i, (prompt, words_) in enumerate(zip(prompts, words)):
252
+ if isinstance(words_, str):
253
+ words_ = [words_]
254
+ for word in words_:
255
+ ind = get_word_inds(prompt, word, tokenizer)
256
+ alpha_layers[i, :, :, :, :, ind] = 1
257
+ self.alpha_layers = alpha_layers.to(device) # a one-hot vector where the 1s are the words we modify (source and target)
258
+ self.threshold = threshold
259
+
260
+
261
+ class AttentionControlEdit(AttentionStore, abc.ABC):
262
+ def step_callback(self, x_t):
263
+ if self.local_blend is not None:
264
+ x_t = self.local_blend(x_t, self.attention_store)
265
+ return x_t
266
+
267
+ def replace_self_attention(self, attn_base, att_replace):
268
+ if att_replace.shape[2] <= self.attn_res[0]**2:
269
+ return attn_base.unsqueeze(0).expand(att_replace.shape[0], *attn_base.shape)
270
+ else:
271
+ return att_replace
272
+
273
+ @abc.abstractmethod
274
+ def replace_cross_attention(self, attn_base, att_replace):
275
+ raise NotImplementedError
276
+
277
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
278
+ super(AttentionControlEdit, self).forward(attn, is_cross, place_in_unet)
279
+ if is_cross or (self.num_self_replace[0] <= self.cur_step < self.num_self_replace[1]):
280
+ h = attn.shape[0] // (self.batch_size)
281
+ attn = attn.reshape(self.batch_size, h, *attn.shape[1:])
282
+ attn_base, attn_replace = attn[0], attn[1:]
283
+ if is_cross:
284
+ alpha_words = self.cross_replace_alpha[self.cur_step]
285
+ attn_replace_new = (
286
+ self.replace_cross_attention(attn_base, attn_replace) * alpha_words
287
+ + (1 - alpha_words) * attn_replace
288
+ )
289
+ attn[1:] = attn_replace_new
290
+ else:
291
+ attn[1:] = self.replace_self_attention(attn_base, attn_replace)
292
+ attn = attn.reshape(self.batch_size * h, *attn.shape[2:])
293
+ return attn
294
+
295
+ def __init__(
296
+ self,
297
+ prompts,
298
+ num_steps: int,
299
+ cross_replace_steps: Union[float, Tuple[float, float], Dict[str, Tuple[float, float]]],
300
+ self_replace_steps: Union[float, Tuple[float, float]],
301
+ local_blend: Optional[LocalBlend],
302
+ tokenizer,
303
+ device,
304
+ attn_res=None,
305
+ ):
306
+ super(AttentionControlEdit, self).__init__(attn_res=attn_res)
307
+ # add tokenizer and device here
308
+
309
+ self.tokenizer = tokenizer
310
+ self.device = device
311
+
312
+ self.batch_size = len(prompts)
313
+ self.cross_replace_alpha = get_time_words_attention_alpha(
314
+ prompts, num_steps, cross_replace_steps, self.tokenizer
315
+ ).to(self.device)
316
+ if isinstance(self_replace_steps, float):
317
+ self_replace_steps = 0, self_replace_steps
318
+ self.num_self_replace = int(num_steps * self_replace_steps[0]), int(num_steps * self_replace_steps[1])
319
+ self.local_blend = local_blend
320
+
321
+
322
+ class AttentionReplace(AttentionControlEdit):
323
+ def replace_cross_attention(self, attn_base, att_replace):
324
+ return torch.einsum("hpw,bwn->bhpn", attn_base, self.mapper)
325
+
326
+ def __init__(
327
+ self,
328
+ prompts,
329
+ num_steps: int,
330
+ cross_replace_steps: float,
331
+ self_replace_steps: float,
332
+ local_blend: Optional[LocalBlend] = None,
333
+ tokenizer=None,
334
+ device=None,
335
+ attn_res=None,
336
+ ):
337
+ super(AttentionReplace, self).__init__(
338
+ prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device, attn_res
339
+ )
340
+ self.mapper = get_replacement_mapper(prompts, self.tokenizer).to(self.device)
341
+
342
+
343
+ class AttentionRefine(AttentionControlEdit):
344
+ def replace_cross_attention(self, attn_base, att_replace):
345
+ attn_base_replace = attn_base[:, :, self.mapper].permute(2, 0, 1, 3)
346
+ attn_replace = attn_base_replace * self.alphas + att_replace * (1 - self.alphas)
347
+ return attn_replace
348
+
349
+ def __init__(
350
+ self,
351
+ prompts,
352
+ num_steps: int,
353
+ cross_replace_steps: float,
354
+ self_replace_steps: float,
355
+ local_blend: Optional[LocalBlend] = None,
356
+ tokenizer=None,
357
+ device=None,
358
+ attn_res=None
359
+ ):
360
+ super(AttentionRefine, self).__init__(
361
+ prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device, attn_res
362
+ )
363
+ self.mapper, alphas = get_refinement_mapper(prompts, self.tokenizer)
364
+ self.mapper, alphas = self.mapper.to(self.device), alphas.to(self.device)
365
+ self.alphas = alphas.reshape(alphas.shape[0], 1, 1, alphas.shape[1])
366
+
367
+
368
+ class AttentionReweight(AttentionControlEdit):
369
+ def replace_cross_attention(self, attn_base, att_replace):
370
+ if self.prev_controller is not None:
371
+ attn_base = self.prev_controller.replace_cross_attention(attn_base, att_replace)
372
+ attn_replace = attn_base[None, :, :, :] * self.equalizer[:, None, None, :]
373
+ return attn_replace
374
+
375
+ def __init__(
376
+ self,
377
+ prompts,
378
+ num_steps: int,
379
+ cross_replace_steps: float,
380
+ self_replace_steps: float,
381
+ equalizer,
382
+ local_blend: Optional[LocalBlend] = None,
383
+ controller: Optional[AttentionControlEdit] = None,
384
+ tokenizer=None,
385
+ device=None,
386
+ attn_res=None,
387
+ ):
388
+ super(AttentionReweight, self).__init__(
389
+ prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend, tokenizer, device, attn_res
390
+ )
391
+ self.equalizer = equalizer.to(self.device)
392
+ self.prev_controller = controller
393
+
394
+
395
+ ### util functions for all Edits
396
+ def update_alpha_time_word(
397
+ alpha, bounds: Union[float, Tuple[float, float]], prompt_ind: int, word_inds: Optional[torch.Tensor] = None
398
+ ):
399
+ if isinstance(bounds, float):
400
+ bounds = 0, bounds
401
+ start, end = int(bounds[0] * alpha.shape[0]), int(bounds[1] * alpha.shape[0])
402
+ if word_inds is None:
403
+ word_inds = torch.arange(alpha.shape[2])
404
+ alpha[:start, prompt_ind, word_inds] = 0
405
+ alpha[start:end, prompt_ind, word_inds] = 1
406
+ alpha[end:, prompt_ind, word_inds] = 0
407
+ return alpha
408
+
409
+
410
+ def get_time_words_attention_alpha(
411
+ prompts, num_steps, cross_replace_steps: Union[float, Dict[str, Tuple[float, float]]], tokenizer, max_num_words=77
412
+ ):
413
+ if not isinstance(cross_replace_steps, dict):
414
+ cross_replace_steps = {"default_": cross_replace_steps}
415
+ if "default_" not in cross_replace_steps:
416
+ cross_replace_steps["default_"] = (0.0, 1.0)
417
+ alpha_time_words = torch.zeros(num_steps + 1, len(prompts) - 1, max_num_words)
418
+ for i in range(len(prompts) - 1):
419
+ alpha_time_words = update_alpha_time_word(alpha_time_words, cross_replace_steps["default_"], i)
420
+ for key, item in cross_replace_steps.items():
421
+ if key != "default_":
422
+ inds = [get_word_inds(prompts[i], key, tokenizer) for i in range(1, len(prompts))]
423
+ for i, ind in enumerate(inds):
424
+ if len(ind) > 0:
425
+ alpha_time_words = update_alpha_time_word(alpha_time_words, item, i, ind)
426
+ alpha_time_words = alpha_time_words.reshape(num_steps + 1, len(prompts) - 1, 1, 1, max_num_words)
427
+ return alpha_time_words
428
+
429
+
430
+ ### util functions for LocalBlend and ReplacementEdit
431
+ def get_word_inds(text: str, word_place: int, tokenizer):
432
+ split_text = text.split(" ")
433
+ if isinstance(word_place, str):
434
+ word_place = [i for i, word in enumerate(split_text) if word_place == word]
435
+ elif isinstance(word_place, int):
436
+ word_place = [word_place]
437
+ out = []
438
+ if len(word_place) > 0:
439
+ words_encode = [tokenizer.decode([item]).strip("#") for item in tokenizer.encode(text)][1:-1]
440
+ cur_len, ptr = 0, 0
441
+
442
+ for i in range(len(words_encode)):
443
+ cur_len += len(words_encode[i])
444
+ if ptr in word_place:
445
+ out.append(i + 1)
446
+ if cur_len >= len(split_text[ptr]):
447
+ ptr += 1
448
+ cur_len = 0
449
+ return np.array(out)
450
+
451
+
452
+ ### util functions for ReplacementEdit
453
+ def get_replacement_mapper_(x: str, y: str, tokenizer, max_len=77):
454
+ words_x = x.split(" ")
455
+ words_y = y.split(" ")
456
+ if len(words_x) != len(words_y):
457
+ raise ValueError(
458
+ f"attention replacement edit can only be applied on prompts with the same length"
459
+ f" but prompt A has {len(words_x)} words and prompt B has {len(words_y)} words."
460
+ )
461
+ inds_replace = [i for i in range(len(words_y)) if words_y[i] != words_x[i]]
462
+ inds_source = [get_word_inds(x, i, tokenizer) for i in inds_replace]
463
+ inds_target = [get_word_inds(y, i, tokenizer) for i in inds_replace]
464
+ mapper = np.zeros((max_len, max_len))
465
+ i = j = 0
466
+ cur_inds = 0
467
+ while i < max_len and j < max_len:
468
+ if cur_inds < len(inds_source) and inds_source[cur_inds][0] == i:
469
+ inds_source_, inds_target_ = inds_source[cur_inds], inds_target[cur_inds]
470
+ if len(inds_source_) == len(inds_target_):
471
+ mapper[inds_source_, inds_target_] = 1
472
+ else:
473
+ ratio = 1 / len(inds_target_)
474
+ for i_t in inds_target_:
475
+ mapper[inds_source_, i_t] = ratio
476
+ cur_inds += 1
477
+ i += len(inds_source_)
478
+ j += len(inds_target_)
479
+ elif cur_inds < len(inds_source):
480
+ mapper[i, j] = 1
481
+ i += 1
482
+ j += 1
483
+ else:
484
+ mapper[j, j] = 1
485
+ i += 1
486
+ j += 1
487
+
488
+ # return torch.from_numpy(mapper).float()
489
+ return torch.from_numpy(mapper).to(torch.float16)
490
+
491
+
492
+ def get_replacement_mapper(prompts, tokenizer, max_len=77):
493
+ x_seq = prompts[0]
494
+ mappers = []
495
+ for i in range(1, len(prompts)):
496
+ mapper = get_replacement_mapper_(x_seq, prompts[i], tokenizer, max_len)
497
+ mappers.append(mapper)
498
+ return torch.stack(mappers)
499
+
500
+
501
+ ### util functions for ReweightEdit
502
+ def get_equalizer(
503
+ text: str, word_select: Union[int, Tuple[int, ...]], values: Union[List[float], Tuple[float, ...]], tokenizer
504
+ ):
505
+ if isinstance(word_select, (int, str)):
506
+ word_select = (word_select,)
507
+ equalizer = torch.ones(len(values), 77)
508
+ values = torch.tensor(values, dtype=torch.float32)
509
+ for i, word in enumerate(word_select):
510
+ inds = get_word_inds(text, word, tokenizer)
511
+ equalizer[:, inds] = torch.FloatTensor(values[i])
512
+ return equalizer
513
+
514
+
515
+ ### util functions for RefinementEdit
516
+ class ScoreParams:
517
+ def __init__(self, gap, match, mismatch):
518
+ self.gap = gap
519
+ self.match = match
520
+ self.mismatch = mismatch
521
+
522
+ def mis_match_char(self, x, y):
523
+ if x != y:
524
+ return self.mismatch
525
+ else:
526
+ return self.match
527
+
528
+
529
+ def get_matrix(size_x, size_y, gap):
530
+ matrix = np.zeros((size_x + 1, size_y + 1), dtype=np.int32)
531
+ matrix[0, 1:] = (np.arange(size_y) + 1) * gap
532
+ matrix[1:, 0] = (np.arange(size_x) + 1) * gap
533
+ return matrix
534
+
535
+
536
+ def get_traceback_matrix(size_x, size_y):
537
+ matrix = np.zeros((size_x + 1, size_y + 1), dtype=np.int32)
538
+ matrix[0, 1:] = 1
539
+ matrix[1:, 0] = 2
540
+ matrix[0, 0] = 4
541
+ return matrix
542
+
543
+
544
+ def global_align(x, y, score):
545
+ matrix = get_matrix(len(x), len(y), score.gap)
546
+ trace_back = get_traceback_matrix(len(x), len(y))
547
+ for i in range(1, len(x) + 1):
548
+ for j in range(1, len(y) + 1):
549
+ left = matrix[i, j - 1] + score.gap
550
+ up = matrix[i - 1, j] + score.gap
551
+ diag = matrix[i - 1, j - 1] + score.mis_match_char(x[i - 1], y[j - 1])
552
+ matrix[i, j] = max(left, up, diag)
553
+ if matrix[i, j] == left:
554
+ trace_back[i, j] = 1
555
+ elif matrix[i, j] == up:
556
+ trace_back[i, j] = 2
557
+ else:
558
+ trace_back[i, j] = 3
559
+ return matrix, trace_back
560
+
561
+
562
+ def get_aligned_sequences(x, y, trace_back):
563
+ x_seq = []
564
+ y_seq = []
565
+ i = len(x)
566
+ j = len(y)
567
+ mapper_y_to_x = []
568
+ while i > 0 or j > 0:
569
+ if trace_back[i, j] == 3:
570
+ x_seq.append(x[i - 1])
571
+ y_seq.append(y[j - 1])
572
+ i = i - 1
573
+ j = j - 1
574
+ mapper_y_to_x.append((j, i))
575
+ elif trace_back[i][j] == 1:
576
+ x_seq.append("-")
577
+ y_seq.append(y[j - 1])
578
+ j = j - 1
579
+ mapper_y_to_x.append((j, -1))
580
+ elif trace_back[i][j] == 2:
581
+ x_seq.append(x[i - 1])
582
+ y_seq.append("-")
583
+ i = i - 1
584
+ elif trace_back[i][j] == 4:
585
+ break
586
+ mapper_y_to_x.reverse()
587
+ return x_seq, y_seq, torch.tensor(mapper_y_to_x, dtype=torch.int64)
588
+
589
+
590
+ def get_mapper(x: str, y: str, tokenizer, max_len=77):
591
+ x_seq = tokenizer.encode(x)
592
+ y_seq = tokenizer.encode(y)
593
+ score = ScoreParams(0, 1, -1)
594
+ matrix, trace_back = global_align(x_seq, y_seq, score)
595
+ mapper_base = get_aligned_sequences(x_seq, y_seq, trace_back)[-1]
596
+ alphas = torch.ones(max_len)
597
+ alphas[: mapper_base.shape[0]] = mapper_base[:, 1].ne(-1).float()
598
+ mapper = torch.zeros(max_len, dtype=torch.int64)
599
+ mapper[: mapper_base.shape[0]] = mapper_base[:, 1]
600
+ mapper[mapper_base.shape[0] :] = len(y_seq) + torch.arange(max_len - len(y_seq))
601
+ return mapper, alphas
602
+
603
+
604
+ def get_refinement_mapper(prompts, tokenizer, max_len=77):
605
+ x_seq = prompts[0]
606
+ mappers, alphas = [], []
607
+ for i in range(1, len(prompts)):
608
+ mapper, alpha = get_mapper(x_seq, prompts[i], tokenizer, max_len)
609
+ mappers.append(mapper)
610
+ alphas.append(alpha)
611
+ return torch.stack(mappers), torch.stack(alphas)
612
+
613
+
614
+
615
+
616
+
617
+ def aggregate_attention(prompts, attention_store: AttentionStore, height: int, width: int, from_where: List[str], is_cross: bool, select: int):
618
+ out = []
619
+ attention_maps = attention_store.get_average_attention()
620
+ attention_map_height = height // 32
621
+ attention_map_width = width // 32
622
+ num_pixels = attention_map_height * attention_map_width
623
+ for location in from_where:
624
+ for item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
625
+ if item.shape[1] == num_pixels:
626
+ cross_maps = item.reshape(len(prompts), -1, attention_map_width, attention_map_height, item.shape[-1])[select]
627
+ out.append(cross_maps)
628
+ out = torch.cat(out, dim=0)
629
+ out = out.sum(0) / out.shape[0]
630
+ return out.cpu()
631
+
632
+
633
+ def show_cross_attention(tokenizer, prompts, attention_store: AttentionStore, res: int, from_where: List[str], select: int = 0, t=0):
634
+ tokens = tokenizer.encode(prompts[select])
635
+ decoder = tokenizer.decode
636
+ attention_maps = aggregate_attention(prompts, attention_store, res, from_where, True, select)
637
+ images = []
638
+ for i in range(len(tokens)):
639
+ image = attention_maps[:, :, i]
640
+ image = 255 * image / image.max()
641
+ image = image.unsqueeze(-1).expand(*image.shape, 3)
642
+ image = image.numpy().astype(np.uint8)
643
+ image = np.array(Image.fromarray(image).resize((256, 256)))
644
+ image = text_under_image(image, decoder(int(tokens[i])))
645
+ images.append(image)
646
+
647
+ view_images(np.stack(images, axis=0), t=t, from_where=from_where)
648
+
649
+
650
+ def show_self_attention_comp(attention_store: AttentionStore, res: int, from_where: List[str],
651
+ max_com=10, select: int = 0):
652
+ attention_maps = aggregate_attention(attention_store, res, from_where, False, select).numpy().reshape((res ** 2, res ** 2))
653
+ u, s, vh = np.linalg.svd(attention_maps - np.mean(attention_maps, axis=1, keepdims=True))
654
+ images = []
655
+ for i in range(max_com):
656
+ image = vh[i].reshape(res, res)
657
+ image = image - image.min()
658
+ image = 255 * image / image.max()
659
+ image = np.repeat(np.expand_dims(image, axis=2), 3, axis=2).astype(np.uint8)
660
+ image = Image.fromarray(image).resize((256, 256))
661
+ image = np.array(image)
662
+ images.append(image)
663
+ view_images(np.concatenate(images, axis=1),from_where=from_where)
664
+
665
+ def view_images(images, num_rows=1, offset_ratio=0.02, t=0, from_where= List[str]):
666
+ if type(images) is list:
667
+ num_empty = len(images) % num_rows
668
+ elif images.ndim == 4:
669
+ num_empty = images.shape[0] % num_rows
670
+ else:
671
+ images = [images]
672
+ num_empty = 0
673
+
674
+ empty_images = np.ones(images[0].shape, dtype=np.uint8) * 255
675
+ images = [image.astype(np.uint8) for image in images] + [empty_images] * num_empty
676
+ num_items = len(images)
677
+
678
+ h, w, c = images[0].shape
679
+ offset = int(h * offset_ratio)
680
+ num_cols = num_items // num_rows
681
+ image_ = np.ones((h * num_rows + offset * (num_rows - 1),
682
+ w * num_cols + offset * (num_cols - 1), 3), dtype=np.uint8) * 255
683
+ for i in range(num_rows):
684
+ for j in range(num_cols):
685
+ image_[i * (h + offset): i * (h + offset) + h:, j * (w + offset): j * (w + offset) + w] = images[
686
+ i * num_cols + j]
687
+
688
+ pil_img = Image.fromarray(image_)
689
+
690
+ if len(from_where) > 1:
691
+ from_where = '_'.join(from_where)
692
+
693
+ save_path = f'./visualization/{from_where}'
694
+ if not os.path.exists(save_path):
695
+ os.mkdir(save_path)
696
+ pil_img.save(f"{save_path}/{t}.png")
697
+
698
+
699
+ def text_under_image(image: np.ndarray, text: str, text_color: Tuple[int, int, int] = (0, 0, 0)):
700
+ h, w, c = image.shape
701
+ offset = int(h * .2)
702
+ img = np.ones((h + offset, w, c), dtype=np.uint8) * 255
703
+ font = cv2.FONT_HERSHEY_SIMPLEX
704
+ img[:h] = image
705
+ textsize = cv2.getTextSize(text, font, 1, 2)[0]
706
+ text_x, text_y = (w - textsize[0]) // 2, h + offset - textsize[1] // 2
707
+ cv2.putText(img, text, (text_x, text_y ), font, 1, text_color, 2)
708
+ return img
709
+
710
+ def get_views(height, width, window_size=32, stride=16, random_jitter=False):
711
+ num_blocks_height = int((height - window_size) / stride - 1e-6) + 2 if height > window_size else 1
712
+ num_blocks_width = int((width - window_size) / stride - 1e-6) + 2 if width > window_size else 1
713
+ total_num_blocks = int(num_blocks_height * num_blocks_width)
714
+ views = []
715
+ for i in range(total_num_blocks):
716
+ h_start = int((i // num_blocks_width) * stride)
717
+ h_end = h_start + window_size
718
+ w_start = int((i % num_blocks_width) * stride)
719
+ w_end = w_start + window_size
720
+
721
+ if h_end > height:
722
+ h_start = int(h_start + height - h_end)
723
+ h_end = int(height)
724
+ if w_end > width:
725
+ w_start = int(w_start + width - w_end)
726
+ w_end = int(width)
727
+ if h_start < 0:
728
+ h_end = int(h_end - h_start)
729
+ h_start = 0
730
+ if w_start < 0:
731
+ w_end = int(w_end - w_start)
732
+ w_start = 0
733
+
734
+ if random_jitter:
735
+ jitter_range = (window_size - stride) // 4
736
+ w_jitter = 0
737
+ h_jitter = 0
738
+ if (w_start != 0) and (w_end != width):
739
+ w_jitter = random.randint(-jitter_range, jitter_range)
740
+ elif (w_start == 0) and (w_end != width):
741
+ w_jitter = random.randint(-jitter_range, 0)
742
+ elif (w_start != 0) and (w_end == width):
743
+ w_jitter = random.randint(0, jitter_range)
744
+ if (h_start != 0) and (h_end != height):
745
+ h_jitter = random.randint(-jitter_range, jitter_range)
746
+ elif (h_start == 0) and (h_end != height):
747
+ h_jitter = random.randint(-jitter_range, 0)
748
+ elif (h_start != 0) and (h_end == height):
749
+ h_jitter = random.randint(0, jitter_range)
750
+ h_start += (h_jitter + jitter_range)
751
+ h_end += (h_jitter + jitter_range)
752
+ w_start += (w_jitter + jitter_range)
753
+ w_end += (w_jitter + jitter_range)
754
+
755
+ views.append((int(h_start), int(h_end), int(w_start), int(w_end)))
756
+ return views
757
+
758
+
759
+ def get_multidiffusion_prompts(tokenizer, prompts, threthod, attention_store:AttentionStore, height:int, width:int, from_where: List[str], scale_num=4, random_jitter=False):
760
+ tokens = tokenizer.encode(prompts[0])
761
+ decoder = tokenizer.decode
762
+
763
+ # get cross_attention_maps
764
+ attention_maps = aggregate_attention(prompts, attention_store, height, width, from_where, True, 0)
765
+
766
+ # view cross_attention_maps
767
+ images = []
768
+ for i in range(len(tokens)):
769
+ image = attention_maps[:, :, i]
770
+ image = 255 * image / image.max()
771
+ image = image.unsqueeze(-1).expand(*image.shape, 3).numpy().astype(np.uint8)
772
+ image = np.array(Image.fromarray(image).resize((256, 256)))
773
+ image = text_under_image(image, decoder(int(tokens[i])))
774
+ images.append(image)
775
+
776
+ # get high attention regions
777
+ masks = []
778
+
779
+ for i in range(len(tokens)):
780
+ attention_map = attention_maps[:, :, i]
781
+ attention_map = attention_map.to(torch.float32)
782
+ words = decoder(int(tokens[i]))
783
+ mask = torch.where(attention_map > attention_map.mean(), 1, 0).numpy().astype(np.uint8)
784
+ mask = mask * 255
785
+ # process mask
786
+ kernel = np.ones((3, 3), np.uint8)
787
+ eroded_mask = cv2.erode(mask, kernel, iterations=mask.shape[0]//16)
788
+ dilated_mask = cv2.dilate(eroded_mask, kernel, iterations=mask.shape[0]//16)
789
+ masks.append(dilated_mask)
790
+
791
+ # dict for prompts and views
792
+ prompt_dict = {}
793
+ view_dict = {}
794
+
795
+ ori_w, ori_h = mask.shape
796
+ window_size = max(ori_h, ori_w)
797
+ for scale in range(2, scale_num+1):
798
+ # current height and width
799
+ cur_w = ori_w * scale
800
+ cur_h = ori_h * scale
801
+ views = get_views(height=cur_h, width=cur_w, window_size=window_size, stride=window_size/2, random_jitter=random_jitter)
802
+
803
+ words_in_patch = []
804
+ for i, mask in enumerate(masks):
805
+ # skip endoftext and beginof text masks
806
+ if i == 0 or i == len(masks) - 1:
807
+ continue
808
+ # upscale masks
809
+ mask = cv2.resize(mask, (cur_w, cur_h), interpolation=cv2.INTER_NEAREST)
810
+ if random_jitter:
811
+ jitter_range = int((ori_h - ori_h/2) // 4)
812
+ mask = np.pad(mask, ((jitter_range, jitter_range), (jitter_range, jitter_range)), 'constant', constant_values=(0, 0))
813
+
814
+ word_in_patch =[]
815
+ word = decoder(int(tokens[i]))
816
+ for i, view in enumerate(views):
817
+ h_start, h_end, w_start, w_end = view
818
+ view_mask = mask[h_start:h_end, w_start:w_end]
819
+ if (view_mask/255).sum() / (ori_h * ori_w) >= threthod:
820
+ word_in_patch.append(word) # word in patch
821
+ else:
822
+ word_in_patch.append('') # word not in patch
823
+ words_in_patch.append(word_in_patch)
824
+
825
+ # get prompts for each view
826
+ result = []
827
+ prompts_for_each_views = [' '.join(strings) for strings in zip(*words_in_patch)]
828
+ for prompt in prompts_for_each_views:
829
+ prompt = prompt.split()
830
+ result.append(" ".join(prompt))
831
+ # save prompts and views in each scale
832
+ prompt_dict[scale] = result
833
+ view_dict[scale] = views
834
+
835
+ return prompt_dict, view_dict
836
+
837
+
838
+
839
+
840
+
841
+ class ScaledAttnProcessor:
842
+ r"""
843
+ Default processor for performing attention-related computations.
844
+ """
845
+
846
+ def __init__(self, processor, test_res, train_res):
847
+ self.processor = processor
848
+ self.test_res = test_res
849
+ self.train_res = train_res
850
+
851
+ def __call__(
852
+ self,
853
+ attn,
854
+ hidden_states,
855
+ encoder_hidden_states=None,
856
+ attention_mask=None,
857
+ temb=None,
858
+ ):
859
+ input_ndim = hidden_states.ndim
860
+ # print(f"cross attention: {not encoder_hidden_states is None}")
861
+ # if encoder_hidden_states is None:
862
+ if input_ndim == 4:
863
+ batch_size, channel, height, width = hidden_states.shape
864
+ sequence_length = height * width
865
+ else:
866
+ batch_size, sequence_length, _ = hidden_states.shape
867
+
868
+ test_train_ratio = (self.test_res ** 2.0) / (self.train_res ** 2.0)
869
+ # test_train_ratio = float(self.test_res / self.train_res)
870
+ # print(f"test_train_ratio: {test_train_ratio}")
871
+ train_sequence_length = sequence_length / test_train_ratio
872
+ scale_factor = math.log(sequence_length, train_sequence_length) ** 0.5
873
+ # else:
874
+ # scale_factor = 1
875
+ # print(f"scale factor: {scale_factor}")
876
+
877
+ original_scale = attn.scale
878
+ attn.scale = attn.scale * scale_factor
879
+ hidden_states = self.processor(attn, hidden_states, encoder_hidden_states, attention_mask, temb, scale = attn.scale )
880
+ # hidden_states = super(ScaledAttnProcessor, self).__call__(
881
+ # attn, hidden_states, encoder_hidden_states, attention_mask, temb)
882
+ attn.scale = original_scale
883
+ return hidden_states
884
+
885
+
watermark.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ from diffusers.utils import is_invisible_watermark_available
5
+
6
+
7
+ if is_invisible_watermark_available():
8
+ from imwatermark import WatermarkEncoder
9
+
10
+
11
+ # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66
12
+ WATERMARK_MESSAGE = 0b101100111110110010010000011110111011000110011110
13
+ # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1
14
+ WATERMARK_BITS = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]]
15
+
16
+
17
+ class StableDiffusionXLWatermarker:
18
+ def __init__(self):
19
+ self.watermark = WATERMARK_BITS
20
+ self.encoder = WatermarkEncoder()
21
+
22
+ self.encoder.set_watermark("bits", self.watermark)
23
+
24
+ def apply_watermark(self, images: torch.FloatTensor):
25
+ # can't encode images that are smaller than 256
26
+ if images.shape[-1] < 256:
27
+ return images
28
+
29
+ images = (255 * (images / 2 + 0.5)).cpu().permute(0, 2, 3, 1).float().numpy()
30
+
31
+ images = [self.encoder.encode(image, "dwtDct") for image in images]
32
+
33
+ images = torch.from_numpy(np.array(images)).permute(0, 3, 1, 2)
34
+
35
+ images = torch.clamp(2 * (images / 255 - 0.5), min=-1.0, max=1.0)
36
+ return images