3v324v23 commited on
Commit
eb20056
1 Parent(s): a917c5e
.gitmodules ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [submodule "newdream-sdxl-20"]
2
+ path = models/newdream-sdxl-20
3
+ url = https://huggingface.co/stablediffusionapi/newdream-sdxl-20
4
+ branch = main
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # edge-maxxing-newdream-sdxl
2
+
3
+ This holds the baseline for the SDXL Nvidia GeForce RTX 4090 contest, which can be forked freely and optimized
4
+
5
+ Some recommendations are as follows:
6
+ - Installing dependencies should be done in pyproject.toml, including git dependencies
7
+ - Compiled models should be included directly in the repository(rather than compiling during loading), loading time matters far more than file sizes
8
+ - Avoid changing `src/main.py`, as that includes mostly protocol logic. Most changes should be in `models` and `src/pipeline.py`
9
+ - Change `requirements.txt` to add extra arguments to be used when installing the package
10
+
11
+ For testing, you need a docker container with pytorch and ubuntu 22.04,
12
+ you can download your listed dependencies with `pip install -r requirements.txt -e .`, and then running `start_inference`
pyproject.toml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools >= 61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "edge-maxxing-4090-newdream"
7
+ description = "An edge-maxxing model submission for the 4090 newdream contest"
8
+ requires-python = ">=3.10,<3.11"
9
+ version = "1.0.0"
10
+ dependencies = [
11
+ "diffusers==0.28.2",
12
+ "onediff==1.2.0",
13
+ "onediffx==1.2.0",
14
+ "accelerate==0.31.0",
15
+ "numpy==1.26.4",
16
+ "xformers==0.0.25.post1",
17
+ "triton==2.2.0",
18
+ "transformers==4.41.2",
19
+ "accelerate==0.31.0",
20
+ "omegaconf==2.3.0",
21
+ "torch==2.2.2",
22
+ "torchvision==0.17.2",
23
+ "edge-maxxing-pipelines @ git+https://github.com/womboai/edge-maxxing#subdirectory=pipelines",
24
+ ]
25
+
26
+ [project.scripts]
27
+ start_inference = "main:main"
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Specify any extra options here, like --find-links, --pre, etc. Avoid specifying dependencies here and specify them in pyproject.toml instead
2
+ https://github.com/siliconflow/oneflow_releases/releases/download/community_cu118/oneflow-0.9.1.dev20240802%2Bcu118-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
src/__pycache__/main.cpython-310.pyc ADDED
Binary file (1.42 kB). View file
 
src/__pycache__/pipeline.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
src/main.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ from multiprocessing.connection import Listener
3
+ from os import chmod, remove
4
+ from os.path import abspath, exists
5
+ from pathlib import Path
6
+
7
+ from PIL.JpegImagePlugin import JpegImageFile
8
+ from pipelines.models import TextToImageRequest
9
+
10
+ from pipeline import load_pipeline, infer
11
+
12
+ SOCKET = abspath(Path(__file__).parent.parent / "inferences.sock")
13
+
14
+
15
+ def main():
16
+ print(f"Loading pipeline")
17
+ pipeline = load_pipeline()
18
+
19
+ print(f"Pipeline loaded, creating socket at '{SOCKET}'")
20
+
21
+ if exists(SOCKET):
22
+ remove(SOCKET)
23
+
24
+ with Listener(SOCKET) as listener:
25
+ chmod(SOCKET, 0o777)
26
+
27
+ print(f"Awaiting connections")
28
+ with listener.accept() as connection:
29
+ print(f"Connected")
30
+
31
+ while True:
32
+ try:
33
+ request = TextToImageRequest.model_validate_json(connection.recv_bytes().decode("utf-8"))
34
+ except EOFError:
35
+ print(f"Inference socket exiting")
36
+
37
+ return
38
+
39
+ image = infer(request, pipeline)
40
+
41
+ data = BytesIO()
42
+ image.save(data, format=JpegImageFile.format)
43
+
44
+ packet = data.getvalue()
45
+
46
+ connection.send_bytes(packet)
47
+
48
+
49
+ if __name__ == '__main__':
50
+ main()
src/pipeline.py ADDED
@@ -0,0 +1,1345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL.Image import Image
3
+ from diffusers import AutoencoderTiny
4
+ from sfast.compilers.diffusion_pipeline_compiler import (compile,
5
+ CompilationConfig)
6
+ from pipelines.models import TextToImageRequest
7
+ from torch import Generator
8
+
9
+
10
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+
24
+ import inspect
25
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
26
+
27
+ import torch
28
+ from transformers import (
29
+ CLIPImageProcessor,
30
+ CLIPTextModel,
31
+ CLIPTextModelWithProjection,
32
+ CLIPTokenizer,
33
+ CLIPVisionModelWithProjection,
34
+ )
35
+
36
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
37
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
38
+ from diffusers.loaders import (
39
+ FromSingleFileMixin,
40
+ IPAdapterMixin,
41
+ StableDiffusionXLLoraLoaderMixin,
42
+ TextualInversionLoaderMixin,
43
+ )
44
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
45
+ from diffusers.models.attention_processor import (
46
+ AttnProcessor2_0,
47
+ FusedAttnProcessor2_0,
48
+ XFormersAttnProcessor,
49
+ )
50
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
51
+ from diffusers.schedulers import KarrasDiffusionSchedulers
52
+ from diffusers.utils import (
53
+ USE_PEFT_BACKEND,
54
+ deprecate,
55
+ is_invisible_watermark_available,
56
+ is_torch_xla_available,
57
+ logging,
58
+ replace_example_docstring,
59
+ scale_lora_layers,
60
+ unscale_lora_layers,
61
+ )
62
+ from diffusers.utils.torch_utils import randn_tensor
63
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
64
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
65
+
66
+
67
+ if is_invisible_watermark_available():
68
+ from .watermark import StableDiffusionXLWatermarker
69
+
70
+ if is_torch_xla_available():
71
+ import torch_xla.core.xla_model as xm
72
+
73
+ XLA_AVAILABLE = True
74
+ else:
75
+ XLA_AVAILABLE = False
76
+
77
+
78
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
79
+
80
+ EXAMPLE_DOC_STRING = """
81
+ Examples:
82
+ ```py
83
+ >>> import torch
84
+ >>> from diffusers import StableDiffusionXLPipeline
85
+
86
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
87
+ diffusers. "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
88
+ diffusers. )
89
+ >>> pipe = pipe.to("cuda")
90
+
91
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
92
+ >>> image = pipe(prompt).images[0]
93
+ ```
94
+ """
95
+
96
+
97
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
98
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
99
+ """
100
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
101
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
102
+ """
103
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
104
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
105
+ # rescale the results from guidance (fixes overexposure)
106
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
107
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
108
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
109
+ return noise_cfg
110
+
111
+
112
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
113
+ def retrieve_timesteps(
114
+ scheduler,
115
+ num_inference_steps: Optional[int] = None,
116
+ device: Optional[Union[str, torch.device]] = None,
117
+ timesteps: Optional[List[int]] = None,
118
+ sigmas: Optional[List[float]] = None,
119
+ **kwargs,
120
+ ):
121
+ """
122
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
123
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
124
+
125
+ Args:
126
+ scheduler (`SchedulerMixin`):
127
+ The scheduler to get timesteps from.
128
+ num_inference_steps (`int`):
129
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
130
+ must be `None`.
131
+ device (`str` or `torch.device`, *optional*):
132
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
133
+ timesteps (`List[int]`, *optional*):
134
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
135
+ `num_inference_steps` and `sigmas` must be `None`.
136
+ sigmas (`List[float]`, *optional*):
137
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
138
+ `num_inference_steps` and `timesteps` must be `None`.
139
+
140
+ Returns:
141
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
142
+ second element is the number of inference steps.
143
+ """
144
+ if timesteps is not None and sigmas is not None:
145
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
146
+ if timesteps is not None:
147
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
148
+ if not accepts_timesteps:
149
+ raise ValueError(
150
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
151
+ f" timestep schedules. Please check whether you are using the correct scheduler."
152
+ )
153
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
154
+ timesteps = scheduler.timesteps
155
+ num_inference_steps = len(timesteps)
156
+ elif sigmas is not None:
157
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
158
+ if not accept_sigmas:
159
+ raise ValueError(
160
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
161
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
162
+ )
163
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
164
+ timesteps = scheduler.timesteps
165
+ num_inference_steps = len(timesteps)
166
+ else:
167
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
168
+ timesteps = scheduler.timesteps
169
+ return timesteps, num_inference_steps
170
+
171
+
172
+ class StableDiffusionXLPipeline(
173
+ DiffusionPipeline,
174
+ StableDiffusionMixin,
175
+ FromSingleFileMixin,
176
+ StableDiffusionXLLoraLoaderMixin,
177
+ TextualInversionLoaderMixin,
178
+ IPAdapterMixin,
179
+ ):
180
+ r"""
181
+ Pipeline for text-to-image generation using Stable Diffusion XL.
182
+
183
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
184
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
185
+
186
+ The pipeline also inherits the following loading methods:
187
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
188
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
189
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
190
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
191
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
192
+
193
+ Args:
194
+ vae ([`AutoencoderKL`]):
195
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
196
+ text_encoder ([`CLIPTextModel`]):
197
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
198
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
199
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
200
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
201
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
202
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
203
+ specifically the
204
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
205
+ variant.
206
+ tokenizer (`CLIPTokenizer`):
207
+ Tokenizer of class
208
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
209
+ tokenizer_2 (`CLIPTokenizer`):
210
+ Second Tokenizer of class
211
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
212
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
213
+ scheduler ([`SchedulerMixin`]):
214
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
215
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
216
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
217
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
218
+ `stabilityai/stable-diffusion-xl-base-1-0`.
219
+ add_watermarker (`bool`, *optional*):
220
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
221
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
222
+ watermarker will be used.
223
+ """
224
+
225
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
226
+ _optional_components = [
227
+ "tokenizer",
228
+ "tokenizer_2",
229
+ "text_encoder",
230
+ "text_encoder_2",
231
+ "image_encoder",
232
+ "feature_extractor",
233
+ ]
234
+ _callback_tensor_inputs = [
235
+ "latents",
236
+ "prompt_embeds",
237
+ "negative_prompt_embeds",
238
+ "add_text_embeds",
239
+ "add_time_ids",
240
+ "negative_pooled_prompt_embeds",
241
+ "negative_add_time_ids",
242
+ ]
243
+
244
+ def __init__(
245
+ self,
246
+ vae: AutoencoderKL,
247
+ text_encoder: CLIPTextModel,
248
+ text_encoder_2: CLIPTextModelWithProjection,
249
+ tokenizer: CLIPTokenizer,
250
+ tokenizer_2: CLIPTokenizer,
251
+ unet: UNet2DConditionModel,
252
+ scheduler: KarrasDiffusionSchedulers,
253
+ image_encoder: CLIPVisionModelWithProjection = None,
254
+ feature_extractor: CLIPImageProcessor = None,
255
+ force_zeros_for_empty_prompt: bool = True,
256
+ add_watermarker: Optional[bool] = None,
257
+ ):
258
+ super().__init__()
259
+
260
+ self.register_modules(
261
+ vae=vae,
262
+ text_encoder=text_encoder,
263
+ text_encoder_2=text_encoder_2,
264
+ tokenizer=tokenizer,
265
+ tokenizer_2=tokenizer_2,
266
+ unet=unet,
267
+ scheduler=scheduler,
268
+ image_encoder=image_encoder,
269
+ feature_extractor=feature_extractor,
270
+ )
271
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
272
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
273
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
274
+
275
+ self.default_sample_size = self.unet.config.sample_size
276
+
277
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
278
+
279
+ if add_watermarker:
280
+ self.watermark = StableDiffusionXLWatermarker()
281
+ else:
282
+ self.watermark = None
283
+
284
+ def encode_prompt(
285
+ self,
286
+ prompt: str,
287
+ prompt_2: Optional[str] = None,
288
+ device: Optional[torch.device] = None,
289
+ num_images_per_prompt: int = 1,
290
+ do_classifier_free_guidance: bool = True,
291
+ negative_prompt: Optional[str] = None,
292
+ negative_prompt_2: Optional[str] = None,
293
+ prompt_embeds: Optional[torch.Tensor] = None,
294
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
295
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
296
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
297
+ lora_scale: Optional[float] = None,
298
+ clip_skip: Optional[int] = None,
299
+ ):
300
+ r"""
301
+ Encodes the prompt into text encoder hidden states.
302
+
303
+ Args:
304
+ prompt (`str` or `List[str]`, *optional*):
305
+ prompt to be encoded
306
+ prompt_2 (`str` or `List[str]`, *optional*):
307
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
308
+ used in both text-encoders
309
+ device: (`torch.device`):
310
+ torch device
311
+ num_images_per_prompt (`int`):
312
+ number of images that should be generated per prompt
313
+ do_classifier_free_guidance (`bool`):
314
+ whether to use classifier free guidance or not
315
+ negative_prompt (`str` or `List[str]`, *optional*):
316
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
317
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
318
+ less than `1`).
319
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
320
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
321
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
322
+ prompt_embeds (`torch.Tensor`, *optional*):
323
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
324
+ provided, text embeddings will be generated from `prompt` input argument.
325
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
326
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
327
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
328
+ argument.
329
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
330
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
331
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
332
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
333
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
334
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
335
+ input argument.
336
+ lora_scale (`float`, *optional*):
337
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
338
+ clip_skip (`int`, *optional*):
339
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
340
+ the output of the pre-final layer will be used for computing the prompt embeddings.
341
+ """
342
+ device = device or self._execution_device
343
+
344
+ # set lora scale so that monkey patched LoRA
345
+ # function of text encoder can correctly access it
346
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
347
+ self._lora_scale = lora_scale
348
+
349
+ # dynamically adjust the LoRA scale
350
+ if self.text_encoder is not None:
351
+ if not USE_PEFT_BACKEND:
352
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
353
+ else:
354
+ scale_lora_layers(self.text_encoder, lora_scale)
355
+
356
+ if self.text_encoder_2 is not None:
357
+ if not USE_PEFT_BACKEND:
358
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
359
+ else:
360
+ scale_lora_layers(self.text_encoder_2, lora_scale)
361
+
362
+ prompt = [prompt] if isinstance(prompt, str) else prompt
363
+
364
+ if prompt is not None:
365
+ batch_size = len(prompt)
366
+ else:
367
+ batch_size = prompt_embeds.shape[0]
368
+
369
+ # Define tokenizers and text encoders
370
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
371
+ text_encoders = (
372
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
373
+ )
374
+
375
+ if prompt_embeds is None:
376
+ prompt_2 = prompt_2 or prompt
377
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
378
+
379
+ # textual inversion: process multi-vector tokens if necessary
380
+ prompt_embeds_list = []
381
+ prompts = [prompt, prompt_2]
382
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
383
+ if isinstance(self, TextualInversionLoaderMixin):
384
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
385
+
386
+ text_inputs = tokenizer(
387
+ prompt,
388
+ padding="max_length",
389
+ max_length=tokenizer.model_max_length,
390
+ truncation=True,
391
+ return_tensors="pt",
392
+ )
393
+
394
+ text_input_ids = text_inputs.input_ids
395
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
396
+
397
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
398
+ text_input_ids, untruncated_ids
399
+ ):
400
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
401
+ logger.warning(
402
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
403
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
404
+ )
405
+
406
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
407
+
408
+ # We are only ALWAYS interested in the pooled output of the final text encoder
409
+ pooled_prompt_embeds = prompt_embeds[0]
410
+ if clip_skip is None:
411
+ prompt_embeds = prompt_embeds.hidden_states[-2]
412
+ else:
413
+ # "2" because SDXL always indexes from the penultimate layer.
414
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
415
+
416
+ prompt_embeds_list.append(prompt_embeds)
417
+
418
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
419
+
420
+ # get unconditional embeddings for classifier free guidance
421
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
422
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
423
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
424
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
425
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
426
+ negative_prompt = negative_prompt or ""
427
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
428
+
429
+ # normalize str to list
430
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
431
+ negative_prompt_2 = (
432
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
433
+ )
434
+
435
+ uncond_tokens: List[str]
436
+ if prompt is not None and type(prompt) is not type(negative_prompt):
437
+ raise TypeError(
438
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
439
+ f" {type(prompt)}."
440
+ )
441
+ elif batch_size != len(negative_prompt):
442
+ raise ValueError(
443
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
444
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
445
+ " the batch size of `prompt`."
446
+ )
447
+ else:
448
+ uncond_tokens = [negative_prompt, negative_prompt_2]
449
+
450
+ negative_prompt_embeds_list = []
451
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
452
+ if isinstance(self, TextualInversionLoaderMixin):
453
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
454
+
455
+ max_length = prompt_embeds.shape[1]
456
+ uncond_input = tokenizer(
457
+ negative_prompt,
458
+ padding="max_length",
459
+ max_length=max_length,
460
+ truncation=True,
461
+ return_tensors="pt",
462
+ )
463
+
464
+ negative_prompt_embeds = text_encoder(
465
+ uncond_input.input_ids.to(device),
466
+ output_hidden_states=True,
467
+ )
468
+ # We are only ALWAYS interested in the pooled output of the final text encoder
469
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
470
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
471
+
472
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
473
+
474
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
475
+
476
+ if self.text_encoder_2 is not None:
477
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
478
+ else:
479
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
480
+
481
+ bs_embed, seq_len, _ = prompt_embeds.shape
482
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
483
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
484
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
485
+
486
+ if do_classifier_free_guidance:
487
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
488
+ seq_len = negative_prompt_embeds.shape[1]
489
+
490
+ if self.text_encoder_2 is not None:
491
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
492
+ else:
493
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
494
+
495
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
496
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
497
+
498
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
499
+ bs_embed * num_images_per_prompt, -1
500
+ )
501
+ if do_classifier_free_guidance:
502
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
503
+ bs_embed * num_images_per_prompt, -1
504
+ )
505
+
506
+ if self.text_encoder is not None:
507
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
508
+ # Retrieve the original scale by scaling back the LoRA layers
509
+ unscale_lora_layers(self.text_encoder, lora_scale)
510
+
511
+ if self.text_encoder_2 is not None:
512
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
513
+ # Retrieve the original scale by scaling back the LoRA layers
514
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
515
+
516
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
517
+
518
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
519
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
520
+ dtype = next(self.image_encoder.parameters()).dtype
521
+
522
+ if not isinstance(image, torch.Tensor):
523
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
524
+
525
+ image = image.to(device=device, dtype=dtype)
526
+ if output_hidden_states:
527
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
528
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
529
+ uncond_image_enc_hidden_states = self.image_encoder(
530
+ torch.zeros_like(image), output_hidden_states=True
531
+ ).hidden_states[-2]
532
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
533
+ num_images_per_prompt, dim=0
534
+ )
535
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
536
+ else:
537
+ image_embeds = self.image_encoder(image).image_embeds
538
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
539
+ uncond_image_embeds = torch.zeros_like(image_embeds)
540
+
541
+ return image_embeds, uncond_image_embeds
542
+
543
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
544
+ def prepare_ip_adapter_image_embeds(
545
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
546
+ ):
547
+ image_embeds = []
548
+ if do_classifier_free_guidance:
549
+ negative_image_embeds = []
550
+ if ip_adapter_image_embeds is None:
551
+ if not isinstance(ip_adapter_image, list):
552
+ ip_adapter_image = [ip_adapter_image]
553
+
554
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
555
+ raise ValueError(
556
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
557
+ )
558
+
559
+ for single_ip_adapter_image, image_proj_layer in zip(
560
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
561
+ ):
562
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
563
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
564
+ single_ip_adapter_image, device, 1, output_hidden_state
565
+ )
566
+
567
+ image_embeds.append(single_image_embeds[None, :])
568
+ if do_classifier_free_guidance:
569
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
570
+ else:
571
+ for single_image_embeds in ip_adapter_image_embeds:
572
+ if do_classifier_free_guidance:
573
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
574
+ negative_image_embeds.append(single_negative_image_embeds)
575
+ image_embeds.append(single_image_embeds)
576
+
577
+ ip_adapter_image_embeds = []
578
+ for i, single_image_embeds in enumerate(image_embeds):
579
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
580
+ if do_classifier_free_guidance:
581
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
582
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
583
+
584
+ single_image_embeds = single_image_embeds.to(device=device)
585
+ ip_adapter_image_embeds.append(single_image_embeds)
586
+
587
+ return ip_adapter_image_embeds
588
+
589
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
590
+ def prepare_extra_step_kwargs(self, generator, eta):
591
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
592
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
593
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
594
+ # and should be between [0, 1]
595
+
596
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
597
+ extra_step_kwargs = {}
598
+ if accepts_eta:
599
+ extra_step_kwargs["eta"] = eta
600
+
601
+ # check if the scheduler accepts generator
602
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
603
+ if accepts_generator:
604
+ extra_step_kwargs["generator"] = generator
605
+ return extra_step_kwargs
606
+
607
+ def check_inputs(
608
+ self,
609
+ prompt,
610
+ prompt_2,
611
+ height,
612
+ width,
613
+ callback_steps,
614
+ negative_prompt=None,
615
+ negative_prompt_2=None,
616
+ prompt_embeds=None,
617
+ negative_prompt_embeds=None,
618
+ pooled_prompt_embeds=None,
619
+ negative_pooled_prompt_embeds=None,
620
+ ip_adapter_image=None,
621
+ ip_adapter_image_embeds=None,
622
+ callback_on_step_end_tensor_inputs=None,
623
+ ):
624
+ if height % 8 != 0 or width % 8 != 0:
625
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
626
+
627
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
628
+ raise ValueError(
629
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
630
+ f" {type(callback_steps)}."
631
+ )
632
+
633
+ if callback_on_step_end_tensor_inputs is not None and not all(
634
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
635
+ ):
636
+ raise ValueError(
637
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
638
+ )
639
+
640
+ if prompt is not None and prompt_embeds is not None:
641
+ raise ValueError(
642
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
643
+ " only forward one of the two."
644
+ )
645
+ elif prompt_2 is not None and prompt_embeds is not None:
646
+ raise ValueError(
647
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
648
+ " only forward one of the two."
649
+ )
650
+ elif prompt is None and prompt_embeds is None:
651
+ raise ValueError(
652
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
653
+ )
654
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
655
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
656
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
657
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
658
+
659
+ if negative_prompt is not None and negative_prompt_embeds is not None:
660
+ raise ValueError(
661
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
662
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
663
+ )
664
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
665
+ raise ValueError(
666
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
667
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
668
+ )
669
+
670
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
671
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
672
+ raise ValueError(
673
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
674
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
675
+ f" {negative_prompt_embeds.shape}."
676
+ )
677
+
678
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
679
+ raise ValueError(
680
+ "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`."
681
+ )
682
+
683
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
684
+ raise ValueError(
685
+ "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`."
686
+ )
687
+
688
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
689
+ raise ValueError(
690
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
691
+ )
692
+
693
+ if ip_adapter_image_embeds is not None:
694
+ if not isinstance(ip_adapter_image_embeds, list):
695
+ raise ValueError(
696
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
697
+ )
698
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
699
+ raise ValueError(
700
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
701
+ )
702
+
703
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
704
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
705
+ shape = (
706
+ batch_size,
707
+ num_channels_latents,
708
+ int(height) // self.vae_scale_factor,
709
+ int(width) // self.vae_scale_factor,
710
+ )
711
+ if isinstance(generator, list) and len(generator) != batch_size:
712
+ raise ValueError(
713
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
714
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
715
+ )
716
+
717
+ if latents is None:
718
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
719
+ else:
720
+ latents = latents.to(device)
721
+
722
+ # scale the initial noise by the standard deviation required by the scheduler
723
+ latents = latents * self.scheduler.init_noise_sigma
724
+ return latents
725
+
726
+ def _get_add_time_ids(
727
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
728
+ ):
729
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
730
+
731
+ passed_add_embed_dim = (
732
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
733
+ )
734
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
735
+
736
+ if expected_add_embed_dim != passed_add_embed_dim:
737
+ raise ValueError(
738
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
739
+ )
740
+
741
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
742
+ return add_time_ids
743
+
744
+ def upcast_vae(self):
745
+ dtype = self.vae.dtype
746
+ self.vae.to(dtype=torch.float32)
747
+ use_torch_2_0_or_xformers = isinstance(
748
+ self.vae.decoder.mid_block.attentions[0].processor,
749
+ (
750
+ AttnProcessor2_0,
751
+ XFormersAttnProcessor,
752
+ FusedAttnProcessor2_0,
753
+ ),
754
+ )
755
+ # if xformers or torch_2_0 is used attention block does not need
756
+ # to be in float32 which can save lots of memory
757
+ if use_torch_2_0_or_xformers:
758
+ self.vae.post_quant_conv.to(dtype)
759
+ self.vae.decoder.conv_in.to(dtype)
760
+ self.vae.decoder.mid_block.to(dtype)
761
+
762
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
763
+ def get_guidance_scale_embedding(
764
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
765
+ ) -> torch.Tensor:
766
+ """
767
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
768
+
769
+ Args:
770
+ w (`torch.Tensor`):
771
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
772
+ embedding_dim (`int`, *optional*, defaults to 512):
773
+ Dimension of the embeddings to generate.
774
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
775
+ Data type of the generated embeddings.
776
+
777
+ Returns:
778
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
779
+ """
780
+ assert len(w.shape) == 1
781
+ w = w * 1000.0
782
+
783
+ half_dim = embedding_dim // 2
784
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
785
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
786
+ emb = w.to(dtype)[:, None] * emb[None, :]
787
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
788
+ if embedding_dim % 2 == 1: # zero pad
789
+ emb = torch.nn.functional.pad(emb, (0, 1))
790
+ assert emb.shape == (w.shape[0], embedding_dim)
791
+ return emb
792
+
793
+ @property
794
+ def guidance_scale(self):
795
+ return self._guidance_scale
796
+
797
+ @property
798
+ def guidance_rescale(self):
799
+ return self._guidance_rescale
800
+
801
+ @property
802
+ def clip_skip(self):
803
+ return self._clip_skip
804
+
805
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
806
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
807
+ # corresponds to doing no classifier free guidance.
808
+ @property
809
+ def do_classifier_free_guidance(self):
810
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
811
+
812
+ @property
813
+ def cross_attention_kwargs(self):
814
+ return self._cross_attention_kwargs
815
+
816
+ @property
817
+ def denoising_end(self):
818
+ return self._denoising_end
819
+
820
+ @property
821
+ def num_timesteps(self):
822
+ return self._num_timesteps
823
+
824
+ @property
825
+ def interrupt(self):
826
+ return self._interrupt
827
+
828
+ @torch.no_grad()
829
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
830
+ def __call__(
831
+ self,
832
+ prompt: Union[str, List[str]] = None,
833
+ prompt_2: Optional[Union[str, List[str]]] = None,
834
+ height: Optional[int] = None,
835
+ width: Optional[int] = None,
836
+ num_inference_steps: int = 50,
837
+ timesteps: List[int] = None,
838
+ sigmas: List[float] = None,
839
+ denoising_end: Optional[float] = None,
840
+ guidance_scale: float = 5.0,
841
+ negative_prompt: Optional[Union[str, List[str]]] = None,
842
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
843
+ num_images_per_prompt: Optional[int] = 1,
844
+ eta: float = 0.0,
845
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
846
+ latents: Optional[torch.Tensor] = None,
847
+ prompt_embeds: Optional[torch.Tensor] = None,
848
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
849
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
850
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
851
+ ip_adapter_image: Optional[PipelineImageInput] = None,
852
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
853
+ output_type: Optional[str] = "pil",
854
+ return_dict: bool = True,
855
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
856
+ guidance_rescale: float = 0.0,
857
+ end_cfg: float = 0.4,
858
+ original_size: Optional[Tuple[int, int]] = None,
859
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
860
+ target_size: Optional[Tuple[int, int]] = None,
861
+ negative_original_size: Optional[Tuple[int, int]] = None,
862
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
863
+ negative_target_size: Optional[Tuple[int, int]] = None,
864
+ clip_skip: Optional[int] = None,
865
+ callback_on_step_end: Optional[
866
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
867
+ ] = None,
868
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
869
+ **kwargs,
870
+ ):
871
+ r"""
872
+ Function invoked when calling the pipeline for generation.
873
+
874
+ Args:
875
+ prompt (`str` or `List[str]`, *optional*):
876
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
877
+ instead.
878
+ prompt_2 (`str` or `List[str]`, *optional*):
879
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
880
+ used in both text-encoders
881
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
882
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
883
+ Anything below 512 pixels won't work well for
884
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
885
+ and checkpoints that are not specifically fine-tuned on low resolutions.
886
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
887
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
888
+ Anything below 512 pixels won't work well for
889
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
890
+ and checkpoints that are not specifically fine-tuned on low resolutions.
891
+ num_inference_steps (`int`, *optional*, defaults to 50):
892
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
893
+ expense of slower inference.
894
+ timesteps (`List[int]`, *optional*):
895
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
896
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
897
+ passed will be used. Must be in descending order.
898
+ sigmas (`List[float]`, *optional*):
899
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
900
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
901
+ will be used.
902
+ denoising_end (`float`, *optional*):
903
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
904
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
905
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
906
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
907
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
908
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
909
+ guidance_scale (`float`, *optional*, defaults to 5.0):
910
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
911
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
912
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
913
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
914
+ usually at the expense of lower image quality.
915
+ negative_prompt (`str` or `List[str]`, *optional*):
916
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
917
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
918
+ less than `1`).
919
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
920
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
921
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
922
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
923
+ The number of images to generate per prompt.
924
+ eta (`float`, *optional*, defaults to 0.0):
925
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
926
+ [`schedulers.DDIMScheduler`], will be ignored for others.
927
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
928
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
929
+ to make generation deterministic.
930
+ latents (`torch.Tensor`, *optional*):
931
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
932
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
933
+ tensor will ge generated by sampling using the supplied random `generator`.
934
+ prompt_embeds (`torch.Tensor`, *optional*):
935
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
936
+ provided, text embeddings will be generated from `prompt` input argument.
937
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
938
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
939
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
940
+ argument.
941
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
942
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
943
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
944
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
945
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
946
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
947
+ input argument.
948
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
949
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
950
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
951
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
952
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
953
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
954
+ output_type (`str`, *optional*, defaults to `"pil"`):
955
+ The output format of the generate image. Choose between
956
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
957
+ return_dict (`bool`, *optional*, defaults to `True`):
958
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
959
+ of a plain tuple.
960
+ cross_attention_kwargs (`dict`, *optional*):
961
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
962
+ `self.processor` in
963
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
964
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
965
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
966
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
967
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
968
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
969
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
970
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
971
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
972
+ explained in section 2.2 of
973
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
974
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
975
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
976
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
977
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
978
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
979
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
980
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
981
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
982
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
983
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
984
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
985
+ micro-conditioning as explained in section 2.2 of
986
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
987
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
988
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
989
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
990
+ micro-conditioning as explained in section 2.2 of
991
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
992
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
993
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
994
+ To negatively condition the generation process based on a target image resolution. It should be as same
995
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
996
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
997
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
998
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
999
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1000
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1001
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1002
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1003
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1004
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1005
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1006
+ `._callback_tensor_inputs` attribute of your pipeline class.
1007
+
1008
+ Examples:
1009
+
1010
+ Returns:
1011
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1012
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1013
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1014
+ """
1015
+
1016
+ callback = kwargs.pop("callback", None)
1017
+ callback_steps = kwargs.pop("callback_steps", None)
1018
+
1019
+ if callback is not None:
1020
+ deprecate(
1021
+ "callback",
1022
+ "1.0.0",
1023
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1024
+ )
1025
+ if callback_steps is not None:
1026
+ deprecate(
1027
+ "callback_steps",
1028
+ "1.0.0",
1029
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1030
+ )
1031
+
1032
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1033
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1034
+
1035
+ # 0. Default height and width to unet
1036
+ height = height or self.default_sample_size * self.vae_scale_factor
1037
+ width = width or self.default_sample_size * self.vae_scale_factor
1038
+
1039
+ original_size = original_size or (height, width)
1040
+ target_size = target_size or (height, width)
1041
+
1042
+ # 1. Check inputs. Raise error if not correct
1043
+ self.check_inputs(
1044
+ prompt,
1045
+ prompt_2,
1046
+ height,
1047
+ width,
1048
+ callback_steps,
1049
+ negative_prompt,
1050
+ negative_prompt_2,
1051
+ prompt_embeds,
1052
+ negative_prompt_embeds,
1053
+ pooled_prompt_embeds,
1054
+ negative_pooled_prompt_embeds,
1055
+ ip_adapter_image,
1056
+ ip_adapter_image_embeds,
1057
+ callback_on_step_end_tensor_inputs,
1058
+ )
1059
+
1060
+ self._guidance_scale = guidance_scale
1061
+ self._guidance_rescale = guidance_rescale
1062
+ self._clip_skip = clip_skip
1063
+ self._cross_attention_kwargs = cross_attention_kwargs
1064
+ self._denoising_end = denoising_end
1065
+ self._interrupt = False
1066
+
1067
+ # 2. Define call parameters
1068
+ if prompt is not None and isinstance(prompt, str):
1069
+ batch_size = 1
1070
+ elif prompt is not None and isinstance(prompt, list):
1071
+ batch_size = len(prompt)
1072
+ else:
1073
+ batch_size = prompt_embeds.shape[0]
1074
+
1075
+ device = self._execution_device
1076
+
1077
+ # 3. Encode input prompt
1078
+ lora_scale = (
1079
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1080
+ )
1081
+
1082
+ (
1083
+ prompt_embeds,
1084
+ negative_prompt_embeds,
1085
+ pooled_prompt_embeds,
1086
+ negative_pooled_prompt_embeds,
1087
+ ) = self.encode_prompt(
1088
+ prompt=prompt,
1089
+ prompt_2=prompt_2,
1090
+ device=device,
1091
+ num_images_per_prompt=num_images_per_prompt,
1092
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1093
+ negative_prompt=negative_prompt,
1094
+ negative_prompt_2=negative_prompt_2,
1095
+ prompt_embeds=prompt_embeds,
1096
+ negative_prompt_embeds=negative_prompt_embeds,
1097
+ pooled_prompt_embeds=pooled_prompt_embeds,
1098
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1099
+ lora_scale=lora_scale,
1100
+ clip_skip=self.clip_skip,
1101
+ )
1102
+
1103
+ # 4. Prepare timesteps
1104
+ timesteps, num_inference_steps = retrieve_timesteps(
1105
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1106
+ )
1107
+
1108
+ # 5. Prepare latent variables
1109
+ num_channels_latents = self.unet.config.in_channels
1110
+ latents = self.prepare_latents(
1111
+ batch_size * num_images_per_prompt,
1112
+ num_channels_latents,
1113
+ height,
1114
+ width,
1115
+ prompt_embeds.dtype,
1116
+ device,
1117
+ generator,
1118
+ latents,
1119
+ )
1120
+
1121
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1122
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1123
+
1124
+ # 7. Prepare added time ids & embeddings
1125
+ add_text_embeds = pooled_prompt_embeds
1126
+ if self.text_encoder_2 is None:
1127
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1128
+ else:
1129
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1130
+
1131
+ add_time_ids = self._get_add_time_ids(
1132
+ original_size,
1133
+ crops_coords_top_left,
1134
+ target_size,
1135
+ dtype=prompt_embeds.dtype,
1136
+ text_encoder_projection_dim=text_encoder_projection_dim,
1137
+ )
1138
+ if negative_original_size is not None and negative_target_size is not None:
1139
+ negative_add_time_ids = self._get_add_time_ids(
1140
+ negative_original_size,
1141
+ negative_crops_coords_top_left,
1142
+ negative_target_size,
1143
+ dtype=prompt_embeds.dtype,
1144
+ text_encoder_projection_dim=text_encoder_projection_dim,
1145
+ )
1146
+ else:
1147
+ negative_add_time_ids = add_time_ids
1148
+
1149
+ if self.do_classifier_free_guidance:
1150
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1151
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1152
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1153
+
1154
+ prompt_embeds = prompt_embeds.to(device)
1155
+ add_text_embeds = add_text_embeds.to(device)
1156
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1157
+
1158
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1159
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1160
+ ip_adapter_image,
1161
+ ip_adapter_image_embeds,
1162
+ device,
1163
+ batch_size * num_images_per_prompt,
1164
+ self.do_classifier_free_guidance,
1165
+ )
1166
+
1167
+ # 8. Denoising loop
1168
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1169
+
1170
+ # 8.1 Apply denoising_end
1171
+ if (
1172
+ self.denoising_end is not None
1173
+ and isinstance(self.denoising_end, float)
1174
+ and self.denoising_end > 0
1175
+ and self.denoising_end < 1
1176
+ ):
1177
+ discrete_timestep_cutoff = int(
1178
+ round(
1179
+ self.scheduler.config.num_train_timesteps
1180
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1181
+ )
1182
+ )
1183
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1184
+ timesteps = timesteps[:num_inference_steps]
1185
+
1186
+ # 9. Optionally get Guidance Scale Embedding
1187
+ timestep_cond = None
1188
+ if self.unet.config.time_cond_proj_dim is not None:
1189
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1190
+ timestep_cond = self.get_guidance_scale_embedding(
1191
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1192
+ ).to(device=device, dtype=latents.dtype)
1193
+
1194
+ self._num_timesteps = len(timesteps)
1195
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1196
+ do_classifier_free_guidance = self.do_classifier_free_guidance
1197
+ for i, t in enumerate(timesteps):
1198
+ if self.interrupt:
1199
+ continue
1200
+ if end_cfg is not None and i / num_inference_steps > end_cfg and do_classifier_free_guidance:
1201
+ do_classifier_free_guidance = False
1202
+ prompt_embeds = torch.chunk(prompt_embeds, 2, dim=0)[-1]
1203
+ add_text_embeds = torch.chunk(add_text_embeds, 2, dim=0)[-1]
1204
+ add_time_ids = torch.chunk(add_time_ids, 2, dim=0)[-1]
1205
+ # expand the latents if we are doing classifier free guidance
1206
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1207
+
1208
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1209
+
1210
+ # predict the noise residual
1211
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1212
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1213
+ added_cond_kwargs["image_embeds"] = image_embeds
1214
+ noise_pred = self.unet(
1215
+ latent_model_input,
1216
+ t,
1217
+ encoder_hidden_states=prompt_embeds,
1218
+ timestep_cond=timestep_cond,
1219
+ cross_attention_kwargs=self.cross_attention_kwargs,
1220
+ added_cond_kwargs=added_cond_kwargs,
1221
+ return_dict=False,
1222
+ )[0]
1223
+
1224
+ # perform guidance
1225
+ if do_classifier_free_guidance:
1226
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1227
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1228
+
1229
+ if do_classifier_free_guidance and self.guidance_rescale > 0.0:
1230
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1231
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1232
+
1233
+ # compute the previous noisy sample x_t -> x_t-1
1234
+ latents_dtype = latents.dtype
1235
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1236
+ if latents.dtype != latents_dtype:
1237
+ if torch.backends.mps.is_available():
1238
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1239
+ latents = latents.to(latents_dtype)
1240
+
1241
+ if callback_on_step_end is not None:
1242
+ callback_kwargs = {}
1243
+ for k in callback_on_step_end_tensor_inputs:
1244
+ callback_kwargs[k] = locals()[k]
1245
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1246
+
1247
+ latents = callback_outputs.pop("latents", latents)
1248
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1249
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1250
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1251
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1252
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1253
+ )
1254
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1255
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1256
+
1257
+ # call the callback, if provided
1258
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1259
+ progress_bar.update()
1260
+ if callback is not None and i % callback_steps == 0:
1261
+ step_idx = i // getattr(self.scheduler, "order", 1)
1262
+ callback(step_idx, t, latents)
1263
+
1264
+ if XLA_AVAILABLE:
1265
+ xm.mark_step()
1266
+
1267
+ if not output_type == "latent":
1268
+ # make sure the VAE is in float32 mode, as it overflows in float16
1269
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1270
+
1271
+ if needs_upcasting:
1272
+ self.upcast_vae()
1273
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1274
+ elif latents.dtype != self.vae.dtype:
1275
+ if torch.backends.mps.is_available():
1276
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1277
+ self.vae = self.vae.to(latents.dtype)
1278
+
1279
+ # unscale/denormalize the latents
1280
+ # denormalize with the mean and std if available and not None
1281
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1282
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1283
+ if has_latents_mean and has_latents_std:
1284
+ latents_mean = (
1285
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1286
+ )
1287
+ latents_std = (
1288
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1289
+ )
1290
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1291
+ else:
1292
+ latents = latents / self.vae.config.scaling_factor
1293
+
1294
+ image = self.vae.decode(latents, return_dict=False)[0]
1295
+
1296
+ # cast back to fp16 if needed
1297
+ if needs_upcasting:
1298
+ self.vae.to(dtype=torch.float16)
1299
+ else:
1300
+ image = latents
1301
+
1302
+ if not output_type == "latent":
1303
+ # apply watermark if available
1304
+ if self.watermark is not None:
1305
+ image = self.watermark.apply_watermark(image)
1306
+
1307
+ image = self.image_processor.postprocess(image, output_type=output_type)
1308
+
1309
+ # Offload all models
1310
+ self.maybe_free_model_hooks()
1311
+
1312
+ if not return_dict:
1313
+ return (image,)
1314
+
1315
+ return StableDiffusionXLPipelineOutput(images=image)
1316
+
1317
+ from onediffx import compile_pipe
1318
+
1319
+ def load_pipeline(pipeline=None) -> StableDiffusionXLPipeline:
1320
+ if not pipeline:
1321
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
1322
+ "./models/newdream-sdxl-20",
1323
+ torch_dtype=torch.float16,
1324
+ local_files_only=True,
1325
+ ).to("cuda")
1326
+ pipeline.vae = AutoencoderTiny.from_pretrained("madebyollin/taesdxl", torch_dtype=torch.float16).to('cuda')
1327
+ pipeline = compile_pipe(pipeline)
1328
+ for _ in range(2):
1329
+ pipeline(prompt="", num_inference_steps=10)
1330
+
1331
+ return pipeline
1332
+
1333
+
1334
+
1335
+ def infer(request: TextToImageRequest, pipeline: StableDiffusionXLPipeline) -> Image:
1336
+ generator = Generator(pipeline.device).manual_seed(request.seed) if request.seed else None
1337
+
1338
+ return pipeline(
1339
+ prompt=request.prompt,
1340
+ negative_prompt=request.negative_prompt,
1341
+ width=request.width,
1342
+ height=request.height,
1343
+ generator=generator,
1344
+ num_inference_steps=10,
1345
+ ).images[0]