fffiloni commited on
Commit
565a2da
1 Parent(s): fe72a39

Create app.py

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