zhiweili commited on
Commit
87f06d9
1 Parent(s): 3125693

add app_haircolor

Browse files
app.py CHANGED
@@ -1,10 +1,10 @@
1
  import gradio as gr
2
 
3
- from app_img2img import create_demo as create_demo_face
4
 
5
  with gr.Blocks(css="style.css") as demo:
6
  with gr.Tabs():
7
- with gr.Tab(label="Face"):
8
- create_demo_face()
9
 
10
  demo.launch()
 
1
  import gradio as gr
2
 
3
+ from app_haircolor import create_demo as create_demo_haircolor
4
 
5
  with gr.Blocks(css="style.css") as demo:
6
  with gr.Tabs():
7
+ with gr.Tab(label="Hair Color"):
8
+ create_demo_haircolor()
9
 
10
  demo.launch()
app_haircolor.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import time
4
+ import torch
5
+
6
+ from PIL import Image
7
+ from segment_utils import(
8
+ segment_image,
9
+ restore_result,
10
+ )
11
+ from diffusers import (
12
+ DiffusionPipeline,
13
+ T2IAdapter,
14
+ )
15
+
16
+ from controlnet_aux import (
17
+ LineartDetector,
18
+ )
19
+
20
+ BASE_MODEL = "stabilityai/sdxl-turbo"
21
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
22
+
23
+ DEFAULT_EDIT_PROMPT = "a woman, blue hair, high detailed"
24
+ DEFAULT_NEGATIVE_PROMPT = "worst quality, normal quality, low quality, low res, blurry, text, watermark, logo, banner, extra digits, cropped, jpeg artifacts, signature, username, error, sketch ,duplicate, ugly, monochrome, horror, geometry, mutation, disgusting, poorly drawn face, bad face, fused face, ugly face, worst face, asymmetrical, unrealistic skin texture, bad proportions, out of frame, poorly drawn hands, cloned face, double face"
25
+
26
+ DEFAULT_CATEGORY = "hair"
27
+
28
+ lineart_detector = LineartDetector.from_pretrained("lllyasviel/Annotators")
29
+ lineart_detector = lineart_detector.to(DEVICE)
30
+
31
+ adapter = T2IAdapter.from_pretrained(
32
+ "TencentARC/t2i-adapter-lineart-sdxl-1.0",
33
+ torch_dtype=torch.float16,
34
+ varient="fp16",
35
+ )
36
+
37
+
38
+ basepipeline = DiffusionPipeline.from_pretrained(
39
+ BASE_MODEL,
40
+ torch_dtype=torch.float16,
41
+ use_safetensors=True,
42
+ adapter=adapter,
43
+ custom_pipeline="./pipelines/pipeline_sdxl_adapter_img2img.py",
44
+ )
45
+
46
+ basepipeline = basepipeline.to(DEVICE)
47
+
48
+ basepipeline.enable_model_cpu_offload()
49
+
50
+ @spaces.GPU(duration=10)
51
+ def image_to_image(
52
+ input_image: Image,
53
+ edit_prompt: str,
54
+ seed: int,
55
+ num_steps: int,
56
+ guidance_scale: float,
57
+ generate_size: int,
58
+ adapter_weight: float = 1.0,
59
+ ):
60
+ run_task_time = 0
61
+ time_cost_str = ''
62
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
63
+ lineart_image = lineart_detector(input_image, int(generate_size*0.375), generate_size)
64
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
65
+ generator = torch.Generator(device=DEVICE).manual_seed(seed)
66
+ generated_image = basepipeline(
67
+ generator=generator,
68
+ prompt=edit_prompt,
69
+ negative_prompt=DEFAULT_NEGATIVE_PROMPT,
70
+ image=input_image,
71
+ height=generate_size,
72
+ width=generate_size,
73
+ guidance_scale=guidance_scale,
74
+ num_inference_steps=num_steps,
75
+ adapter_image=lineart_image,
76
+ adapter_conditioning_scale=adapter_weight,
77
+ ).images[0]
78
+
79
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
80
+
81
+ return generated_image, time_cost_str
82
+
83
+ def get_time_cost(run_task_time, time_cost_str):
84
+ now_time = int(time.time()*1000)
85
+ if run_task_time == 0:
86
+ time_cost_str = 'start'
87
+ else:
88
+ if time_cost_str != '':
89
+ time_cost_str += f'-->'
90
+ time_cost_str += f'{now_time - run_task_time}'
91
+ run_task_time = now_time
92
+ return run_task_time, time_cost_str
93
+
94
+ def create_demo() -> gr.Blocks:
95
+ with gr.Blocks() as demo:
96
+ croper = gr.State()
97
+ with gr.Row():
98
+ with gr.Column():
99
+ edit_prompt = gr.Textbox(lines=1, label="Edit Prompt", value=DEFAULT_EDIT_PROMPT)
100
+ generate_size = gr.Number(label="Generate Size", value=1024)
101
+ category = gr.Textbox(label="Category", value=DEFAULT_CATEGORY, visible=False)
102
+ with gr.Column():
103
+ num_steps = gr.Slider(minimum=1, maximum=100, value=30, step=1, label="Num Steps")
104
+ guidance_scale = gr.Slider(minimum=0, maximum=30, value=5, step=0.5, label="Guidance Scale")
105
+ mask_expansion = gr.Number(label="Mask Expansion", value=50, visible=True)
106
+ with gr.Column():
107
+ mask_dilation = gr.Slider(minimum=0, maximum=10, value=2, step=1, label="Mask Dilation")
108
+ seed = gr.Number(label="Seed", value=8)
109
+ g_btn = gr.Button("Edit Image")
110
+
111
+ with gr.Row():
112
+ with gr.Column():
113
+ input_image = gr.Image(label="Input Image", type="pil")
114
+ with gr.Column():
115
+ restored_image = gr.Image(label="Restored Image", type="pil", interactive=False)
116
+ with gr.Column():
117
+ origin_area_image = gr.Image(label="Origin Area Image", type="pil", interactive=False)
118
+ generated_image = gr.Image(label="Generated Image", type="pil", interactive=False)
119
+ generated_cost = gr.Textbox(label="Time cost by step (ms):", visible=True, interactive=False)
120
+
121
+ g_btn.click(
122
+ fn=segment_image,
123
+ inputs=[input_image, category, generate_size, mask_expansion, mask_dilation],
124
+ outputs=[origin_area_image, croper],
125
+ ).success(
126
+ fn=image_to_image,
127
+ inputs=[origin_area_image, edit_prompt,seed, num_steps, guidance_scale],
128
+ outputs=[generated_image, generated_cost],
129
+ ).success(
130
+ fn=restore_result,
131
+ inputs=[croper, category, generated_image],
132
+ outputs=[restored_image],
133
+ )
134
+
135
+ return demo
pipelines/pipeline_sdxl_adapter_img2img.py ADDED
@@ -0,0 +1,1672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from transformers import (
22
+ CLIPImageProcessor,
23
+ CLIPTextModel,
24
+ CLIPTextModelWithProjection,
25
+ CLIPTokenizer,
26
+ CLIPVisionModelWithProjection,
27
+ )
28
+
29
+ from diffusers.callbacks import (
30
+ MultiPipelineCallbacks,
31
+ PipelineCallback,
32
+ )
33
+
34
+ from diffusers.image_processor import (
35
+ PipelineImageInput,
36
+ VaeImageProcessor,
37
+ )
38
+
39
+ from diffusers.loaders import (
40
+ FromSingleFileMixin,
41
+ IPAdapterMixin,
42
+ StableDiffusionXLLoraLoaderMixin,
43
+ TextualInversionLoaderMixin,
44
+ )
45
+
46
+ from diffusers.models import (
47
+ AutoencoderKL,
48
+ ImageProjection,
49
+ MultiAdapter,
50
+ T2IAdapter,
51
+ UNet2DConditionModel,
52
+ )
53
+
54
+ from diffusers.models.attention_processor import (
55
+ AttnProcessor2_0,
56
+ XFormersAttnProcessor,
57
+ )
58
+
59
+ from diffusers.models.lora import (
60
+ adjust_lora_scale_text_encoder,
61
+ )
62
+
63
+ from diffusers.schedulers import (
64
+ KarrasDiffusionSchedulers,
65
+ )
66
+
67
+ from diffusers.utils import (
68
+ PIL_INTERPOLATION,
69
+ USE_PEFT_BACKEND,
70
+ deprecate,
71
+ is_invisible_watermark_available,
72
+ is_torch_xla_available,
73
+ logging,
74
+ replace_example_docstring,
75
+ scale_lora_layers,
76
+ unscale_lora_layers,
77
+ )
78
+
79
+ from diffusers.utils.torch_utils import (
80
+ randn_tensor,
81
+ )
82
+
83
+ from diffusers.pipelines.pipeline_utils import (
84
+ DiffusionPipeline,
85
+ StableDiffusionMixin,
86
+ )
87
+
88
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import (
89
+ StableDiffusionXLPipelineOutput,
90
+ )
91
+
92
+
93
+ if is_invisible_watermark_available():
94
+ from diffusers.pipelines.stable_diffusion_xl.watermark import (
95
+ StableDiffusionXLWatermarker,
96
+ )
97
+
98
+ if is_torch_xla_available():
99
+ import torch_xla.core.xla_model as xm
100
+
101
+ XLA_AVAILABLE = True
102
+ else:
103
+ XLA_AVAILABLE = False
104
+
105
+
106
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
107
+
108
+ EXAMPLE_DOC_STRING = """
109
+ Examples:
110
+ ```py
111
+ >>> import torch
112
+ >>> from diffusers import StableDiffusionXLImg2ImgPipeline
113
+ >>> from diffusers.utils import load_image
114
+
115
+ >>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
116
+ ... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
117
+ ... )
118
+ >>> pipe = pipe.to("cuda")
119
+ >>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
120
+
121
+ >>> init_image = load_image(url).convert("RGB")
122
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
123
+ >>> image = pipe(prompt, image=init_image).images[0]
124
+ ```
125
+ """
126
+
127
+
128
+ def _preprocess_adapter_image(image, height, width):
129
+ if isinstance(image, torch.Tensor):
130
+ return image
131
+ elif isinstance(image, PIL.Image.Image):
132
+ image = [image]
133
+
134
+ if isinstance(image[0], PIL.Image.Image):
135
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
136
+ image = [
137
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
138
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
139
+ image = np.concatenate(image, axis=0)
140
+ image = np.array(image).astype(np.float32) / 255.0
141
+ image = image.transpose(0, 3, 1, 2)
142
+ image = torch.from_numpy(image)
143
+ elif isinstance(image[0], torch.Tensor):
144
+ if image[0].ndim == 3:
145
+ image = torch.stack(image, dim=0)
146
+ elif image[0].ndim == 4:
147
+ image = torch.cat(image, dim=0)
148
+ else:
149
+ raise ValueError(
150
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
151
+ )
152
+ return image
153
+
154
+
155
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
156
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
157
+ """
158
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
159
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
160
+ """
161
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
162
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
163
+ # rescale the results from guidance (fixes overexposure)
164
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
165
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
166
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
167
+ return noise_cfg
168
+
169
+
170
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
171
+ def retrieve_latents(
172
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
173
+ ):
174
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
175
+ return encoder_output.latent_dist.sample(generator)
176
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
177
+ return encoder_output.latent_dist.mode()
178
+ elif hasattr(encoder_output, "latents"):
179
+ return encoder_output.latents
180
+ else:
181
+ raise AttributeError("Could not access latents of provided encoder_output")
182
+
183
+
184
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
185
+ def retrieve_timesteps(
186
+ scheduler,
187
+ num_inference_steps: Optional[int] = None,
188
+ device: Optional[Union[str, torch.device]] = None,
189
+ timesteps: Optional[List[int]] = None,
190
+ sigmas: Optional[List[float]] = None,
191
+ **kwargs,
192
+ ):
193
+ """
194
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
195
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
196
+
197
+ Args:
198
+ scheduler (`SchedulerMixin`):
199
+ The scheduler to get timesteps from.
200
+ num_inference_steps (`int`):
201
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
202
+ must be `None`.
203
+ device (`str` or `torch.device`, *optional*):
204
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
205
+ timesteps (`List[int]`, *optional*):
206
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
207
+ `num_inference_steps` and `sigmas` must be `None`.
208
+ sigmas (`List[float]`, *optional*):
209
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
210
+ `num_inference_steps` and `timesteps` must be `None`.
211
+
212
+ Returns:
213
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
214
+ second element is the number of inference steps.
215
+ """
216
+ if timesteps is not None and sigmas is not None:
217
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
218
+ if timesteps is not None:
219
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
220
+ if not accepts_timesteps:
221
+ raise ValueError(
222
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
223
+ f" timestep schedules. Please check whether you are using the correct scheduler."
224
+ )
225
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
226
+ timesteps = scheduler.timesteps
227
+ num_inference_steps = len(timesteps)
228
+ elif sigmas is not None:
229
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
230
+ if not accept_sigmas:
231
+ raise ValueError(
232
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
233
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
234
+ )
235
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
236
+ timesteps = scheduler.timesteps
237
+ num_inference_steps = len(timesteps)
238
+ else:
239
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
240
+ timesteps = scheduler.timesteps
241
+ return timesteps, num_inference_steps
242
+
243
+
244
+ class StableDiffusionXLImg2ImgPipeline(
245
+ DiffusionPipeline,
246
+ StableDiffusionMixin,
247
+ TextualInversionLoaderMixin,
248
+ FromSingleFileMixin,
249
+ StableDiffusionXLLoraLoaderMixin,
250
+ IPAdapterMixin,
251
+ ):
252
+ r"""
253
+ Pipeline for text-to-image generation using Stable Diffusion XL.
254
+
255
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
256
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
257
+
258
+ The pipeline also inherits the following loading methods:
259
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
260
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
261
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
262
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
263
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
264
+
265
+ Args:
266
+ vae ([`AutoencoderKL`]):
267
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
268
+ text_encoder ([`CLIPTextModel`]):
269
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
270
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
271
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
272
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
273
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
274
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
275
+ specifically the
276
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
277
+ variant.
278
+ tokenizer (`CLIPTokenizer`):
279
+ Tokenizer of class
280
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
281
+ tokenizer_2 (`CLIPTokenizer`):
282
+ Second Tokenizer of class
283
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
284
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
285
+ scheduler ([`SchedulerMixin`]):
286
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
287
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
288
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
289
+ Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
290
+ config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
291
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
292
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
293
+ `stabilityai/stable-diffusion-xl-base-1-0`.
294
+ add_watermarker (`bool`, *optional*):
295
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
296
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
297
+ watermarker will be used.
298
+ """
299
+
300
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
301
+ _optional_components = [
302
+ "tokenizer",
303
+ "tokenizer_2",
304
+ "text_encoder",
305
+ "text_encoder_2",
306
+ "image_encoder",
307
+ "feature_extractor",
308
+ ]
309
+ _callback_tensor_inputs = [
310
+ "latents",
311
+ "prompt_embeds",
312
+ "negative_prompt_embeds",
313
+ "add_text_embeds",
314
+ "add_time_ids",
315
+ "negative_pooled_prompt_embeds",
316
+ "add_neg_time_ids",
317
+ ]
318
+
319
+ def __init__(
320
+ self,
321
+ vae: AutoencoderKL,
322
+ text_encoder: CLIPTextModel,
323
+ text_encoder_2: CLIPTextModelWithProjection,
324
+ tokenizer: CLIPTokenizer,
325
+ tokenizer_2: CLIPTokenizer,
326
+ unet: UNet2DConditionModel,
327
+ adapter: Union[T2IAdapter, MultiAdapter, List[T2IAdapter]],
328
+ scheduler: KarrasDiffusionSchedulers,
329
+ image_encoder: CLIPVisionModelWithProjection = None,
330
+ feature_extractor: CLIPImageProcessor = None,
331
+ requires_aesthetics_score: bool = False,
332
+ force_zeros_for_empty_prompt: bool = True,
333
+ add_watermarker: Optional[bool] = None,
334
+ ):
335
+ super().__init__()
336
+
337
+ self.register_modules(
338
+ vae=vae,
339
+ text_encoder=text_encoder,
340
+ text_encoder_2=text_encoder_2,
341
+ tokenizer=tokenizer,
342
+ tokenizer_2=tokenizer_2,
343
+ unet=unet,
344
+ adapter=adapter,
345
+ image_encoder=image_encoder,
346
+ feature_extractor=feature_extractor,
347
+ scheduler=scheduler,
348
+ )
349
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
350
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
351
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
352
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
353
+
354
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
355
+
356
+ if add_watermarker:
357
+ self.watermark = StableDiffusionXLWatermarker()
358
+ else:
359
+ self.watermark = None
360
+
361
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
362
+ def encode_prompt(
363
+ self,
364
+ prompt: str,
365
+ prompt_2: Optional[str] = None,
366
+ device: Optional[torch.device] = None,
367
+ num_images_per_prompt: int = 1,
368
+ do_classifier_free_guidance: bool = True,
369
+ negative_prompt: Optional[str] = None,
370
+ negative_prompt_2: Optional[str] = None,
371
+ prompt_embeds: Optional[torch.Tensor] = None,
372
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
373
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
374
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
375
+ lora_scale: Optional[float] = None,
376
+ clip_skip: Optional[int] = None,
377
+ ):
378
+ r"""
379
+ Encodes the prompt into text encoder hidden states.
380
+
381
+ Args:
382
+ prompt (`str` or `List[str]`, *optional*):
383
+ prompt to be encoded
384
+ prompt_2 (`str` or `List[str]`, *optional*):
385
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
386
+ used in both text-encoders
387
+ device: (`torch.device`):
388
+ torch device
389
+ num_images_per_prompt (`int`):
390
+ number of images that should be generated per prompt
391
+ do_classifier_free_guidance (`bool`):
392
+ whether to use classifier free guidance or not
393
+ negative_prompt (`str` or `List[str]`, *optional*):
394
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
395
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
396
+ less than `1`).
397
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
398
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
399
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
400
+ prompt_embeds (`torch.Tensor`, *optional*):
401
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
402
+ provided, text embeddings will be generated from `prompt` input argument.
403
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
404
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
405
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
406
+ argument.
407
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
408
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
409
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
410
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
411
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
412
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
413
+ input argument.
414
+ lora_scale (`float`, *optional*):
415
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
416
+ clip_skip (`int`, *optional*):
417
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
418
+ the output of the pre-final layer will be used for computing the prompt embeddings.
419
+ """
420
+ device = device or self._execution_device
421
+
422
+ # set lora scale so that monkey patched LoRA
423
+ # function of text encoder can correctly access it
424
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
425
+ self._lora_scale = lora_scale
426
+
427
+ # dynamically adjust the LoRA scale
428
+ if self.text_encoder is not None:
429
+ if not USE_PEFT_BACKEND:
430
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
431
+ else:
432
+ scale_lora_layers(self.text_encoder, lora_scale)
433
+
434
+ if self.text_encoder_2 is not None:
435
+ if not USE_PEFT_BACKEND:
436
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
437
+ else:
438
+ scale_lora_layers(self.text_encoder_2, lora_scale)
439
+
440
+ prompt = [prompt] if isinstance(prompt, str) else prompt
441
+
442
+ if prompt is not None:
443
+ batch_size = len(prompt)
444
+ else:
445
+ batch_size = prompt_embeds.shape[0]
446
+
447
+ # Define tokenizers and text encoders
448
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
449
+ text_encoders = (
450
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
451
+ )
452
+
453
+ if prompt_embeds is None:
454
+ prompt_2 = prompt_2 or prompt
455
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
456
+
457
+ # textual inversion: process multi-vector tokens if necessary
458
+ prompt_embeds_list = []
459
+ prompts = [prompt, prompt_2]
460
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
461
+ if isinstance(self, TextualInversionLoaderMixin):
462
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
463
+
464
+ text_inputs = tokenizer(
465
+ prompt,
466
+ padding="max_length",
467
+ max_length=tokenizer.model_max_length,
468
+ truncation=True,
469
+ return_tensors="pt",
470
+ )
471
+
472
+ text_input_ids = text_inputs.input_ids
473
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
474
+
475
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
476
+ text_input_ids, untruncated_ids
477
+ ):
478
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
479
+ logger.warning(
480
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
481
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
482
+ )
483
+
484
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
485
+
486
+ # We are only ALWAYS interested in the pooled output of the final text encoder
487
+ pooled_prompt_embeds = prompt_embeds[0]
488
+ if clip_skip is None:
489
+ prompt_embeds = prompt_embeds.hidden_states[-2]
490
+ else:
491
+ # "2" because SDXL always indexes from the penultimate layer.
492
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
493
+
494
+ prompt_embeds_list.append(prompt_embeds)
495
+
496
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
497
+
498
+ # get unconditional embeddings for classifier free guidance
499
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
500
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
501
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
502
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
503
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
504
+ negative_prompt = negative_prompt or ""
505
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
506
+
507
+ # normalize str to list
508
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
509
+ negative_prompt_2 = (
510
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
511
+ )
512
+
513
+ uncond_tokens: List[str]
514
+ if prompt is not None and type(prompt) is not type(negative_prompt):
515
+ raise TypeError(
516
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
517
+ f" {type(prompt)}."
518
+ )
519
+ elif batch_size != len(negative_prompt):
520
+ raise ValueError(
521
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
522
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
523
+ " the batch size of `prompt`."
524
+ )
525
+ else:
526
+ uncond_tokens = [negative_prompt, negative_prompt_2]
527
+
528
+ negative_prompt_embeds_list = []
529
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
530
+ if isinstance(self, TextualInversionLoaderMixin):
531
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
532
+
533
+ max_length = prompt_embeds.shape[1]
534
+ uncond_input = tokenizer(
535
+ negative_prompt,
536
+ padding="max_length",
537
+ max_length=max_length,
538
+ truncation=True,
539
+ return_tensors="pt",
540
+ )
541
+
542
+ negative_prompt_embeds = text_encoder(
543
+ uncond_input.input_ids.to(device),
544
+ output_hidden_states=True,
545
+ )
546
+ # We are only ALWAYS interested in the pooled output of the final text encoder
547
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
548
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
549
+
550
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
551
+
552
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
553
+
554
+ if self.text_encoder_2 is not None:
555
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
556
+ else:
557
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
558
+
559
+ bs_embed, seq_len, _ = prompt_embeds.shape
560
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
561
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
562
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
563
+
564
+ if do_classifier_free_guidance:
565
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
566
+ seq_len = negative_prompt_embeds.shape[1]
567
+
568
+ if self.text_encoder_2 is not None:
569
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
570
+ else:
571
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
572
+
573
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
574
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
575
+
576
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
577
+ bs_embed * num_images_per_prompt, -1
578
+ )
579
+ if do_classifier_free_guidance:
580
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
581
+ bs_embed * num_images_per_prompt, -1
582
+ )
583
+
584
+ if self.text_encoder is not None:
585
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
586
+ # Retrieve the original scale by scaling back the LoRA layers
587
+ unscale_lora_layers(self.text_encoder, lora_scale)
588
+
589
+ if self.text_encoder_2 is not None:
590
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
591
+ # Retrieve the original scale by scaling back the LoRA layers
592
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
593
+
594
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
595
+
596
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
597
+ def prepare_ip_adapter_image_embeds(
598
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
599
+ ):
600
+ image_embeds = []
601
+ if do_classifier_free_guidance:
602
+ negative_image_embeds = []
603
+ if ip_adapter_image_embeds is None:
604
+ if not isinstance(ip_adapter_image, list):
605
+ ip_adapter_image = [ip_adapter_image]
606
+
607
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
608
+ raise ValueError(
609
+ 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."
610
+ )
611
+
612
+ for single_ip_adapter_image, image_proj_layer in zip(
613
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
614
+ ):
615
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
616
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
617
+ single_ip_adapter_image, device, 1, output_hidden_state
618
+ )
619
+
620
+ image_embeds.append(single_image_embeds[None, :])
621
+ if do_classifier_free_guidance:
622
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
623
+ else:
624
+ for single_image_embeds in ip_adapter_image_embeds:
625
+ if do_classifier_free_guidance:
626
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
627
+ negative_image_embeds.append(single_negative_image_embeds)
628
+ image_embeds.append(single_image_embeds)
629
+
630
+ ip_adapter_image_embeds = []
631
+ for i, single_image_embeds in enumerate(image_embeds):
632
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
633
+ if do_classifier_free_guidance:
634
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
635
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
636
+
637
+ single_image_embeds = single_image_embeds.to(device=device)
638
+ ip_adapter_image_embeds.append(single_image_embeds)
639
+
640
+ return ip_adapter_image_embeds
641
+
642
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
643
+ def prepare_extra_step_kwargs(self, generator, eta):
644
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
645
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
646
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
647
+ # and should be between [0, 1]
648
+
649
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
650
+ extra_step_kwargs = {}
651
+ if accepts_eta:
652
+ extra_step_kwargs["eta"] = eta
653
+
654
+ # check if the scheduler accepts generator
655
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
656
+ if accepts_generator:
657
+ extra_step_kwargs["generator"] = generator
658
+ return extra_step_kwargs
659
+
660
+ def check_inputs(
661
+ self,
662
+ prompt,
663
+ prompt_2,
664
+ strength,
665
+ num_inference_steps,
666
+ callback_steps,
667
+ negative_prompt=None,
668
+ negative_prompt_2=None,
669
+ prompt_embeds=None,
670
+ negative_prompt_embeds=None,
671
+ ip_adapter_image=None,
672
+ ip_adapter_image_embeds=None,
673
+ callback_on_step_end_tensor_inputs=None,
674
+ ):
675
+ if strength < 0 or strength > 1:
676
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
677
+ if num_inference_steps is None:
678
+ raise ValueError("`num_inference_steps` cannot be None.")
679
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
680
+ raise ValueError(
681
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
682
+ f" {type(num_inference_steps)}."
683
+ )
684
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
685
+ raise ValueError(
686
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
687
+ f" {type(callback_steps)}."
688
+ )
689
+
690
+ if callback_on_step_end_tensor_inputs is not None and not all(
691
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
692
+ ):
693
+ raise ValueError(
694
+ 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]}"
695
+ )
696
+
697
+ if prompt is not None and prompt_embeds is not None:
698
+ raise ValueError(
699
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
700
+ " only forward one of the two."
701
+ )
702
+ elif prompt_2 is not None and prompt_embeds is not None:
703
+ raise ValueError(
704
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
705
+ " only forward one of the two."
706
+ )
707
+ elif prompt is None and prompt_embeds is None:
708
+ raise ValueError(
709
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
710
+ )
711
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
712
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
713
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
714
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
715
+
716
+ if negative_prompt is not None and negative_prompt_embeds is not None:
717
+ raise ValueError(
718
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
719
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
720
+ )
721
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
722
+ raise ValueError(
723
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
724
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
725
+ )
726
+
727
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
728
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
729
+ raise ValueError(
730
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
731
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
732
+ f" {negative_prompt_embeds.shape}."
733
+ )
734
+
735
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
736
+ raise ValueError(
737
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
738
+ )
739
+
740
+ if ip_adapter_image_embeds is not None:
741
+ if not isinstance(ip_adapter_image_embeds, list):
742
+ raise ValueError(
743
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
744
+ )
745
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
746
+ raise ValueError(
747
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
748
+ )
749
+
750
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
751
+ # get the original timestep using init_timestep
752
+ if denoising_start is None:
753
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
754
+ t_start = max(num_inference_steps - init_timestep, 0)
755
+ else:
756
+ t_start = 0
757
+
758
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
759
+
760
+ # Strength is irrelevant if we directly request a timestep to start at;
761
+ # that is, strength is determined by the denoising_start instead.
762
+ if denoising_start is not None:
763
+ discrete_timestep_cutoff = int(
764
+ round(
765
+ self.scheduler.config.num_train_timesteps
766
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
767
+ )
768
+ )
769
+
770
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
771
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
772
+ # if the scheduler is a 2nd order scheduler we might have to do +1
773
+ # because `num_inference_steps` might be even given that every timestep
774
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
775
+ # mean that we cut the timesteps in the middle of the denoising step
776
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
777
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
778
+ num_inference_steps = num_inference_steps + 1
779
+
780
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
781
+ timesteps = timesteps[-num_inference_steps:]
782
+ return timesteps, num_inference_steps
783
+
784
+ return timesteps, num_inference_steps - t_start
785
+
786
+ def prepare_latents(
787
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
788
+ ):
789
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
790
+ raise ValueError(
791
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
792
+ )
793
+
794
+ latents_mean = latents_std = None
795
+ if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
796
+ latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
797
+ if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
798
+ latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
799
+
800
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
801
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
802
+ self.text_encoder_2.to("cpu")
803
+ torch.cuda.empty_cache()
804
+
805
+ image = image.to(device=device, dtype=dtype)
806
+
807
+ batch_size = batch_size * num_images_per_prompt
808
+
809
+ if image.shape[1] == 4:
810
+ init_latents = image
811
+
812
+ else:
813
+ # make sure the VAE is in float32 mode, as it overflows in float16
814
+ if self.vae.config.force_upcast:
815
+ image = image.float()
816
+ self.vae.to(dtype=torch.float32)
817
+
818
+ if isinstance(generator, list) and len(generator) != batch_size:
819
+ raise ValueError(
820
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
821
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
822
+ )
823
+
824
+ elif isinstance(generator, list):
825
+ if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
826
+ image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
827
+ elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
828
+ raise ValueError(
829
+ f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
830
+ )
831
+
832
+ init_latents = [
833
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
834
+ for i in range(batch_size)
835
+ ]
836
+ init_latents = torch.cat(init_latents, dim=0)
837
+ else:
838
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
839
+
840
+ if self.vae.config.force_upcast:
841
+ self.vae.to(dtype)
842
+
843
+ init_latents = init_latents.to(dtype)
844
+ if latents_mean is not None and latents_std is not None:
845
+ latents_mean = latents_mean.to(device=device, dtype=dtype)
846
+ latents_std = latents_std.to(device=device, dtype=dtype)
847
+ init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
848
+ else:
849
+ init_latents = self.vae.config.scaling_factor * init_latents
850
+
851
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
852
+ # expand init_latents for batch_size
853
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
854
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
855
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
856
+ raise ValueError(
857
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
858
+ )
859
+ else:
860
+ init_latents = torch.cat([init_latents], dim=0)
861
+
862
+ if add_noise:
863
+ shape = init_latents.shape
864
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
865
+ # get latents
866
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
867
+
868
+ latents = init_latents
869
+
870
+ return latents
871
+
872
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
873
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
874
+ dtype = next(self.image_encoder.parameters()).dtype
875
+
876
+ if not isinstance(image, torch.Tensor):
877
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
878
+
879
+ image = image.to(device=device, dtype=dtype)
880
+ if output_hidden_states:
881
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
882
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
883
+ uncond_image_enc_hidden_states = self.image_encoder(
884
+ torch.zeros_like(image), output_hidden_states=True
885
+ ).hidden_states[-2]
886
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
887
+ num_images_per_prompt, dim=0
888
+ )
889
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
890
+ else:
891
+ image_embeds = self.image_encoder(image).image_embeds
892
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
893
+ uncond_image_embeds = torch.zeros_like(image_embeds)
894
+
895
+ return image_embeds, uncond_image_embeds
896
+
897
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
898
+ def prepare_ip_adapter_image_embeds(
899
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
900
+ ):
901
+ image_embeds = []
902
+ if do_classifier_free_guidance:
903
+ negative_image_embeds = []
904
+ if ip_adapter_image_embeds is None:
905
+ if not isinstance(ip_adapter_image, list):
906
+ ip_adapter_image = [ip_adapter_image]
907
+
908
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
909
+ raise ValueError(
910
+ 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."
911
+ )
912
+
913
+ for single_ip_adapter_image, image_proj_layer in zip(
914
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
915
+ ):
916
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
917
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
918
+ single_ip_adapter_image, device, 1, output_hidden_state
919
+ )
920
+
921
+ image_embeds.append(single_image_embeds[None, :])
922
+ if do_classifier_free_guidance:
923
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
924
+ else:
925
+ for single_image_embeds in ip_adapter_image_embeds:
926
+ if do_classifier_free_guidance:
927
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
928
+ negative_image_embeds.append(single_negative_image_embeds)
929
+ image_embeds.append(single_image_embeds)
930
+
931
+ ip_adapter_image_embeds = []
932
+ for i, single_image_embeds in enumerate(image_embeds):
933
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
934
+ if do_classifier_free_guidance:
935
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
936
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
937
+
938
+ single_image_embeds = single_image_embeds.to(device=device)
939
+ ip_adapter_image_embeds.append(single_image_embeds)
940
+
941
+ return ip_adapter_image_embeds
942
+
943
+ def _get_add_time_ids(
944
+ self,
945
+ original_size,
946
+ crops_coords_top_left,
947
+ target_size,
948
+ aesthetic_score,
949
+ negative_aesthetic_score,
950
+ negative_original_size,
951
+ negative_crops_coords_top_left,
952
+ negative_target_size,
953
+ dtype,
954
+ text_encoder_projection_dim=None,
955
+ ):
956
+ if self.config.requires_aesthetics_score:
957
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
958
+ add_neg_time_ids = list(
959
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
960
+ )
961
+ else:
962
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
963
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
964
+
965
+ passed_add_embed_dim = (
966
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
967
+ )
968
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
969
+
970
+ if (
971
+ expected_add_embed_dim > passed_add_embed_dim
972
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
973
+ ):
974
+ raise ValueError(
975
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
976
+ )
977
+ elif (
978
+ expected_add_embed_dim < passed_add_embed_dim
979
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
980
+ ):
981
+ raise ValueError(
982
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
983
+ )
984
+ elif expected_add_embed_dim != passed_add_embed_dim:
985
+ raise ValueError(
986
+ 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`."
987
+ )
988
+
989
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
990
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
991
+
992
+ return add_time_ids, add_neg_time_ids
993
+
994
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
995
+ def upcast_vae(self):
996
+ dtype = self.vae.dtype
997
+ self.vae.to(dtype=torch.float32)
998
+ use_torch_2_0_or_xformers = isinstance(
999
+ self.vae.decoder.mid_block.attentions[0].processor,
1000
+ (
1001
+ AttnProcessor2_0,
1002
+ XFormersAttnProcessor,
1003
+ ),
1004
+ )
1005
+ # if xformers or torch_2_0 is used attention block does not need
1006
+ # to be in float32 which can save lots of memory
1007
+ if use_torch_2_0_or_xformers:
1008
+ self.vae.post_quant_conv.to(dtype)
1009
+ self.vae.decoder.conv_in.to(dtype)
1010
+ self.vae.decoder.mid_block.to(dtype)
1011
+
1012
+ # Copied from diffusers.pipelines.t2i_adapter.pipeline_stable_diffusion_adapter.StableDiffusionAdapterPipeline._default_height_width
1013
+ def _default_height_width(self, height, width, image):
1014
+ # NOTE: It is possible that a list of images have different
1015
+ # dimensions for each image, so just checking the first image
1016
+ # is not _exactly_ correct, but it is simple.
1017
+ while isinstance(image, list):
1018
+ image = image[0]
1019
+
1020
+ if height is None:
1021
+ if isinstance(image, PIL.Image.Image):
1022
+ height = image.height
1023
+ elif isinstance(image, torch.Tensor):
1024
+ height = image.shape[-2]
1025
+
1026
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1027
+ height = (height // self.adapter.downscale_factor) * self.adapter.downscale_factor
1028
+
1029
+ if width is None:
1030
+ if isinstance(image, PIL.Image.Image):
1031
+ width = image.width
1032
+ elif isinstance(image, torch.Tensor):
1033
+ width = image.shape[-1]
1034
+
1035
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1036
+ width = (width // self.adapter.downscale_factor) * self.adapter.downscale_factor
1037
+
1038
+ return height, width
1039
+
1040
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1041
+ def get_guidance_scale_embedding(
1042
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
1043
+ ) -> torch.Tensor:
1044
+ """
1045
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1046
+
1047
+ Args:
1048
+ w (`torch.Tensor`):
1049
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
1050
+ embedding_dim (`int`, *optional*, defaults to 512):
1051
+ Dimension of the embeddings to generate.
1052
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
1053
+ Data type of the generated embeddings.
1054
+
1055
+ Returns:
1056
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1057
+ """
1058
+ assert len(w.shape) == 1
1059
+ w = w * 1000.0
1060
+
1061
+ half_dim = embedding_dim // 2
1062
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1063
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1064
+ emb = w.to(dtype)[:, None] * emb[None, :]
1065
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1066
+ if embedding_dim % 2 == 1: # zero pad
1067
+ emb = torch.nn.functional.pad(emb, (0, 1))
1068
+ assert emb.shape == (w.shape[0], embedding_dim)
1069
+ return emb
1070
+
1071
+ @property
1072
+ def guidance_scale(self):
1073
+ return self._guidance_scale
1074
+
1075
+ @property
1076
+ def guidance_rescale(self):
1077
+ return self._guidance_rescale
1078
+
1079
+ @property
1080
+ def clip_skip(self):
1081
+ return self._clip_skip
1082
+
1083
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1084
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1085
+ # corresponds to doing no classifier free guidance.
1086
+ @property
1087
+ def do_classifier_free_guidance(self):
1088
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1089
+
1090
+ @property
1091
+ def cross_attention_kwargs(self):
1092
+ return self._cross_attention_kwargs
1093
+
1094
+ @property
1095
+ def denoising_end(self):
1096
+ return self._denoising_end
1097
+
1098
+ @property
1099
+ def denoising_start(self):
1100
+ return self._denoising_start
1101
+
1102
+ @property
1103
+ def num_timesteps(self):
1104
+ return self._num_timesteps
1105
+
1106
+ @property
1107
+ def interrupt(self):
1108
+ return self._interrupt
1109
+
1110
+ @torch.no_grad()
1111
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1112
+ def __call__(
1113
+ self,
1114
+ prompt: Union[str, List[str]] = None,
1115
+ prompt_2: Optional[Union[str, List[str]]] = None,
1116
+ image: PipelineImageInput = None,
1117
+ height: Optional[int] = None,
1118
+ width: Optional[int] = None,
1119
+ adapter_image: PipelineImageInput = None,
1120
+ strength: float = 0.3,
1121
+ num_inference_steps: int = 50,
1122
+ timesteps: List[int] = None,
1123
+ sigmas: List[float] = None,
1124
+ denoising_start: Optional[float] = None,
1125
+ denoising_end: Optional[float] = None,
1126
+ guidance_scale: float = 5.0,
1127
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1128
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1129
+ num_images_per_prompt: Optional[int] = 1,
1130
+ eta: float = 0.0,
1131
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1132
+ latents: Optional[torch.Tensor] = None,
1133
+ prompt_embeds: Optional[torch.Tensor] = None,
1134
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1135
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1136
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1137
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1138
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1139
+ output_type: Optional[str] = "pil",
1140
+ return_dict: bool = True,
1141
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1142
+ guidance_rescale: float = 0.0,
1143
+ original_size: Tuple[int, int] = None,
1144
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1145
+ target_size: Tuple[int, int] = None,
1146
+ negative_original_size: Optional[Tuple[int, int]] = None,
1147
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1148
+ negative_target_size: Optional[Tuple[int, int]] = None,
1149
+ aesthetic_score: float = 6.0,
1150
+ negative_aesthetic_score: float = 2.5,
1151
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
1152
+ adapter_conditioning_factor: float = 1.0,
1153
+ clip_skip: Optional[int] = None,
1154
+ callback_on_step_end: Optional[
1155
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1156
+ ] = None,
1157
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1158
+ **kwargs,
1159
+ ):
1160
+ r"""
1161
+ Function invoked when calling the pipeline for generation.
1162
+
1163
+ Args:
1164
+ prompt (`str` or `List[str]`, *optional*):
1165
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1166
+ instead.
1167
+ prompt_2 (`str` or `List[str]`, *optional*):
1168
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1169
+ used in both text-encoders
1170
+ image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
1171
+ The image(s) to modify with the pipeline.
1172
+ strength (`float`, *optional*, defaults to 0.3):
1173
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
1174
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
1175
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
1176
+ be maximum and the denoising process will run for the full number of iterations specified in
1177
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
1178
+ `denoising_start` being declared as an integer, the value of `strength` will be ignored.
1179
+ num_inference_steps (`int`, *optional*, defaults to 50):
1180
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1181
+ expense of slower inference.
1182
+ timesteps (`List[int]`, *optional*):
1183
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1184
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1185
+ passed will be used. Must be in descending order.
1186
+ sigmas (`List[float]`, *optional*):
1187
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1188
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1189
+ will be used.
1190
+ denoising_start (`float`, *optional*):
1191
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1192
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1193
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1194
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1195
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refine Image
1196
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1197
+ denoising_end (`float`, *optional*):
1198
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1199
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1200
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1201
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1202
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1203
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refine Image
1204
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1205
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1206
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1207
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1208
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1209
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1210
+ usually at the expense of lower image quality.
1211
+ negative_prompt (`str` or `List[str]`, *optional*):
1212
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1213
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1214
+ less than `1`).
1215
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1216
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1217
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1218
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1219
+ The number of images to generate per prompt.
1220
+ eta (`float`, *optional*, defaults to 0.0):
1221
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1222
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1223
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1224
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1225
+ to make generation deterministic.
1226
+ latents (`torch.Tensor`, *optional*):
1227
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1228
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1229
+ tensor will ge generated by sampling using the supplied random `generator`.
1230
+ prompt_embeds (`torch.Tensor`, *optional*):
1231
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1232
+ provided, text embeddings will be generated from `prompt` input argument.
1233
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1234
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1235
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1236
+ argument.
1237
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1238
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1239
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1240
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1241
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1242
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1243
+ input argument.
1244
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1245
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1246
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1247
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1248
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1249
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1250
+ output_type (`str`, *optional*, defaults to `"pil"`):
1251
+ The output format of the generate image. Choose between
1252
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1253
+ return_dict (`bool`, *optional*, defaults to `True`):
1254
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
1255
+ plain tuple.
1256
+ cross_attention_kwargs (`dict`, *optional*):
1257
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1258
+ `self.processor` in
1259
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1260
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1261
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1262
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1263
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1264
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1265
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1266
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1267
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1268
+ explained in section 2.2 of
1269
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1270
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1271
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1272
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1273
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1274
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1275
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1276
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1277
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1278
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1279
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1280
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1281
+ micro-conditioning as explained in section 2.2 of
1282
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1283
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1284
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1285
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1286
+ micro-conditioning as explained in section 2.2 of
1287
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1288
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1289
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1290
+ To negatively condition the generation process based on a target image resolution. It should be as same
1291
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1292
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1293
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1294
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1295
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1296
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1297
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1298
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1299
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1300
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1301
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1302
+ clip_skip (`int`, *optional*):
1303
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1304
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1305
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1306
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1307
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1308
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1309
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1310
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1311
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1312
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1313
+ `._callback_tensor_inputs` attribute of your pipeline class.
1314
+
1315
+ Examples:
1316
+
1317
+ Returns:
1318
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1319
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1320
+ `tuple. When returning a tuple, the first element is a list with the generated images.
1321
+ """
1322
+ height, width = self._default_height_width(height, width, adapter_image)
1323
+ device = self._execution_device
1324
+
1325
+ if isinstance(self.adapter, MultiAdapter):
1326
+ adapter_input = []
1327
+
1328
+ for one_image in adapter_image:
1329
+ one_image = _preprocess_adapter_image(one_image, height, width)
1330
+ one_image = one_image.to(device=device, dtype=self.adapter.dtype)
1331
+ adapter_input.append(one_image)
1332
+ else:
1333
+ adapter_input = _preprocess_adapter_image(adapter_image, height, width)
1334
+ adapter_input = adapter_input.to(device=device, dtype=self.adapter.dtype)
1335
+
1336
+ callback = kwargs.pop("callback", None)
1337
+ callback_steps = kwargs.pop("callback_steps", None)
1338
+
1339
+ if callback is not None:
1340
+ deprecate(
1341
+ "callback",
1342
+ "1.0.0",
1343
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1344
+ )
1345
+ if callback_steps is not None:
1346
+ deprecate(
1347
+ "callback_steps",
1348
+ "1.0.0",
1349
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1350
+ )
1351
+
1352
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1353
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1354
+
1355
+ # 1. Check inputs. Raise error if not correct
1356
+ self.check_inputs(
1357
+ prompt,
1358
+ prompt_2,
1359
+ strength,
1360
+ num_inference_steps,
1361
+ callback_steps,
1362
+ negative_prompt,
1363
+ negative_prompt_2,
1364
+ prompt_embeds,
1365
+ negative_prompt_embeds,
1366
+ ip_adapter_image,
1367
+ ip_adapter_image_embeds,
1368
+ callback_on_step_end_tensor_inputs,
1369
+ )
1370
+
1371
+ self._guidance_scale = guidance_scale
1372
+ self._guidance_rescale = guidance_rescale
1373
+ self._clip_skip = clip_skip
1374
+ self._cross_attention_kwargs = cross_attention_kwargs
1375
+ self._denoising_end = denoising_end
1376
+ self._denoising_start = denoising_start
1377
+ self._interrupt = False
1378
+
1379
+ # 2. Define call parameters
1380
+ if prompt is not None and isinstance(prompt, str):
1381
+ batch_size = 1
1382
+ elif prompt is not None and isinstance(prompt, list):
1383
+ batch_size = len(prompt)
1384
+ else:
1385
+ batch_size = prompt_embeds.shape[0]
1386
+
1387
+ device = self._execution_device
1388
+
1389
+ # 3. Encode input prompt
1390
+ text_encoder_lora_scale = (
1391
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1392
+ )
1393
+ (
1394
+ prompt_embeds,
1395
+ negative_prompt_embeds,
1396
+ pooled_prompt_embeds,
1397
+ negative_pooled_prompt_embeds,
1398
+ ) = self.encode_prompt(
1399
+ prompt=prompt,
1400
+ prompt_2=prompt_2,
1401
+ device=device,
1402
+ num_images_per_prompt=num_images_per_prompt,
1403
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1404
+ negative_prompt=negative_prompt,
1405
+ negative_prompt_2=negative_prompt_2,
1406
+ prompt_embeds=prompt_embeds,
1407
+ negative_prompt_embeds=negative_prompt_embeds,
1408
+ pooled_prompt_embeds=pooled_prompt_embeds,
1409
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1410
+ lora_scale=text_encoder_lora_scale,
1411
+ clip_skip=self.clip_skip,
1412
+ )
1413
+
1414
+ # 4. Preprocess image
1415
+ image = self.image_processor.preprocess(image)
1416
+
1417
+ # 5. Prepare timesteps
1418
+ def denoising_value_valid(dnv):
1419
+ return isinstance(dnv, float) and 0 < dnv < 1
1420
+
1421
+ timesteps, num_inference_steps = retrieve_timesteps(
1422
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1423
+ )
1424
+ timesteps, num_inference_steps = self.get_timesteps(
1425
+ num_inference_steps,
1426
+ strength,
1427
+ device,
1428
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1429
+ )
1430
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1431
+
1432
+ add_noise = True if self.denoising_start is None else False
1433
+
1434
+ # 6. Prepare latent variables
1435
+ if latents is None:
1436
+ latents = self.prepare_latents(
1437
+ image,
1438
+ latent_timestep,
1439
+ batch_size,
1440
+ num_images_per_prompt,
1441
+ prompt_embeds.dtype,
1442
+ device,
1443
+ generator,
1444
+ add_noise,
1445
+ )
1446
+ # 7. Prepare extra step kwargs.
1447
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1448
+
1449
+ height, width = latents.shape[-2:]
1450
+ height = height * self.vae_scale_factor
1451
+ width = width * self.vae_scale_factor
1452
+
1453
+ original_size = original_size or (height, width)
1454
+ target_size = target_size or (height, width)
1455
+
1456
+ # 8. Prepare added time ids & embeddings
1457
+ # adapter_input = adapter_input.type(latents.dtype)
1458
+ if isinstance(self.adapter, MultiAdapter):
1459
+ adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
1460
+ for k, v in enumerate(adapter_state):
1461
+ adapter_state[k] = v
1462
+ else:
1463
+ adapter_state = self.adapter(adapter_input)
1464
+ for k, v in enumerate(adapter_state):
1465
+ adapter_state[k] = v * adapter_conditioning_scale
1466
+ if num_images_per_prompt > 1:
1467
+ for k, v in enumerate(adapter_state):
1468
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
1469
+ if self.do_classifier_free_guidance:
1470
+ for k, v in enumerate(adapter_state):
1471
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
1472
+
1473
+ if negative_original_size is None:
1474
+ negative_original_size = original_size
1475
+ if negative_target_size is None:
1476
+ negative_target_size = target_size
1477
+
1478
+ add_text_embeds = pooled_prompt_embeds
1479
+ if self.text_encoder_2 is None:
1480
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1481
+ else:
1482
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1483
+
1484
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1485
+ original_size,
1486
+ crops_coords_top_left,
1487
+ target_size,
1488
+ aesthetic_score,
1489
+ negative_aesthetic_score,
1490
+ negative_original_size,
1491
+ negative_crops_coords_top_left,
1492
+ negative_target_size,
1493
+ dtype=prompt_embeds.dtype,
1494
+ text_encoder_projection_dim=text_encoder_projection_dim,
1495
+ )
1496
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1497
+
1498
+ if self.do_classifier_free_guidance:
1499
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1500
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1501
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1502
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1503
+
1504
+ prompt_embeds = prompt_embeds.to(device)
1505
+ add_text_embeds = add_text_embeds.to(device)
1506
+ add_time_ids = add_time_ids.to(device)
1507
+
1508
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1509
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1510
+ ip_adapter_image,
1511
+ ip_adapter_image_embeds,
1512
+ device,
1513
+ batch_size * num_images_per_prompt,
1514
+ self.do_classifier_free_guidance,
1515
+ )
1516
+
1517
+ # 9. Denoising loop
1518
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1519
+
1520
+ # 9.1 Apply denoising_end
1521
+ if (
1522
+ self.denoising_end is not None
1523
+ and self.denoising_start is not None
1524
+ and denoising_value_valid(self.denoising_end)
1525
+ and denoising_value_valid(self.denoising_start)
1526
+ and self.denoising_start >= self.denoising_end
1527
+ ):
1528
+ raise ValueError(
1529
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
1530
+ + f" {self.denoising_end} when using type float."
1531
+ )
1532
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
1533
+ discrete_timestep_cutoff = int(
1534
+ round(
1535
+ self.scheduler.config.num_train_timesteps
1536
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1537
+ )
1538
+ )
1539
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1540
+ timesteps = timesteps[:num_inference_steps]
1541
+
1542
+ # 9.2 Optionally get Guidance Scale Embedding
1543
+ timestep_cond = None
1544
+ if self.unet.config.time_cond_proj_dim is not None:
1545
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1546
+ timestep_cond = self.get_guidance_scale_embedding(
1547
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1548
+ ).to(device=device, dtype=latents.dtype)
1549
+
1550
+ self._num_timesteps = len(timesteps)
1551
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1552
+ for i, t in enumerate(timesteps):
1553
+ if self.interrupt:
1554
+ continue
1555
+
1556
+ # expand the latents if we are doing classifier free guidance
1557
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1558
+
1559
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1560
+
1561
+ # predict the noise residual
1562
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1563
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1564
+ added_cond_kwargs["image_embeds"] = image_embeds
1565
+
1566
+ if i < int(num_inference_steps * adapter_conditioning_factor):
1567
+ down_intrablock_additional_residuals = [state.clone() for state in adapter_state]
1568
+ else:
1569
+ down_intrablock_additional_residuals = None
1570
+
1571
+ noise_pred = self.unet(
1572
+ latent_model_input,
1573
+ t,
1574
+ encoder_hidden_states=prompt_embeds,
1575
+ timestep_cond=timestep_cond,
1576
+ cross_attention_kwargs=self.cross_attention_kwargs,
1577
+ added_cond_kwargs=added_cond_kwargs,
1578
+ return_dict=False,
1579
+ down_intrablock_additional_residuals=down_intrablock_additional_residuals,
1580
+ )[0]
1581
+
1582
+ # perform guidance
1583
+ if self.do_classifier_free_guidance:
1584
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1585
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1586
+
1587
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1588
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1589
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1590
+
1591
+ # compute the previous noisy sample x_t -> x_t-1
1592
+ latents_dtype = latents.dtype
1593
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1594
+ if latents.dtype != latents_dtype:
1595
+ if torch.backends.mps.is_available():
1596
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1597
+ latents = latents.to(latents_dtype)
1598
+
1599
+ if callback_on_step_end is not None:
1600
+ callback_kwargs = {}
1601
+ for k in callback_on_step_end_tensor_inputs:
1602
+ callback_kwargs[k] = locals()[k]
1603
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1604
+
1605
+ latents = callback_outputs.pop("latents", latents)
1606
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1607
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1608
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1609
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1610
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1611
+ )
1612
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1613
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1614
+
1615
+ # call the callback, if provided
1616
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1617
+ progress_bar.update()
1618
+ if callback is not None and i % callback_steps == 0:
1619
+ step_idx = i // getattr(self.scheduler, "order", 1)
1620
+ callback(step_idx, t, latents)
1621
+
1622
+ if XLA_AVAILABLE:
1623
+ xm.mark_step()
1624
+
1625
+ if not output_type == "latent":
1626
+ # make sure the VAE is in float32 mode, as it overflows in float16
1627
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1628
+
1629
+ if needs_upcasting:
1630
+ self.upcast_vae()
1631
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1632
+ elif latents.dtype != self.vae.dtype:
1633
+ if torch.backends.mps.is_available():
1634
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1635
+ self.vae = self.vae.to(latents.dtype)
1636
+
1637
+ # unscale/denormalize the latents
1638
+ # denormalize with the mean and std if available and not None
1639
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1640
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1641
+ if has_latents_mean and has_latents_std:
1642
+ latents_mean = (
1643
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1644
+ )
1645
+ latents_std = (
1646
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1647
+ )
1648
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1649
+ else:
1650
+ latents = latents / self.vae.config.scaling_factor
1651
+
1652
+ image = self.vae.decode(latents, return_dict=False)[0]
1653
+
1654
+ # cast back to fp16 if needed
1655
+ if needs_upcasting:
1656
+ self.vae.to(dtype=torch.float16)
1657
+ else:
1658
+ image = latents
1659
+
1660
+ # apply watermark if available
1661
+ if self.watermark is not None:
1662
+ image = self.watermark.apply_watermark(image)
1663
+
1664
+ image = self.image_processor.postprocess(image, output_type=output_type)
1665
+
1666
+ # Offload all models
1667
+ self.maybe_free_model_hooks()
1668
+
1669
+ if not return_dict:
1670
+ return (image,)
1671
+
1672
+ return StableDiffusionXLPipelineOutput(images=image)
requirements.txt CHANGED
@@ -5,4 +5,7 @@ diffusers
5
  transformers
6
  accelerate
7
  mediapipe
8
- spaces
 
 
 
 
5
  transformers
6
  accelerate
7
  mediapipe
8
+ spaces
9
+ sentencepiece
10
+ controlnet_aux
11
+ peft