EpicJhon commited on
Commit
c4f2ea6
1 Parent(s): 64e668e

Initial commit with folder contents

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