zhiweili commited on
Commit
963fadc
1 Parent(s): 37a1718

chnage to adapter

Browse files
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
 
3
- from app_haircolor_inpaint_15 import create_demo as create_demo_haircolor
4
 
5
  with gr.Blocks(css="style.css") as demo:
6
  with gr.Tabs():
 
1
  import gradio as gr
2
 
3
+ from app_haircolor_inpaint_adapter_15 import create_demo as create_demo_haircolor
4
 
5
  with gr.Blocks(css="style.css") as demo:
6
  with gr.Tabs():
app_haircolor_inpaint_adapter_15.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ import time
4
+ import torch
5
+ import numpy as np
6
+
7
+ from PIL import Image
8
+ from segment_utils import(
9
+ segment_image_withmask,
10
+ restore_result,
11
+ )
12
+ from diffusers import (
13
+ DiffusionPipeline,
14
+ DDIMScheduler,
15
+ AutoencoderKL,
16
+ EulerAncestralDiscreteScheduler,
17
+ T2IAdapter,
18
+ MultiAdapter,
19
+ )
20
+
21
+ from controlnet_aux import (
22
+ CannyDetector,
23
+ LineartDetector,
24
+ PidiNetDetector,
25
+ HEDdetector,
26
+ )
27
+
28
+ BASE_MODEL = "stable-diffusion-v1-5/stable-diffusion-v1-5"
29
+
30
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
31
+
32
+ DEFAULT_EDIT_PROMPT = "a woman, blue hair, high detailed"
33
+ 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"
34
+
35
+ DEFAULT_CATEGORY = "hair"
36
+
37
+ canny_detector = CannyDetector()
38
+ lineart_detector = LineartDetector.from_pretrained("lllyasviel/Annotators")
39
+ lineart_detector = lineart_detector.to(DEVICE)
40
+
41
+ pidiNet_detector = PidiNetDetector.from_pretrained('lllyasviel/Annotators')
42
+ pidiNet_detector = pidiNet_detector.to(DEVICE)
43
+
44
+ adapters = MultiAdapter(
45
+ [
46
+ T2IAdapter.from_pretrained(
47
+ "TencentARC/t2iadapter_canny_sd15v2",
48
+ torch_dtype=torch.float16,
49
+ varient="fp16",
50
+ ),
51
+ T2IAdapter.from_pretrained(
52
+ "TencentARC/t2iadapter_sketch_sd15v2",
53
+ torch_dtype=torch.float16,
54
+ varient="fp16",
55
+ ),
56
+ ]
57
+ )
58
+ adapters = adapters.to(torch.float16)
59
+
60
+ basepipeline = DiffusionPipeline.from_pretrained(
61
+ BASE_MODEL,
62
+ torch_dtype=torch.float16,
63
+ use_safetensors=True,
64
+ adapter=adapters,
65
+ custom_pipeline="./pipelines/pipeline_sd_adapter_inpaint.py",
66
+ )
67
+
68
+ basepipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(basepipeline.scheduler.config)
69
+
70
+ basepipeline = basepipeline.to(DEVICE)
71
+
72
+ basepipeline.enable_model_cpu_offload()
73
+
74
+ @spaces.GPU(duration=30)
75
+ def image_to_image(
76
+ input_image: Image,
77
+ mask_image: Image,
78
+ edit_prompt: str,
79
+ seed: int,
80
+ num_steps: int,
81
+ guidance_scale: float,
82
+ generate_size: int,
83
+ cond_scale1: float = 1.2,
84
+ cond_scale2: float = 1.2,
85
+ ):
86
+ run_task_time = 0
87
+ time_cost_str = ''
88
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
89
+ canny_image = canny_detector(input_image, int(generate_size*1), generate_size)
90
+ # lineart_image = lineart_detector(input_image, int(generate_size*1), generate_size)
91
+ # run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
92
+ pidiNet_image = pidiNet_detector(input_image, int(generate_size*1), generate_size)
93
+ cond_image = [pidiNet_image, canny_image]
94
+ cond_scale = [cond_scale1, cond_scale2]
95
+
96
+ generator = torch.Generator(device=DEVICE).manual_seed(seed)
97
+ generated_image = basepipeline(
98
+ generator=generator,
99
+ prompt=edit_prompt,
100
+ negative_prompt=DEFAULT_NEGATIVE_PROMPT,
101
+ image=input_image,
102
+ mask_image=mask_image,
103
+ height=generate_size,
104
+ width=generate_size,
105
+ guidance_scale=guidance_scale,
106
+ num_inference_steps=num_steps,
107
+ adapter_image=cond_image,
108
+ adapter_conditioning_scale=cond_scale,
109
+ ).images[0]
110
+
111
+ run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
112
+
113
+ return generated_image, time_cost_str
114
+
115
+ def make_inpaint_condition(image, image_mask):
116
+ image = np.array(image.convert("RGB")).astype(np.float32) / 255.0
117
+ image_mask = np.array(image_mask.convert("L")).astype(np.float32) / 255.0
118
+
119
+ assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size"
120
+ image[image_mask > 0.5] = -1.0 # set as masked pixel
121
+ image = np.expand_dims(image, 0).transpose(0, 3, 1, 2)
122
+ image = torch.from_numpy(image)
123
+ return image
124
+
125
+ def get_time_cost(run_task_time, time_cost_str):
126
+ now_time = int(time.time()*1000)
127
+ if run_task_time == 0:
128
+ time_cost_str = 'start'
129
+ else:
130
+ if time_cost_str != '':
131
+ time_cost_str += f'-->'
132
+ time_cost_str += f'{now_time - run_task_time}'
133
+ run_task_time = now_time
134
+ return run_task_time, time_cost_str
135
+
136
+ def create_demo() -> gr.Blocks:
137
+ with gr.Blocks() as demo:
138
+ croper = gr.State()
139
+ with gr.Row():
140
+ with gr.Column():
141
+ edit_prompt = gr.Textbox(lines=1, label="Edit Prompt", value=DEFAULT_EDIT_PROMPT)
142
+ generate_size = gr.Number(label="Generate Size", value=512)
143
+ with gr.Column():
144
+ num_steps = gr.Slider(minimum=1, maximum=100, value=15, step=1, label="Num Steps")
145
+ guidance_scale = gr.Slider(minimum=0, maximum=30, value=5, step=0.5, label="Guidance Scale")
146
+ with gr.Column():
147
+ with gr.Accordion("Advanced Options", open=False):
148
+ cond_scale1 = gr.Slider(minimum=0, maximum=3, value=1.2, step=0.1, label="Lineart Scale")
149
+ cond_scale2 = gr.Slider(minimum=0, maximum=3, value=1.2, step=0.1, label="PidiNet Scale")
150
+ mask_expansion = gr.Number(label="Mask Expansion", value=50, visible=True)
151
+ mask_dilation = gr.Slider(minimum=0, maximum=10, value=2, step=1, label="Mask Dilation")
152
+ seed = gr.Number(label="Seed", value=8)
153
+ category = gr.Textbox(label="Category", value=DEFAULT_CATEGORY, visible=False)
154
+ g_btn = gr.Button("Edit Image")
155
+
156
+ with gr.Row():
157
+ with gr.Column():
158
+ input_image = gr.Image(label="Input Image", type="pil")
159
+ with gr.Column():
160
+ restored_image = gr.Image(label="Restored Image", type="pil", interactive=False)
161
+ with gr.Column():
162
+ origin_area_image = gr.Image(label="Origin Area Image", type="pil", interactive=False)
163
+ generated_image = gr.Image(label="Generated Image", type="pil", interactive=False)
164
+ generated_cost = gr.Textbox(label="Time cost by step (ms):", visible=True, interactive=False)
165
+ mask_image = gr.Image(label="Mask Image", type="pil", interactive=False)
166
+
167
+ g_btn.click(
168
+ fn=segment_image_withmask,
169
+ inputs=[input_image, category, generate_size, mask_expansion, mask_dilation],
170
+ outputs=[origin_area_image, mask_image, croper],
171
+ ).success(
172
+ fn=image_to_image,
173
+ inputs=[origin_area_image, mask_image, edit_prompt,seed, num_steps, guidance_scale, generate_size, cond_scale1, cond_scale2],
174
+ outputs=[generated_image, generated_cost],
175
+ ).success(
176
+ fn=restore_result,
177
+ inputs=[croper, category, generated_image],
178
+ outputs=[restored_image],
179
+ )
180
+
181
+ return demo
pipelines/pipeline_sd_adapter_inpaint.py ADDED
@@ -0,0 +1,1475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from packaging import version
22
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
23
+
24
+ from diffusers.callbacks import (
25
+ MultiPipelineCallbacks,
26
+ PipelineCallback,
27
+ )
28
+
29
+ from diffusers.configuration_utils import FrozenDict
30
+
31
+ from diffusers.image_processor import (
32
+ PipelineImageInput,
33
+ VaeImageProcessor,
34
+ )
35
+
36
+ from diffusers.loaders import (
37
+ FromSingleFileMixin,
38
+ IPAdapterMixin,
39
+ StableDiffusionLoraLoaderMixin,
40
+ TextualInversionLoaderMixin,
41
+ )
42
+
43
+ from diffusers.models import (
44
+ AsymmetricAutoencoderKL,
45
+ AutoencoderKL,
46
+ ImageProjection,
47
+ MultiAdapter,
48
+ T2IAdapter,
49
+ UNet2DConditionModel,
50
+ )
51
+
52
+ from diffusers.models.lora import (
53
+ adjust_lora_scale_text_encoder,
54
+ )
55
+
56
+ from diffusers.schedulers import (
57
+ KarrasDiffusionSchedulers,
58
+ )
59
+
60
+ from diffusers.utils import (
61
+ PIL_INTERPOLATION,
62
+ USE_PEFT_BACKEND,
63
+ deprecate,
64
+ logging,
65
+ scale_lora_layers,
66
+ unscale_lora_layers,
67
+ )
68
+ from diffusers.utils.torch_utils import (
69
+ randn_tensor,
70
+ )
71
+
72
+ from diffusers.pipelines.pipeline_utils import (
73
+ DiffusionPipeline,
74
+ StableDiffusionMixin,
75
+ )
76
+
77
+ from diffusers.pipelines.stable_diffusion.pipeline_output import (
78
+ StableDiffusionPipelineOutput,
79
+ )
80
+
81
+ from diffusers.pipelines.stable_diffusion.safety_checker import (
82
+ StableDiffusionSafetyChecker,
83
+ )
84
+
85
+
86
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
87
+
88
+ def _preprocess_adapter_image(image, height, width):
89
+ if isinstance(image, torch.Tensor):
90
+ return image
91
+ elif isinstance(image, PIL.Image.Image):
92
+ image = [image]
93
+
94
+ if isinstance(image[0], PIL.Image.Image):
95
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
96
+ image = [
97
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
98
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
99
+ image = np.concatenate(image, axis=0)
100
+ image = np.array(image).astype(np.float32) / 255.0
101
+ image = image.transpose(0, 3, 1, 2)
102
+ image = torch.from_numpy(image)
103
+ elif isinstance(image[0], torch.Tensor):
104
+ if image[0].ndim == 3:
105
+ image = torch.stack(image, dim=0)
106
+ elif image[0].ndim == 4:
107
+ image = torch.cat(image, dim=0)
108
+ else:
109
+ raise ValueError(
110
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
111
+ )
112
+ return image
113
+
114
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
115
+ def retrieve_latents(
116
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
117
+ ):
118
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
119
+ return encoder_output.latent_dist.sample(generator)
120
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
121
+ return encoder_output.latent_dist.mode()
122
+ elif hasattr(encoder_output, "latents"):
123
+ return encoder_output.latents
124
+ else:
125
+ raise AttributeError("Could not access latents of provided encoder_output")
126
+
127
+
128
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
129
+ def retrieve_timesteps(
130
+ scheduler,
131
+ num_inference_steps: Optional[int] = None,
132
+ device: Optional[Union[str, torch.device]] = None,
133
+ timesteps: Optional[List[int]] = None,
134
+ sigmas: Optional[List[float]] = None,
135
+ **kwargs,
136
+ ):
137
+ """
138
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
139
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
140
+
141
+ Args:
142
+ scheduler (`SchedulerMixin`):
143
+ The scheduler to get timesteps from.
144
+ num_inference_steps (`int`):
145
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
146
+ must be `None`.
147
+ device (`str` or `torch.device`, *optional*):
148
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
149
+ timesteps (`List[int]`, *optional*):
150
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
151
+ `num_inference_steps` and `sigmas` must be `None`.
152
+ sigmas (`List[float]`, *optional*):
153
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
154
+ `num_inference_steps` and `timesteps` must be `None`.
155
+
156
+ Returns:
157
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
158
+ second element is the number of inference steps.
159
+ """
160
+ if timesteps is not None and sigmas is not None:
161
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
162
+ if timesteps is not None:
163
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
164
+ if not accepts_timesteps:
165
+ raise ValueError(
166
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
167
+ f" timestep schedules. Please check whether you are using the correct scheduler."
168
+ )
169
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
170
+ timesteps = scheduler.timesteps
171
+ num_inference_steps = len(timesteps)
172
+ elif sigmas is not None:
173
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
174
+ if not accept_sigmas:
175
+ raise ValueError(
176
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
177
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
178
+ )
179
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
180
+ timesteps = scheduler.timesteps
181
+ num_inference_steps = len(timesteps)
182
+ else:
183
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
184
+ timesteps = scheduler.timesteps
185
+ return timesteps, num_inference_steps
186
+
187
+
188
+ class StableDiffusionInpaintPipeline(
189
+ DiffusionPipeline,
190
+ StableDiffusionMixin,
191
+ TextualInversionLoaderMixin,
192
+ IPAdapterMixin,
193
+ StableDiffusionLoraLoaderMixin,
194
+ FromSingleFileMixin,
195
+ ):
196
+ r"""
197
+ Pipeline for text-guided image inpainting using Stable Diffusion.
198
+
199
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
200
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
201
+
202
+ The pipeline also inherits the following loading methods:
203
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
204
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
205
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
206
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
207
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
208
+
209
+ Args:
210
+ vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]):
211
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
212
+ text_encoder ([`CLIPTextModel`]):
213
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
214
+ tokenizer ([`~transformers.CLIPTokenizer`]):
215
+ A `CLIPTokenizer` to tokenize text.
216
+ unet ([`UNet2DConditionModel`]):
217
+ A `UNet2DConditionModel` to denoise the encoded image latents.
218
+ scheduler ([`SchedulerMixin`]):
219
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
220
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
221
+ safety_checker ([`StableDiffusionSafetyChecker`]):
222
+ Classification module that estimates whether generated images could be considered offensive or harmful.
223
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
224
+ about a model's potential harms.
225
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
226
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
227
+ """
228
+
229
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
230
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
231
+ _exclude_from_cpu_offload = ["safety_checker"]
232
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "mask", "masked_image_latents"]
233
+
234
+ def __init__(
235
+ self,
236
+ vae: Union[AutoencoderKL, AsymmetricAutoencoderKL],
237
+ text_encoder: CLIPTextModel,
238
+ tokenizer: CLIPTokenizer,
239
+ unet: UNet2DConditionModel,
240
+ adapter: Union[T2IAdapter, MultiAdapter, List[T2IAdapter]],
241
+ scheduler: KarrasDiffusionSchedulers,
242
+ safety_checker: StableDiffusionSafetyChecker,
243
+ feature_extractor: CLIPImageProcessor,
244
+ image_encoder: CLIPVisionModelWithProjection = None,
245
+ requires_safety_checker: bool = True,
246
+ ):
247
+ super().__init__()
248
+
249
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
250
+ deprecation_message = (
251
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
252
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
253
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
254
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
255
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
256
+ " file"
257
+ )
258
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
259
+ new_config = dict(scheduler.config)
260
+ new_config["steps_offset"] = 1
261
+ scheduler._internal_dict = FrozenDict(new_config)
262
+
263
+ if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False:
264
+ deprecation_message = (
265
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration"
266
+ " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"
267
+ " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"
268
+ " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"
269
+ " Hub, it would be very nice if you could open a Pull request for the"
270
+ " `scheduler/scheduler_config.json` file"
271
+ )
272
+ deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False)
273
+ new_config = dict(scheduler.config)
274
+ new_config["skip_prk_steps"] = True
275
+ scheduler._internal_dict = FrozenDict(new_config)
276
+
277
+ if safety_checker is None and requires_safety_checker:
278
+ logger.warning(
279
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
280
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
281
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
282
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
283
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
284
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
285
+ )
286
+
287
+ if safety_checker is not None and feature_extractor is None:
288
+ raise ValueError(
289
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
290
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
291
+ )
292
+
293
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
294
+ version.parse(unet.config._diffusers_version).base_version
295
+ ) < version.parse("0.9.0.dev0")
296
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
297
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
298
+ deprecation_message = (
299
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
300
+ " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the"
301
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
302
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
303
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
304
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
305
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
306
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
307
+ " the `unet/config.json` file"
308
+ )
309
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
310
+ new_config = dict(unet.config)
311
+ new_config["sample_size"] = 64
312
+ unet._internal_dict = FrozenDict(new_config)
313
+
314
+ # Check shapes, assume num_channels_latents == 4, num_channels_mask == 1, num_channels_masked == 4
315
+ if unet.config.in_channels != 9:
316
+ logger.info(f"You have loaded a UNet with {unet.config.in_channels} input channels which.")
317
+
318
+ if isinstance(adapter, (list, tuple)):
319
+ adapter = MultiAdapter(adapter)
320
+
321
+ self.register_modules(
322
+ vae=vae,
323
+ text_encoder=text_encoder,
324
+ tokenizer=tokenizer,
325
+ unet=unet,
326
+ adapter=adapter,
327
+ scheduler=scheduler,
328
+ safety_checker=safety_checker,
329
+ feature_extractor=feature_extractor,
330
+ image_encoder=image_encoder,
331
+ )
332
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
333
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
334
+ self.mask_processor = VaeImageProcessor(
335
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True
336
+ )
337
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
338
+
339
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
340
+ def _encode_prompt(
341
+ self,
342
+ prompt,
343
+ device,
344
+ num_images_per_prompt,
345
+ do_classifier_free_guidance,
346
+ negative_prompt=None,
347
+ prompt_embeds: Optional[torch.Tensor] = None,
348
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
349
+ lora_scale: Optional[float] = None,
350
+ **kwargs,
351
+ ):
352
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
353
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
354
+
355
+ prompt_embeds_tuple = self.encode_prompt(
356
+ prompt=prompt,
357
+ device=device,
358
+ num_images_per_prompt=num_images_per_prompt,
359
+ do_classifier_free_guidance=do_classifier_free_guidance,
360
+ negative_prompt=negative_prompt,
361
+ prompt_embeds=prompt_embeds,
362
+ negative_prompt_embeds=negative_prompt_embeds,
363
+ lora_scale=lora_scale,
364
+ **kwargs,
365
+ )
366
+
367
+ # concatenate for backwards comp
368
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
369
+
370
+ return prompt_embeds
371
+
372
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
373
+ def encode_prompt(
374
+ self,
375
+ prompt,
376
+ device,
377
+ num_images_per_prompt,
378
+ do_classifier_free_guidance,
379
+ negative_prompt=None,
380
+ prompt_embeds: Optional[torch.Tensor] = None,
381
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
382
+ lora_scale: Optional[float] = None,
383
+ clip_skip: Optional[int] = None,
384
+ ):
385
+ r"""
386
+ Encodes the prompt into text encoder hidden states.
387
+
388
+ Args:
389
+ prompt (`str` or `List[str]`, *optional*):
390
+ prompt to be encoded
391
+ device: (`torch.device`):
392
+ torch device
393
+ num_images_per_prompt (`int`):
394
+ number of images that should be generated per prompt
395
+ do_classifier_free_guidance (`bool`):
396
+ whether to use classifier free guidance or not
397
+ negative_prompt (`str` or `List[str]`, *optional*):
398
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
399
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
400
+ less than `1`).
401
+ prompt_embeds (`torch.Tensor`, *optional*):
402
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
403
+ provided, text embeddings will be generated from `prompt` input argument.
404
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
405
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
406
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
407
+ argument.
408
+ lora_scale (`float`, *optional*):
409
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
410
+ clip_skip (`int`, *optional*):
411
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
412
+ the output of the pre-final layer will be used for computing the prompt embeddings.
413
+ """
414
+ # set lora scale so that monkey patched LoRA
415
+ # function of text encoder can correctly access it
416
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
417
+ self._lora_scale = lora_scale
418
+
419
+ # dynamically adjust the LoRA scale
420
+ if not USE_PEFT_BACKEND:
421
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
422
+ else:
423
+ scale_lora_layers(self.text_encoder, lora_scale)
424
+
425
+ if prompt is not None and isinstance(prompt, str):
426
+ batch_size = 1
427
+ elif prompt is not None and isinstance(prompt, list):
428
+ batch_size = len(prompt)
429
+ else:
430
+ batch_size = prompt_embeds.shape[0]
431
+
432
+ if prompt_embeds is None:
433
+ # textual inversion: process multi-vector tokens if necessary
434
+ if isinstance(self, TextualInversionLoaderMixin):
435
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
436
+
437
+ text_inputs = self.tokenizer(
438
+ prompt,
439
+ padding="max_length",
440
+ max_length=self.tokenizer.model_max_length,
441
+ truncation=True,
442
+ return_tensors="pt",
443
+ )
444
+ text_input_ids = text_inputs.input_ids
445
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
446
+
447
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
448
+ text_input_ids, untruncated_ids
449
+ ):
450
+ removed_text = self.tokenizer.batch_decode(
451
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
452
+ )
453
+ logger.warning(
454
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
455
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
456
+ )
457
+
458
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
459
+ attention_mask = text_inputs.attention_mask.to(device)
460
+ else:
461
+ attention_mask = None
462
+
463
+ if clip_skip is None:
464
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
465
+ prompt_embeds = prompt_embeds[0]
466
+ else:
467
+ prompt_embeds = self.text_encoder(
468
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
469
+ )
470
+ # Access the `hidden_states` first, that contains a tuple of
471
+ # all the hidden states from the encoder layers. Then index into
472
+ # the tuple to access the hidden states from the desired layer.
473
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
474
+ # We also need to apply the final LayerNorm here to not mess with the
475
+ # representations. The `last_hidden_states` that we typically use for
476
+ # obtaining the final prompt representations passes through the LayerNorm
477
+ # layer.
478
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
479
+
480
+ if self.text_encoder is not None:
481
+ prompt_embeds_dtype = self.text_encoder.dtype
482
+ elif self.unet is not None:
483
+ prompt_embeds_dtype = self.unet.dtype
484
+ else:
485
+ prompt_embeds_dtype = prompt_embeds.dtype
486
+
487
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
488
+
489
+ bs_embed, seq_len, _ = prompt_embeds.shape
490
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
491
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
492
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
493
+
494
+ # get unconditional embeddings for classifier free guidance
495
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
496
+ uncond_tokens: List[str]
497
+ if negative_prompt is None:
498
+ uncond_tokens = [""] * batch_size
499
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
500
+ raise TypeError(
501
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
502
+ f" {type(prompt)}."
503
+ )
504
+ elif isinstance(negative_prompt, str):
505
+ uncond_tokens = [negative_prompt]
506
+ elif batch_size != len(negative_prompt):
507
+ raise ValueError(
508
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
509
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
510
+ " the batch size of `prompt`."
511
+ )
512
+ else:
513
+ uncond_tokens = negative_prompt
514
+
515
+ # textual inversion: process multi-vector tokens if necessary
516
+ if isinstance(self, TextualInversionLoaderMixin):
517
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
518
+
519
+ max_length = prompt_embeds.shape[1]
520
+ uncond_input = self.tokenizer(
521
+ uncond_tokens,
522
+ padding="max_length",
523
+ max_length=max_length,
524
+ truncation=True,
525
+ return_tensors="pt",
526
+ )
527
+
528
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
529
+ attention_mask = uncond_input.attention_mask.to(device)
530
+ else:
531
+ attention_mask = None
532
+
533
+ negative_prompt_embeds = self.text_encoder(
534
+ uncond_input.input_ids.to(device),
535
+ attention_mask=attention_mask,
536
+ )
537
+ negative_prompt_embeds = negative_prompt_embeds[0]
538
+
539
+ if do_classifier_free_guidance:
540
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
541
+ seq_len = negative_prompt_embeds.shape[1]
542
+
543
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
544
+
545
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
546
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
547
+
548
+ if self.text_encoder is not None:
549
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
550
+ # Retrieve the original scale by scaling back the LoRA layers
551
+ unscale_lora_layers(self.text_encoder, lora_scale)
552
+
553
+ return prompt_embeds, negative_prompt_embeds
554
+
555
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
556
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
557
+ dtype = next(self.image_encoder.parameters()).dtype
558
+
559
+ if not isinstance(image, torch.Tensor):
560
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
561
+
562
+ image = image.to(device=device, dtype=dtype)
563
+ if output_hidden_states:
564
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
565
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
566
+ uncond_image_enc_hidden_states = self.image_encoder(
567
+ torch.zeros_like(image), output_hidden_states=True
568
+ ).hidden_states[-2]
569
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
570
+ num_images_per_prompt, dim=0
571
+ )
572
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
573
+ else:
574
+ image_embeds = self.image_encoder(image).image_embeds
575
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
576
+ uncond_image_embeds = torch.zeros_like(image_embeds)
577
+
578
+ return image_embeds, uncond_image_embeds
579
+
580
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
581
+ def prepare_ip_adapter_image_embeds(
582
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
583
+ ):
584
+ image_embeds = []
585
+ if do_classifier_free_guidance:
586
+ negative_image_embeds = []
587
+ if ip_adapter_image_embeds is None:
588
+ if not isinstance(ip_adapter_image, list):
589
+ ip_adapter_image = [ip_adapter_image]
590
+
591
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
592
+ raise ValueError(
593
+ 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."
594
+ )
595
+
596
+ for single_ip_adapter_image, image_proj_layer in zip(
597
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
598
+ ):
599
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
600
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
601
+ single_ip_adapter_image, device, 1, output_hidden_state
602
+ )
603
+
604
+ image_embeds.append(single_image_embeds[None, :])
605
+ if do_classifier_free_guidance:
606
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
607
+ else:
608
+ for single_image_embeds in ip_adapter_image_embeds:
609
+ if do_classifier_free_guidance:
610
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
611
+ negative_image_embeds.append(single_negative_image_embeds)
612
+ image_embeds.append(single_image_embeds)
613
+
614
+ ip_adapter_image_embeds = []
615
+ for i, single_image_embeds in enumerate(image_embeds):
616
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
617
+ if do_classifier_free_guidance:
618
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
619
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
620
+
621
+ single_image_embeds = single_image_embeds.to(device=device)
622
+ ip_adapter_image_embeds.append(single_image_embeds)
623
+
624
+ return ip_adapter_image_embeds
625
+
626
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
627
+ def run_safety_checker(self, image, device, dtype):
628
+ if self.safety_checker is None:
629
+ has_nsfw_concept = None
630
+ else:
631
+ if torch.is_tensor(image):
632
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
633
+ else:
634
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
635
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
636
+ image, has_nsfw_concept = self.safety_checker(
637
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
638
+ )
639
+ return image, has_nsfw_concept
640
+
641
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
642
+ def prepare_extra_step_kwargs(self, generator, eta):
643
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
644
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
645
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
646
+ # and should be between [0, 1]
647
+
648
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
649
+ extra_step_kwargs = {}
650
+ if accepts_eta:
651
+ extra_step_kwargs["eta"] = eta
652
+
653
+ # check if the scheduler accepts generator
654
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
655
+ if accepts_generator:
656
+ extra_step_kwargs["generator"] = generator
657
+ return extra_step_kwargs
658
+
659
+ def check_inputs(
660
+ self,
661
+ prompt,
662
+ image,
663
+ mask_image,
664
+ height,
665
+ width,
666
+ strength,
667
+ callback_steps,
668
+ output_type,
669
+ negative_prompt=None,
670
+ prompt_embeds=None,
671
+ negative_prompt_embeds=None,
672
+ ip_adapter_image=None,
673
+ ip_adapter_image_embeds=None,
674
+ callback_on_step_end_tensor_inputs=None,
675
+ padding_mask_crop=None,
676
+ ):
677
+ if strength < 0 or strength > 1:
678
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
679
+
680
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
681
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
682
+
683
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
684
+ raise ValueError(
685
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
686
+ f" {type(callback_steps)}."
687
+ )
688
+
689
+ if callback_on_step_end_tensor_inputs is not None and not all(
690
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
691
+ ):
692
+ raise ValueError(
693
+ 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]}"
694
+ )
695
+
696
+ if prompt is not None and prompt_embeds is not None:
697
+ raise ValueError(
698
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
699
+ " only forward one of the two."
700
+ )
701
+ elif prompt is None and prompt_embeds is None:
702
+ raise ValueError(
703
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
704
+ )
705
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
706
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
707
+
708
+ if negative_prompt is not None and negative_prompt_embeds is not None:
709
+ raise ValueError(
710
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
711
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
712
+ )
713
+
714
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
715
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
716
+ raise ValueError(
717
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
718
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
719
+ f" {negative_prompt_embeds.shape}."
720
+ )
721
+ if padding_mask_crop is not None:
722
+ if not isinstance(image, PIL.Image.Image):
723
+ raise ValueError(
724
+ f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}."
725
+ )
726
+ if not isinstance(mask_image, PIL.Image.Image):
727
+ raise ValueError(
728
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
729
+ f" {type(mask_image)}."
730
+ )
731
+ if output_type != "pil":
732
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is" f" {output_type}.")
733
+
734
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
735
+ raise ValueError(
736
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
737
+ )
738
+
739
+ if ip_adapter_image_embeds is not None:
740
+ if not isinstance(ip_adapter_image_embeds, list):
741
+ raise ValueError(
742
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
743
+ )
744
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
745
+ raise ValueError(
746
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
747
+ )
748
+
749
+ def prepare_latents(
750
+ self,
751
+ batch_size,
752
+ num_channels_latents,
753
+ height,
754
+ width,
755
+ dtype,
756
+ device,
757
+ generator,
758
+ latents=None,
759
+ image=None,
760
+ timestep=None,
761
+ is_strength_max=True,
762
+ return_noise=False,
763
+ return_image_latents=False,
764
+ ):
765
+ shape = (
766
+ batch_size,
767
+ num_channels_latents,
768
+ int(height) // self.vae_scale_factor,
769
+ int(width) // self.vae_scale_factor,
770
+ )
771
+ if isinstance(generator, list) and len(generator) != batch_size:
772
+ raise ValueError(
773
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
774
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
775
+ )
776
+
777
+ if (image is None or timestep is None) and not is_strength_max:
778
+ raise ValueError(
779
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
780
+ "However, either the image or the noise timestep has not been provided."
781
+ )
782
+
783
+ if return_image_latents or (latents is None and not is_strength_max):
784
+ image = image.to(device=device, dtype=dtype)
785
+
786
+ if image.shape[1] == 4:
787
+ image_latents = image
788
+ else:
789
+ image_latents = self._encode_vae_image(image=image, generator=generator)
790
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
791
+
792
+ if latents is None:
793
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
794
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
795
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
796
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
797
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
798
+ else:
799
+ noise = latents.to(device)
800
+ latents = noise * self.scheduler.init_noise_sigma
801
+
802
+ outputs = (latents,)
803
+
804
+ if return_noise:
805
+ outputs += (noise,)
806
+
807
+ if return_image_latents:
808
+ outputs += (image_latents,)
809
+
810
+ return outputs
811
+
812
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
813
+ if isinstance(generator, list):
814
+ image_latents = [
815
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
816
+ for i in range(image.shape[0])
817
+ ]
818
+ image_latents = torch.cat(image_latents, dim=0)
819
+ else:
820
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
821
+
822
+ image_latents = self.vae.config.scaling_factor * image_latents
823
+
824
+ return image_latents
825
+
826
+ def prepare_mask_latents(
827
+ self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
828
+ ):
829
+ # resize the mask to latents shape as we concatenate the mask to the latents
830
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
831
+ # and half precision
832
+ mask = torch.nn.functional.interpolate(
833
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
834
+ )
835
+ mask = mask.to(device=device, dtype=dtype)
836
+
837
+ masked_image = masked_image.to(device=device, dtype=dtype)
838
+
839
+ if masked_image.shape[1] == 4:
840
+ masked_image_latents = masked_image
841
+ else:
842
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
843
+
844
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
845
+ if mask.shape[0] < batch_size:
846
+ if not batch_size % mask.shape[0] == 0:
847
+ raise ValueError(
848
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
849
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
850
+ " of masks that you pass is divisible by the total requested batch size."
851
+ )
852
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
853
+ if masked_image_latents.shape[0] < batch_size:
854
+ if not batch_size % masked_image_latents.shape[0] == 0:
855
+ raise ValueError(
856
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
857
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
858
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
859
+ )
860
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
861
+
862
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
863
+ masked_image_latents = (
864
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
865
+ )
866
+
867
+ # aligning device to prevent device errors when concating it with the latent model input
868
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
869
+ return mask, masked_image_latents
870
+
871
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
872
+ def get_timesteps(self, num_inference_steps, strength, device):
873
+ # get the original timestep using init_timestep
874
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
875
+
876
+ t_start = max(num_inference_steps - init_timestep, 0)
877
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
878
+ if hasattr(self.scheduler, "set_begin_index"):
879
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
880
+
881
+ return timesteps, num_inference_steps - t_start
882
+
883
+ def _default_height_width(self, height, width, image):
884
+ # NOTE: It is possible that a list of images have different
885
+ # dimensions for each image, so just checking the first image
886
+ # is not _exactly_ correct, but it is simple.
887
+ while isinstance(image, list):
888
+ image = image[0]
889
+
890
+ if height is None:
891
+ if isinstance(image, PIL.Image.Image):
892
+ height = image.height
893
+ elif isinstance(image, torch.Tensor):
894
+ height = image.shape[-2]
895
+
896
+ # round down to nearest multiple of `self.adapter.downscale_factor`
897
+ height = (height // self.adapter.downscale_factor) * self.adapter.downscale_factor
898
+
899
+ if width is None:
900
+ if isinstance(image, PIL.Image.Image):
901
+ width = image.width
902
+ elif isinstance(image, torch.Tensor):
903
+ width = image.shape[-1]
904
+
905
+ # round down to nearest multiple of `self.adapter.downscale_factor`
906
+ width = (width // self.adapter.downscale_factor) * self.adapter.downscale_factor
907
+
908
+ return height, width
909
+
910
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
911
+ def get_guidance_scale_embedding(
912
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
913
+ ) -> torch.Tensor:
914
+ """
915
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
916
+
917
+ Args:
918
+ w (`torch.Tensor`):
919
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
920
+ embedding_dim (`int`, *optional*, defaults to 512):
921
+ Dimension of the embeddings to generate.
922
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
923
+ Data type of the generated embeddings.
924
+
925
+ Returns:
926
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
927
+ """
928
+ assert len(w.shape) == 1
929
+ w = w * 1000.0
930
+
931
+ half_dim = embedding_dim // 2
932
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
933
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
934
+ emb = w.to(dtype)[:, None] * emb[None, :]
935
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
936
+ if embedding_dim % 2 == 1: # zero pad
937
+ emb = torch.nn.functional.pad(emb, (0, 1))
938
+ assert emb.shape == (w.shape[0], embedding_dim)
939
+ return emb
940
+
941
+ @property
942
+ def guidance_scale(self):
943
+ return self._guidance_scale
944
+
945
+ @property
946
+ def clip_skip(self):
947
+ return self._clip_skip
948
+
949
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
950
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
951
+ # corresponds to doing no classifier free guidance.
952
+ @property
953
+ def do_classifier_free_guidance(self):
954
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
955
+
956
+ @property
957
+ def cross_attention_kwargs(self):
958
+ return self._cross_attention_kwargs
959
+
960
+ @property
961
+ def num_timesteps(self):
962
+ return self._num_timesteps
963
+
964
+ @property
965
+ def interrupt(self):
966
+ return self._interrupt
967
+
968
+ @torch.no_grad()
969
+ def __call__(
970
+ self,
971
+ prompt: Union[str, List[str]] = None,
972
+ image: PipelineImageInput = None,
973
+ mask_image: PipelineImageInput = None,
974
+ masked_image_latents: torch.Tensor = None,
975
+ height: Optional[int] = None,
976
+ width: Optional[int] = None,
977
+ adapter_image: PipelineImageInput = None,
978
+ padding_mask_crop: Optional[int] = None,
979
+ strength: float = 1.0,
980
+ num_inference_steps: int = 50,
981
+ timesteps: List[int] = None,
982
+ sigmas: List[float] = None,
983
+ guidance_scale: float = 7.5,
984
+ negative_prompt: Optional[Union[str, List[str]]] = None,
985
+ num_images_per_prompt: Optional[int] = 1,
986
+ eta: float = 0.0,
987
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
988
+ latents: Optional[torch.Tensor] = None,
989
+ prompt_embeds: Optional[torch.Tensor] = None,
990
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
991
+ ip_adapter_image: Optional[PipelineImageInput] = None,
992
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
993
+ output_type: Optional[str] = "pil",
994
+ return_dict: bool = True,
995
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
996
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
997
+ clip_skip: int = None,
998
+ callback_on_step_end: Optional[
999
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1000
+ ] = None,
1001
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1002
+ **kwargs,
1003
+ ):
1004
+ r"""
1005
+ The call function to the pipeline for generation.
1006
+
1007
+ Args:
1008
+ prompt (`str` or `List[str]`, *optional*):
1009
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1010
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
1011
+ `Image`, numpy array or tensor representing an image batch to be inpainted (which parts of the image to
1012
+ be masked out with `mask_image` and repainted according to `prompt`). For both numpy array and pytorch
1013
+ tensor, the expected value range is between `[0, 1]` If it's a tensor or a list or tensors, the
1014
+ expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a list of arrays, the
1015
+ expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image latents as `image`, but
1016
+ if passing latents directly it is not encoded again.
1017
+ mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
1018
+ `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
1019
+ are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
1020
+ single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
1021
+ color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
1022
+ H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
1023
+ 1)`, or `(H, W)`.
1024
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1025
+ The height in pixels of the generated image.
1026
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1027
+ The width in pixels of the generated image.
1028
+ padding_mask_crop (`int`, *optional*, defaults to `None`):
1029
+ The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
1030
+ image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
1031
+ with the same aspect ration of the image and contains all masked area, and then expand that area based
1032
+ on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
1033
+ resizing to the original image size for inpainting. This is useful when the masked area is small while
1034
+ the image is large and contain information irrelevant for inpainting, such as background.
1035
+ strength (`float`, *optional*, defaults to 1.0):
1036
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
1037
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
1038
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
1039
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
1040
+ essentially ignores `image`.
1041
+ num_inference_steps (`int`, *optional*, defaults to 50):
1042
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1043
+ expense of slower inference. This parameter is modulated by `strength`.
1044
+ timesteps (`List[int]`, *optional*):
1045
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1046
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1047
+ passed will be used. Must be in descending order.
1048
+ sigmas (`List[float]`, *optional*):
1049
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1050
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1051
+ will be used.
1052
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1053
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1054
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1055
+ negative_prompt (`str` or `List[str]`, *optional*):
1056
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1057
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1058
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1059
+ The number of images to generate per prompt.
1060
+ eta (`float`, *optional*, defaults to 0.0):
1061
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1062
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1063
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1064
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1065
+ generation deterministic.
1066
+ latents (`torch.Tensor`, *optional*):
1067
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1068
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1069
+ tensor is generated by sampling using the supplied random `generator`.
1070
+ prompt_embeds (`torch.Tensor`, *optional*):
1071
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1072
+ provided, text embeddings are generated from the `prompt` input argument.
1073
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1074
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1075
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1076
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1077
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1078
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1079
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1080
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1081
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1082
+ output_type (`str`, *optional*, defaults to `"pil"`):
1083
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1084
+ return_dict (`bool`, *optional*, defaults to `True`):
1085
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1086
+ plain tuple.
1087
+ cross_attention_kwargs (`dict`, *optional*):
1088
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1089
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1090
+ clip_skip (`int`, *optional*):
1091
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1092
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1093
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1094
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1095
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1096
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1097
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1098
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1099
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1100
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1101
+ `._callback_tensor_inputs` attribute of your pipeline class.
1102
+ Examples:
1103
+
1104
+ ```py
1105
+ >>> import PIL
1106
+ >>> import requests
1107
+ >>> import torch
1108
+ >>> from io import BytesIO
1109
+
1110
+ >>> from diffusers import StableDiffusionInpaintPipeline
1111
+
1112
+
1113
+ >>> def download_image(url):
1114
+ ... response = requests.get(url)
1115
+ ... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
1116
+
1117
+
1118
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
1119
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
1120
+
1121
+ >>> init_image = download_image(img_url).resize((512, 512))
1122
+ >>> mask_image = download_image(mask_url).resize((512, 512))
1123
+
1124
+ >>> pipe = StableDiffusionInpaintPipeline.from_pretrained(
1125
+ ... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16
1126
+ ... )
1127
+ >>> pipe = pipe.to("cuda")
1128
+
1129
+ >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
1130
+ >>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
1131
+ ```
1132
+
1133
+ Returns:
1134
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1135
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1136
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
1137
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
1138
+ "not-safe-for-work" (nsfw) content.
1139
+ """
1140
+ height, width = self._default_height_width(height, width, adapter_image)
1141
+ device = self._execution_device
1142
+
1143
+ if isinstance(self.adapter, MultiAdapter):
1144
+ adapter_input = []
1145
+
1146
+ for one_image in adapter_image:
1147
+ one_image = _preprocess_adapter_image(one_image, height, width)
1148
+ one_image = one_image.to(device=device, dtype=self.adapter.dtype)
1149
+ adapter_input.append(one_image)
1150
+ else:
1151
+ adapter_input = _preprocess_adapter_image(adapter_image, height, width)
1152
+ adapter_input = adapter_input.to(device=device, dtype=self.adapter.dtype)
1153
+
1154
+ callback = kwargs.pop("callback", None)
1155
+ callback_steps = kwargs.pop("callback_steps", None)
1156
+
1157
+ if callback is not None:
1158
+ deprecate(
1159
+ "callback",
1160
+ "1.0.0",
1161
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1162
+ )
1163
+ if callback_steps is not None:
1164
+ deprecate(
1165
+ "callback_steps",
1166
+ "1.0.0",
1167
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1168
+ )
1169
+
1170
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1171
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1172
+
1173
+ # 0. Default height and width to unet
1174
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1175
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1176
+
1177
+ # 1. Check inputs
1178
+ self.check_inputs(
1179
+ prompt,
1180
+ image,
1181
+ mask_image,
1182
+ height,
1183
+ width,
1184
+ strength,
1185
+ callback_steps,
1186
+ output_type,
1187
+ negative_prompt,
1188
+ prompt_embeds,
1189
+ negative_prompt_embeds,
1190
+ ip_adapter_image,
1191
+ ip_adapter_image_embeds,
1192
+ callback_on_step_end_tensor_inputs,
1193
+ padding_mask_crop,
1194
+ )
1195
+
1196
+ self._guidance_scale = guidance_scale
1197
+ self._clip_skip = clip_skip
1198
+ self._cross_attention_kwargs = cross_attention_kwargs
1199
+ self._interrupt = False
1200
+
1201
+ # 2. Define call parameters
1202
+ if prompt is not None and isinstance(prompt, str):
1203
+ batch_size = 1
1204
+ elif prompt is not None and isinstance(prompt, list):
1205
+ batch_size = len(prompt)
1206
+ else:
1207
+ batch_size = prompt_embeds.shape[0]
1208
+
1209
+ device = self._execution_device
1210
+
1211
+ # 3. Encode input prompt
1212
+ text_encoder_lora_scale = (
1213
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1214
+ )
1215
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1216
+ prompt,
1217
+ device,
1218
+ num_images_per_prompt,
1219
+ self.do_classifier_free_guidance,
1220
+ negative_prompt,
1221
+ prompt_embeds=prompt_embeds,
1222
+ negative_prompt_embeds=negative_prompt_embeds,
1223
+ lora_scale=text_encoder_lora_scale,
1224
+ clip_skip=self.clip_skip,
1225
+ )
1226
+ # For classifier free guidance, we need to do two forward passes.
1227
+ # Here we concatenate the unconditional and text embeddings into a single batch
1228
+ # to avoid doing two forward passes
1229
+ if self.do_classifier_free_guidance:
1230
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1231
+
1232
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1233
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1234
+ ip_adapter_image,
1235
+ ip_adapter_image_embeds,
1236
+ device,
1237
+ batch_size * num_images_per_prompt,
1238
+ self.do_classifier_free_guidance,
1239
+ )
1240
+
1241
+ # 4. set timesteps
1242
+ timesteps, num_inference_steps = retrieve_timesteps(
1243
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1244
+ )
1245
+ timesteps, num_inference_steps = self.get_timesteps(
1246
+ num_inference_steps=num_inference_steps, strength=strength, device=device
1247
+ )
1248
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1249
+ if num_inference_steps < 1:
1250
+ raise ValueError(
1251
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1252
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1253
+ )
1254
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1255
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1256
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1257
+ is_strength_max = strength == 1.0
1258
+
1259
+ # 5. Preprocess mask and image
1260
+
1261
+ if padding_mask_crop is not None:
1262
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
1263
+ resize_mode = "fill"
1264
+ else:
1265
+ crops_coords = None
1266
+ resize_mode = "default"
1267
+
1268
+ original_image = image
1269
+ init_image = self.image_processor.preprocess(
1270
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
1271
+ )
1272
+ init_image = init_image.to(dtype=torch.float32)
1273
+
1274
+ # 6. Prepare latent variables
1275
+ num_channels_latents = self.vae.config.latent_channels
1276
+ num_channels_unet = self.unet.config.in_channels
1277
+ return_image_latents = num_channels_unet == 4
1278
+
1279
+ latents_outputs = self.prepare_latents(
1280
+ batch_size * num_images_per_prompt,
1281
+ num_channels_latents,
1282
+ height,
1283
+ width,
1284
+ prompt_embeds.dtype,
1285
+ device,
1286
+ generator,
1287
+ latents,
1288
+ image=init_image,
1289
+ timestep=latent_timestep,
1290
+ is_strength_max=is_strength_max,
1291
+ return_noise=True,
1292
+ return_image_latents=return_image_latents,
1293
+ )
1294
+
1295
+ if return_image_latents:
1296
+ latents, noise, image_latents = latents_outputs
1297
+ else:
1298
+ latents, noise = latents_outputs
1299
+
1300
+ # 7. Prepare mask latent variables
1301
+ mask_condition = self.mask_processor.preprocess(
1302
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
1303
+ )
1304
+
1305
+ if masked_image_latents is None:
1306
+ masked_image = init_image * (mask_condition < 0.5)
1307
+ else:
1308
+ masked_image = masked_image_latents
1309
+
1310
+ mask, masked_image_latents = self.prepare_mask_latents(
1311
+ mask_condition,
1312
+ masked_image,
1313
+ batch_size * num_images_per_prompt,
1314
+ height,
1315
+ width,
1316
+ prompt_embeds.dtype,
1317
+ device,
1318
+ generator,
1319
+ self.do_classifier_free_guidance,
1320
+ )
1321
+
1322
+ # 8. Check that sizes of mask, masked image and latents match
1323
+ if num_channels_unet == 9:
1324
+ # default case for runwayml/stable-diffusion-inpainting
1325
+ num_channels_mask = mask.shape[1]
1326
+ num_channels_masked_image = masked_image_latents.shape[1]
1327
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
1328
+ raise ValueError(
1329
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
1330
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
1331
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
1332
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
1333
+ " `pipeline.unet` or your `mask_image` or `image` input."
1334
+ )
1335
+ elif num_channels_unet != 4:
1336
+ raise ValueError(
1337
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1338
+ )
1339
+
1340
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1341
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1342
+
1343
+ # 9.1 Add image embeds for IP-Adapter
1344
+ added_cond_kwargs = (
1345
+ {"image_embeds": image_embeds}
1346
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
1347
+ else None
1348
+ )
1349
+
1350
+ # 9.2 Optionally get Guidance Scale Embedding
1351
+ timestep_cond = None
1352
+ if self.unet.config.time_cond_proj_dim is not None:
1353
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1354
+ timestep_cond = self.get_guidance_scale_embedding(
1355
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1356
+ ).to(device=device, dtype=latents.dtype)
1357
+
1358
+ # 10. Denoising loop
1359
+ if isinstance(self.adapter, MultiAdapter):
1360
+ adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
1361
+ for k, v in enumerate(adapter_state):
1362
+ adapter_state[k] = v
1363
+ else:
1364
+ adapter_state = self.adapter(adapter_input)
1365
+ for k, v in enumerate(adapter_state):
1366
+ adapter_state[k] = v * adapter_conditioning_scale
1367
+ if num_images_per_prompt > 1:
1368
+ for k, v in enumerate(adapter_state):
1369
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
1370
+ if self.do_classifier_free_guidance:
1371
+ for k, v in enumerate(adapter_state):
1372
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
1373
+
1374
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1375
+ self._num_timesteps = len(timesteps)
1376
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1377
+ for i, t in enumerate(timesteps):
1378
+ if self.interrupt:
1379
+ continue
1380
+
1381
+ # expand the latents if we are doing classifier free guidance
1382
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1383
+
1384
+ # concat latents, mask, masked_image_latents in the channel dimension
1385
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1386
+
1387
+ if num_channels_unet == 9:
1388
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
1389
+
1390
+ # predict the noise residual
1391
+ noise_pred = self.unet(
1392
+ latent_model_input,
1393
+ t,
1394
+ encoder_hidden_states=prompt_embeds,
1395
+ timestep_cond=timestep_cond,
1396
+ cross_attention_kwargs=self.cross_attention_kwargs,
1397
+ added_cond_kwargs=added_cond_kwargs,
1398
+ down_intrablock_additional_residuals=[state.clone() for state in adapter_state],
1399
+ return_dict=False,
1400
+ )[0]
1401
+
1402
+ # perform guidance
1403
+ if self.do_classifier_free_guidance:
1404
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1405
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1406
+
1407
+ # compute the previous noisy sample x_t -> x_t-1
1408
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1409
+ if num_channels_unet == 4:
1410
+ init_latents_proper = image_latents
1411
+ if self.do_classifier_free_guidance:
1412
+ init_mask, _ = mask.chunk(2)
1413
+ else:
1414
+ init_mask = mask
1415
+
1416
+ if i < len(timesteps) - 1:
1417
+ noise_timestep = timesteps[i + 1]
1418
+ init_latents_proper = self.scheduler.add_noise(
1419
+ init_latents_proper, noise, torch.tensor([noise_timestep])
1420
+ )
1421
+
1422
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1423
+
1424
+ if callback_on_step_end is not None:
1425
+ callback_kwargs = {}
1426
+ for k in callback_on_step_end_tensor_inputs:
1427
+ callback_kwargs[k] = locals()[k]
1428
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1429
+
1430
+ latents = callback_outputs.pop("latents", latents)
1431
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1432
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1433
+ mask = callback_outputs.pop("mask", mask)
1434
+ masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)
1435
+
1436
+ # call the callback, if provided
1437
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1438
+ progress_bar.update()
1439
+ if callback is not None and i % callback_steps == 0:
1440
+ step_idx = i // getattr(self.scheduler, "order", 1)
1441
+ callback(step_idx, t, latents)
1442
+
1443
+ if not output_type == "latent":
1444
+ condition_kwargs = {}
1445
+ if isinstance(self.vae, AsymmetricAutoencoderKL):
1446
+ init_image = init_image.to(device=device, dtype=masked_image_latents.dtype)
1447
+ init_image_condition = init_image.clone()
1448
+ init_image = self._encode_vae_image(init_image, generator=generator)
1449
+ mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype)
1450
+ condition_kwargs = {"image": init_image_condition, "mask": mask_condition}
1451
+ image = self.vae.decode(
1452
+ latents / self.vae.config.scaling_factor, return_dict=False, generator=generator, **condition_kwargs
1453
+ )[0]
1454
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1455
+ else:
1456
+ image = latents
1457
+ has_nsfw_concept = None
1458
+
1459
+ if has_nsfw_concept is None:
1460
+ do_denormalize = [True] * image.shape[0]
1461
+ else:
1462
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1463
+
1464
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1465
+
1466
+ if padding_mask_crop is not None:
1467
+ image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
1468
+
1469
+ # Offload all models
1470
+ self.maybe_free_model_hooks()
1471
+
1472
+ if not return_dict:
1473
+ return (image, has_nsfw_concept)
1474
+
1475
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)