MrAlex commited on
Commit
38fcd44
1 Parent(s): d02f467

Enable textual inversion

Browse files
Files changed (1) hide show
  1. pipeline.py +999 -0
pipeline.py ADDED
@@ -0,0 +1,999 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
2
+
3
+ import inspect
4
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
5
+
6
+ import numpy as np
7
+ import PIL.Image
8
+ import torch
9
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
10
+
11
+ from diffusers.loaders import FromCkptMixin, LoraLoaderMixin, TextualInversionLoaderMixin
12
+
13
+ from diffusers import AutoencoderKL, ControlNetModel, DiffusionPipeline, UNet2DConditionModel, logging
14
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
15
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
16
+ from diffusers.schedulers import KarrasDiffusionSchedulers
17
+ from diffusers.utils import (
18
+ PIL_INTERPOLATION,
19
+ is_accelerate_available,
20
+ is_accelerate_version,
21
+ randn_tensor,
22
+ replace_example_docstring,
23
+ )
24
+
25
+
26
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
27
+
28
+ EXAMPLE_DOC_STRING = """
29
+ Examples:
30
+ ```py
31
+ >>> import numpy as np
32
+ >>> import torch
33
+ >>> from PIL import Image
34
+ >>> from diffusers import ControlNetModel, UniPCMultistepScheduler
35
+ >>> from diffusers.utils import load_image
36
+
37
+ >>> input_image = load_image("https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png")
38
+
39
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
40
+
41
+ >>> pipe_controlnet = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
42
+ "runwayml/stable-diffusion-v1-5",
43
+ controlnet=controlnet,
44
+ safety_checker=None,
45
+ torch_dtype=torch.float16
46
+ )
47
+
48
+ >>> pipe_controlnet.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config)
49
+ >>> pipe_controlnet.enable_xformers_memory_efficient_attention()
50
+ >>> pipe_controlnet.enable_model_cpu_offload()
51
+
52
+ # using image with edges for our canny controlnet
53
+ >>> control_image = load_image(
54
+ "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/vermeer_canny_edged.png")
55
+
56
+
57
+ >>> result_img = pipe_controlnet(controlnet_conditioning_image=control_image,
58
+ image=input_image,
59
+ prompt="an android robot, cyberpank, digitl art masterpiece",
60
+ num_inference_steps=20).images[0]
61
+
62
+ >>> result_img.show()
63
+ ```
64
+ """
65
+
66
+
67
+ def prepare_image(image):
68
+ if isinstance(image, torch.Tensor):
69
+ # Batch single image
70
+ if image.ndim == 3:
71
+ image = image.unsqueeze(0)
72
+
73
+ image = image.to(dtype=torch.float32)
74
+ else:
75
+ # preprocess image
76
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
77
+ image = [image]
78
+
79
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
80
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
81
+ image = np.concatenate(image, axis=0)
82
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
83
+ image = np.concatenate([i[None, :] for i in image], axis=0)
84
+
85
+ image = image.transpose(0, 3, 1, 2)
86
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
87
+
88
+ return image
89
+
90
+
91
+ def prepare_controlnet_conditioning_image(
92
+ controlnet_conditioning_image,
93
+ width,
94
+ height,
95
+ batch_size,
96
+ num_images_per_prompt,
97
+ device,
98
+ dtype,
99
+ do_classifier_free_guidance,
100
+ ):
101
+ if not isinstance(controlnet_conditioning_image, torch.Tensor):
102
+ if isinstance(controlnet_conditioning_image, PIL.Image.Image):
103
+ controlnet_conditioning_image = [controlnet_conditioning_image]
104
+
105
+ if isinstance(controlnet_conditioning_image[0], PIL.Image.Image):
106
+ controlnet_conditioning_image = [
107
+ np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :]
108
+ for i in controlnet_conditioning_image
109
+ ]
110
+ controlnet_conditioning_image = np.concatenate(controlnet_conditioning_image, axis=0)
111
+ controlnet_conditioning_image = np.array(controlnet_conditioning_image).astype(np.float32) / 255.0
112
+ controlnet_conditioning_image = controlnet_conditioning_image.transpose(0, 3, 1, 2)
113
+ controlnet_conditioning_image = torch.from_numpy(controlnet_conditioning_image)
114
+ elif isinstance(controlnet_conditioning_image[0], torch.Tensor):
115
+ controlnet_conditioning_image = torch.cat(controlnet_conditioning_image, dim=0)
116
+
117
+ image_batch_size = controlnet_conditioning_image.shape[0]
118
+
119
+ if image_batch_size == 1:
120
+ repeat_by = batch_size
121
+ else:
122
+ # image batch size is the same as prompt batch size
123
+ repeat_by = num_images_per_prompt
124
+
125
+ controlnet_conditioning_image = controlnet_conditioning_image.repeat_interleave(repeat_by, dim=0)
126
+
127
+ controlnet_conditioning_image = controlnet_conditioning_image.to(device=device, dtype=dtype)
128
+
129
+ if do_classifier_free_guidance:
130
+ controlnet_conditioning_image = torch.cat([controlnet_conditioning_image] * 2)
131
+
132
+ return controlnet_conditioning_image
133
+
134
+
135
+ class StableDiffusionControlNetImg2ImgPipeline(DiffusionPipeline, TextualInversionLoaderMixin):
136
+ """
137
+ Inspired by: https://github.com/haofanwang/ControlNet-for-Diffusers/
138
+ """
139
+
140
+ _optional_components = ["safety_checker", "feature_extractor"]
141
+
142
+ def __init__(
143
+ self,
144
+ vae: AutoencoderKL,
145
+ text_encoder: CLIPTextModel,
146
+ tokenizer: CLIPTokenizer,
147
+ unet: UNet2DConditionModel,
148
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
149
+ scheduler: KarrasDiffusionSchedulers,
150
+ safety_checker: StableDiffusionSafetyChecker,
151
+ feature_extractor: CLIPImageProcessor,
152
+ requires_safety_checker: bool = True,
153
+ ):
154
+ super().__init__()
155
+
156
+ if safety_checker is None and requires_safety_checker:
157
+ logger.warning(
158
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
159
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
160
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
161
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
162
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
163
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
164
+ )
165
+
166
+ if safety_checker is not None and feature_extractor is None:
167
+ raise ValueError(
168
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
169
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
170
+ )
171
+
172
+ if isinstance(controlnet, (list, tuple)):
173
+ controlnet = MultiControlNetModel(controlnet)
174
+
175
+ self.register_modules(
176
+ vae=vae,
177
+ text_encoder=text_encoder,
178
+ tokenizer=tokenizer,
179
+ unet=unet,
180
+ controlnet=controlnet,
181
+ scheduler=scheduler,
182
+ safety_checker=safety_checker,
183
+ feature_extractor=feature_extractor,
184
+ )
185
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
186
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
187
+
188
+ def enable_vae_slicing(self):
189
+ r"""
190
+ Enable sliced VAE decoding.
191
+
192
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
193
+ steps. This is useful to save some memory and allow larger batch sizes.
194
+ """
195
+ self.vae.enable_slicing()
196
+
197
+ def disable_vae_slicing(self):
198
+ r"""
199
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
200
+ computing decoding in one step.
201
+ """
202
+ self.vae.disable_slicing()
203
+
204
+ def enable_sequential_cpu_offload(self, gpu_id=0):
205
+ r"""
206
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
207
+ text_encoder, vae, controlnet, and safety checker have their state dicts saved to CPU and then are moved to a
208
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
209
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
210
+ `enable_model_cpu_offload`, but performance is lower.
211
+ """
212
+ if is_accelerate_available():
213
+ from accelerate import cpu_offload
214
+ else:
215
+ raise ImportError("Please install accelerate via `pip install accelerate`")
216
+
217
+ device = torch.device(f"cuda:{gpu_id}")
218
+
219
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.controlnet]:
220
+ cpu_offload(cpu_offloaded_model, device)
221
+
222
+ if self.safety_checker is not None:
223
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
224
+
225
+ def enable_model_cpu_offload(self, gpu_id=0):
226
+ r"""
227
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
228
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
229
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
230
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
231
+ """
232
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
233
+ from accelerate import cpu_offload_with_hook
234
+ else:
235
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
236
+
237
+ device = torch.device(f"cuda:{gpu_id}")
238
+
239
+ hook = None
240
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
241
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
242
+
243
+ if self.safety_checker is not None:
244
+ # the safety checker can offload the vae again
245
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
246
+
247
+ # control net hook has be manually offloaded as it alternates with unet
248
+ cpu_offload_with_hook(self.controlnet, device)
249
+
250
+ # We'll offload the last model manually.
251
+ self.final_offload_hook = hook
252
+
253
+ @property
254
+ def _execution_device(self):
255
+ r"""
256
+ Returns the device on which the pipeline's models will be executed. After calling
257
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
258
+ hooks.
259
+ """
260
+ if not hasattr(self.unet, "_hf_hook"):
261
+ return self.device
262
+ for module in self.unet.modules():
263
+ if (
264
+ hasattr(module, "_hf_hook")
265
+ and hasattr(module._hf_hook, "execution_device")
266
+ and module._hf_hook.execution_device is not None
267
+ ):
268
+ return torch.device(module._hf_hook.execution_device)
269
+ return self.device
270
+
271
+ def _encode_prompt(
272
+ self,
273
+ prompt,
274
+ device,
275
+ num_images_per_prompt,
276
+ do_classifier_free_guidance,
277
+ negative_prompt=None,
278
+ prompt_embeds: Optional[torch.FloatTensor] = None,
279
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
280
+ ):
281
+ r"""
282
+ Encodes the prompt into text encoder hidden states.
283
+
284
+ Args:
285
+ prompt (`str` or `List[str]`, *optional*):
286
+ prompt to be encoded
287
+ device: (`torch.device`):
288
+ torch device
289
+ num_images_per_prompt (`int`):
290
+ number of images that should be generated per prompt
291
+ do_classifier_free_guidance (`bool`):
292
+ whether to use classifier free guidance or not
293
+ negative_prompt (`str` or `List[str]`, *optional*):
294
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
295
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
296
+ prompt_embeds (`torch.FloatTensor`, *optional*):
297
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
298
+ provided, text embeddings will be generated from `prompt` input argument.
299
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
300
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
301
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
302
+ argument.
303
+ """
304
+ if prompt is not None and isinstance(prompt, str):
305
+ batch_size = 1
306
+ elif prompt is not None and isinstance(prompt, list):
307
+ batch_size = len(prompt)
308
+ else:
309
+ batch_size = prompt_embeds.shape[0]
310
+
311
+ if prompt_embeds is None:
312
+ # textual inversion: procecss multi-vector tokens if necessary
313
+ if isinstance(self, TextualInversionLoaderMixin):
314
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
315
+
316
+ text_inputs = self.tokenizer(
317
+ prompt,
318
+ padding="max_length",
319
+ max_length=self.tokenizer.model_max_length,
320
+ truncation=True,
321
+ return_tensors="pt",
322
+ )
323
+ text_input_ids = text_inputs.input_ids
324
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
325
+
326
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
327
+ text_input_ids, untruncated_ids
328
+ ):
329
+ removed_text = self.tokenizer.batch_decode(
330
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
331
+ )
332
+ logger.warning(
333
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
334
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
335
+ )
336
+
337
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
338
+ attention_mask = text_inputs.attention_mask.to(device)
339
+ else:
340
+ attention_mask = None
341
+
342
+ prompt_embeds = self.text_encoder(
343
+ text_input_ids.to(device),
344
+ attention_mask=attention_mask,
345
+ )
346
+ prompt_embeds = prompt_embeds[0]
347
+
348
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
349
+
350
+ bs_embed, seq_len, _ = prompt_embeds.shape
351
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
352
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
353
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
354
+
355
+ # get unconditional embeddings for classifier free guidance
356
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
357
+ uncond_tokens: List[str]
358
+ if negative_prompt is None:
359
+ uncond_tokens = [""] * batch_size
360
+ elif type(prompt) is not type(negative_prompt):
361
+ raise TypeError(
362
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
363
+ f" {type(prompt)}."
364
+ )
365
+ elif isinstance(negative_prompt, str):
366
+ uncond_tokens = [negative_prompt]
367
+ elif batch_size != len(negative_prompt):
368
+ raise ValueError(
369
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
370
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
371
+ " the batch size of `prompt`."
372
+ )
373
+ else:
374
+ uncond_tokens = negative_prompt
375
+
376
+ # textual inversion: procecss multi-vector tokens if necessary
377
+ if isinstance(self, TextualInversionLoaderMixin):
378
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
379
+
380
+ max_length = prompt_embeds.shape[1]
381
+ uncond_input = self.tokenizer(
382
+ uncond_tokens,
383
+ padding="max_length",
384
+ max_length=max_length,
385
+ truncation=True,
386
+ return_tensors="pt",
387
+ )
388
+
389
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
390
+ attention_mask = uncond_input.attention_mask.to(device)
391
+ else:
392
+ attention_mask = None
393
+
394
+ negative_prompt_embeds = self.text_encoder(
395
+ uncond_input.input_ids.to(device),
396
+ attention_mask=attention_mask,
397
+ )
398
+ negative_prompt_embeds = negative_prompt_embeds[0]
399
+
400
+ if do_classifier_free_guidance:
401
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
402
+ seq_len = negative_prompt_embeds.shape[1]
403
+
404
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
405
+
406
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
407
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
408
+
409
+ # For classifier free guidance, we need to do two forward passes.
410
+ # Here we concatenate the unconditional and text embeddings into a single batch
411
+ # to avoid doing two forward passes
412
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
413
+
414
+ return prompt_embeds
415
+
416
+ def run_safety_checker(self, image, device, dtype):
417
+ if self.safety_checker is not None:
418
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
419
+ image, has_nsfw_concept = self.safety_checker(
420
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
421
+ )
422
+ else:
423
+ has_nsfw_concept = None
424
+ return image, has_nsfw_concept
425
+
426
+ def decode_latents(self, latents):
427
+ latents = 1 / self.vae.config.scaling_factor * latents
428
+ image = self.vae.decode(latents).sample
429
+ image = (image / 2 + 0.5).clamp(0, 1)
430
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
431
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
432
+ return image
433
+
434
+ def prepare_extra_step_kwargs(self, generator, eta):
435
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
436
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
437
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
438
+ # and should be between [0, 1]
439
+
440
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
441
+ extra_step_kwargs = {}
442
+ if accepts_eta:
443
+ extra_step_kwargs["eta"] = eta
444
+
445
+ # check if the scheduler accepts generator
446
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
447
+ if accepts_generator:
448
+ extra_step_kwargs["generator"] = generator
449
+ return extra_step_kwargs
450
+
451
+ def check_controlnet_conditioning_image(self, image, prompt, prompt_embeds):
452
+ image_is_pil = isinstance(image, PIL.Image.Image)
453
+ image_is_tensor = isinstance(image, torch.Tensor)
454
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
455
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
456
+
457
+ if not image_is_pil and not image_is_tensor and not image_is_pil_list and not image_is_tensor_list:
458
+ raise TypeError(
459
+ "image must be passed and be one of PIL image, torch tensor, list of PIL images, or list of torch tensors"
460
+ )
461
+
462
+ if image_is_pil:
463
+ image_batch_size = 1
464
+ elif image_is_tensor:
465
+ image_batch_size = image.shape[0]
466
+ elif image_is_pil_list:
467
+ image_batch_size = len(image)
468
+ elif image_is_tensor_list:
469
+ image_batch_size = len(image)
470
+ else:
471
+ raise ValueError("controlnet condition image is not valid")
472
+
473
+ if prompt is not None and isinstance(prompt, str):
474
+ prompt_batch_size = 1
475
+ elif prompt is not None and isinstance(prompt, list):
476
+ prompt_batch_size = len(prompt)
477
+ elif prompt_embeds is not None:
478
+ prompt_batch_size = prompt_embeds.shape[0]
479
+ else:
480
+ raise ValueError("prompt or prompt_embeds are not valid")
481
+
482
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
483
+ raise ValueError(
484
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
485
+ )
486
+
487
+ def check_inputs(
488
+ self,
489
+ prompt,
490
+ image,
491
+ controlnet_conditioning_image,
492
+ height,
493
+ width,
494
+ callback_steps,
495
+ negative_prompt=None,
496
+ prompt_embeds=None,
497
+ negative_prompt_embeds=None,
498
+ strength=None,
499
+ controlnet_guidance_start=None,
500
+ controlnet_guidance_end=None,
501
+ controlnet_conditioning_scale=None,
502
+ ):
503
+ if height % 8 != 0 or width % 8 != 0:
504
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
505
+
506
+ if (callback_steps is None) or (
507
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
508
+ ):
509
+ raise ValueError(
510
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
511
+ f" {type(callback_steps)}."
512
+ )
513
+
514
+ if prompt is not None and prompt_embeds is not None:
515
+ raise ValueError(
516
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
517
+ " only forward one of the two."
518
+ )
519
+ elif prompt is None and prompt_embeds is None:
520
+ raise ValueError(
521
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
522
+ )
523
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
524
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
525
+
526
+ if negative_prompt is not None and negative_prompt_embeds is not None:
527
+ raise ValueError(
528
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
529
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
530
+ )
531
+
532
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
533
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
534
+ raise ValueError(
535
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
536
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
537
+ f" {negative_prompt_embeds.shape}."
538
+ )
539
+
540
+ # check controlnet condition image
541
+
542
+ if isinstance(self.controlnet, ControlNetModel):
543
+ self.check_controlnet_conditioning_image(controlnet_conditioning_image, prompt, prompt_embeds)
544
+ elif isinstance(self.controlnet, MultiControlNetModel):
545
+ if not isinstance(controlnet_conditioning_image, list):
546
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
547
+
548
+ if len(controlnet_conditioning_image) != len(self.controlnet.nets):
549
+ raise ValueError(
550
+ "For multiple controlnets: `image` must have the same length as the number of controlnets."
551
+ )
552
+
553
+ for image_ in controlnet_conditioning_image:
554
+ self.check_controlnet_conditioning_image(image_, prompt, prompt_embeds)
555
+ else:
556
+ assert False
557
+
558
+ # Check `controlnet_conditioning_scale`
559
+
560
+ if isinstance(self.controlnet, ControlNetModel):
561
+ if not isinstance(controlnet_conditioning_scale, float):
562
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
563
+ elif isinstance(self.controlnet, MultiControlNetModel):
564
+ if isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
565
+ self.controlnet.nets
566
+ ):
567
+ raise ValueError(
568
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
569
+ " the same length as the number of controlnets"
570
+ )
571
+ else:
572
+ assert False
573
+
574
+ if isinstance(image, torch.Tensor):
575
+ if image.ndim != 3 and image.ndim != 4:
576
+ raise ValueError("`image` must have 3 or 4 dimensions")
577
+
578
+ if image.ndim == 3:
579
+ image_batch_size = 1
580
+ image_channels, image_height, image_width = image.shape
581
+ elif image.ndim == 4:
582
+ image_batch_size, image_channels, image_height, image_width = image.shape
583
+ else:
584
+ assert False
585
+
586
+ if image_channels != 3:
587
+ raise ValueError("`image` must have 3 channels")
588
+
589
+ if image.min() < -1 or image.max() > 1:
590
+ raise ValueError("`image` should be in range [-1, 1]")
591
+
592
+ if self.vae.config.latent_channels != self.unet.config.in_channels:
593
+ raise ValueError(
594
+ f"The config of `pipeline.unet` expects {self.unet.config.in_channels} but received"
595
+ f" latent channels: {self.vae.config.latent_channels},"
596
+ f" Please verify the config of `pipeline.unet` and the `pipeline.vae`"
597
+ )
598
+
599
+ if strength < 0 or strength > 1:
600
+ raise ValueError(f"The value of `strength` should in [0.0, 1.0] but is {strength}")
601
+
602
+ if controlnet_guidance_start < 0 or controlnet_guidance_start > 1:
603
+ raise ValueError(
604
+ f"The value of `controlnet_guidance_start` should in [0.0, 1.0] but is {controlnet_guidance_start}"
605
+ )
606
+
607
+ if controlnet_guidance_end < 0 or controlnet_guidance_end > 1:
608
+ raise ValueError(
609
+ f"The value of `controlnet_guidance_end` should in [0.0, 1.0] but is {controlnet_guidance_end}"
610
+ )
611
+
612
+ if controlnet_guidance_start > controlnet_guidance_end:
613
+ raise ValueError(
614
+ "The value of `controlnet_guidance_start` should be less than `controlnet_guidance_end`, but got"
615
+ f" `controlnet_guidance_start` {controlnet_guidance_start} >= `controlnet_guidance_end` {controlnet_guidance_end}"
616
+ )
617
+
618
+ def get_timesteps(self, num_inference_steps, strength, device):
619
+ # get the original timestep using init_timestep
620
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
621
+
622
+ t_start = max(num_inference_steps - init_timestep, 0)
623
+ timesteps = self.scheduler.timesteps[t_start:]
624
+
625
+ return timesteps, num_inference_steps - t_start
626
+
627
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
628
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
629
+ raise ValueError(
630
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
631
+ )
632
+
633
+ image = image.to(device=device, dtype=dtype)
634
+
635
+ batch_size = batch_size * num_images_per_prompt
636
+ if isinstance(generator, list) and len(generator) != batch_size:
637
+ raise ValueError(
638
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
639
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
640
+ )
641
+
642
+ if isinstance(generator, list):
643
+ init_latents = [
644
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
645
+ ]
646
+ init_latents = torch.cat(init_latents, dim=0)
647
+ else:
648
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
649
+
650
+ init_latents = self.vae.config.scaling_factor * init_latents
651
+
652
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
653
+ raise ValueError(
654
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
655
+ )
656
+ else:
657
+ init_latents = torch.cat([init_latents], dim=0)
658
+
659
+ shape = init_latents.shape
660
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
661
+
662
+ # get latents
663
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
664
+ latents = init_latents
665
+
666
+ return latents
667
+
668
+ def _default_height_width(self, height, width, image):
669
+ if isinstance(image, list):
670
+ image = image[0]
671
+
672
+ if height is None:
673
+ if isinstance(image, PIL.Image.Image):
674
+ height = image.height
675
+ elif isinstance(image, torch.Tensor):
676
+ height = image.shape[3]
677
+
678
+ height = (height // 8) * 8 # round down to nearest multiple of 8
679
+
680
+ if width is None:
681
+ if isinstance(image, PIL.Image.Image):
682
+ width = image.width
683
+ elif isinstance(image, torch.Tensor):
684
+ width = image.shape[2]
685
+
686
+ width = (width // 8) * 8 # round down to nearest multiple of 8
687
+
688
+ return height, width
689
+
690
+ @torch.no_grad()
691
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
692
+ def __call__(
693
+ self,
694
+ prompt: Union[str, List[str]] = None,
695
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
696
+ controlnet_conditioning_image: Union[
697
+ torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]
698
+ ] = None,
699
+ strength: float = 0.8,
700
+ height: Optional[int] = None,
701
+ width: Optional[int] = None,
702
+ num_inference_steps: int = 50,
703
+ guidance_scale: float = 7.5,
704
+ negative_prompt: Optional[Union[str, List[str]]] = None,
705
+ num_images_per_prompt: Optional[int] = 1,
706
+ eta: float = 0.0,
707
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
708
+ latents: Optional[torch.FloatTensor] = None,
709
+ prompt_embeds: Optional[torch.FloatTensor] = None,
710
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
711
+ output_type: Optional[str] = "pil",
712
+ return_dict: bool = True,
713
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
714
+ callback_steps: int = 1,
715
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
716
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
717
+ controlnet_guidance_start: float = 0.0,
718
+ controlnet_guidance_end: float = 1.0,
719
+ ):
720
+ r"""
721
+ Function invoked when calling the pipeline for generation.
722
+
723
+ Args:
724
+ prompt (`str` or `List[str]`, *optional*):
725
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
726
+ instead.
727
+ image (`torch.Tensor` or `PIL.Image.Image`):
728
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
729
+ be masked out with `mask_image` and repainted according to `prompt`.
730
+ controlnet_conditioning_image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]` or `List[PIL.Image.Image]`):
731
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
732
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. PIL.Image.Image` can
733
+ also be accepted as an image. The control image is automatically resized to fit the output image.
734
+ strength (`float`, *optional*):
735
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
736
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
737
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
738
+ be maximum and the denoising process will run for the full number of iterations specified in
739
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
740
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
741
+ The height in pixels of the generated image.
742
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
743
+ The width in pixels of the generated image.
744
+ num_inference_steps (`int`, *optional*, defaults to 50):
745
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
746
+ expense of slower inference.
747
+ guidance_scale (`float`, *optional*, defaults to 7.5):
748
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
749
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
750
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
751
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
752
+ usually at the expense of lower image quality.
753
+ negative_prompt (`str` or `List[str]`, *optional*):
754
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
755
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
756
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
757
+ The number of images to generate per prompt.
758
+ eta (`float`, *optional*, defaults to 0.0):
759
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
760
+ [`schedulers.DDIMScheduler`], will be ignored for others.
761
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
762
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
763
+ to make generation deterministic.
764
+ latents (`torch.FloatTensor`, *optional*):
765
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
766
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
767
+ tensor will ge generated by sampling using the supplied random `generator`.
768
+ prompt_embeds (`torch.FloatTensor`, *optional*):
769
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
770
+ provided, text embeddings will be generated from `prompt` input argument.
771
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
772
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
773
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
774
+ argument.
775
+ output_type (`str`, *optional*, defaults to `"pil"`):
776
+ The output format of the generate image. Choose between
777
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
778
+ return_dict (`bool`, *optional*, defaults to `True`):
779
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
780
+ plain tuple.
781
+ callback (`Callable`, *optional*):
782
+ A function that will be called every `callback_steps` steps during inference. The function will be
783
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
784
+ callback_steps (`int`, *optional*, defaults to 1):
785
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
786
+ called at every step.
787
+ cross_attention_kwargs (`dict`, *optional*):
788
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
789
+ `self.processor` in
790
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
791
+ controlnet_conditioning_scale (`float`, *optional*, defaults to 1.0):
792
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
793
+ to the residual in the original unet.
794
+ controlnet_guidance_start ('float', *optional*, defaults to 0.0):
795
+ The percentage of total steps the controlnet starts applying. Must be between 0 and 1.
796
+ controlnet_guidance_end ('float', *optional*, defaults to 1.0):
797
+ The percentage of total steps the controlnet ends applying. Must be between 0 and 1. Must be greater
798
+ than `controlnet_guidance_start`.
799
+
800
+ Examples:
801
+
802
+ Returns:
803
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
804
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
805
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
806
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
807
+ (nsfw) content, according to the `safety_checker`.
808
+ """
809
+ # 0. Default height and width to unet
810
+ height, width = self._default_height_width(height, width, controlnet_conditioning_image)
811
+
812
+ # 1. Check inputs. Raise error if not correct
813
+ self.check_inputs(
814
+ prompt,
815
+ image,
816
+ controlnet_conditioning_image,
817
+ height,
818
+ width,
819
+ callback_steps,
820
+ negative_prompt,
821
+ prompt_embeds,
822
+ negative_prompt_embeds,
823
+ strength,
824
+ controlnet_guidance_start,
825
+ controlnet_guidance_end,
826
+ controlnet_conditioning_scale,
827
+ )
828
+
829
+ # 2. Define call parameters
830
+ if prompt is not None and isinstance(prompt, str):
831
+ batch_size = 1
832
+ elif prompt is not None and isinstance(prompt, list):
833
+ batch_size = len(prompt)
834
+ else:
835
+ batch_size = prompt_embeds.shape[0]
836
+
837
+ device = self._execution_device
838
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
839
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
840
+ # corresponds to doing no classifier free guidance.
841
+ do_classifier_free_guidance = guidance_scale > 1.0
842
+
843
+ if isinstance(self.controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
844
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(self.controlnet.nets)
845
+
846
+ # 3. Encode input prompt
847
+ prompt_embeds = self._encode_prompt(
848
+ prompt,
849
+ device,
850
+ num_images_per_prompt,
851
+ do_classifier_free_guidance,
852
+ negative_prompt,
853
+ prompt_embeds=prompt_embeds,
854
+ negative_prompt_embeds=negative_prompt_embeds,
855
+ )
856
+
857
+ # 4. Prepare image, and controlnet_conditioning_image
858
+ image = prepare_image(image)
859
+
860
+ # condition image(s)
861
+ if isinstance(self.controlnet, ControlNetModel):
862
+ controlnet_conditioning_image = prepare_controlnet_conditioning_image(
863
+ controlnet_conditioning_image=controlnet_conditioning_image,
864
+ width=width,
865
+ height=height,
866
+ batch_size=batch_size * num_images_per_prompt,
867
+ num_images_per_prompt=num_images_per_prompt,
868
+ device=device,
869
+ dtype=self.controlnet.dtype,
870
+ do_classifier_free_guidance=do_classifier_free_guidance,
871
+ )
872
+ elif isinstance(self.controlnet, MultiControlNetModel):
873
+ controlnet_conditioning_images = []
874
+
875
+ for image_ in controlnet_conditioning_image:
876
+ image_ = prepare_controlnet_conditioning_image(
877
+ controlnet_conditioning_image=image_,
878
+ width=width,
879
+ height=height,
880
+ batch_size=batch_size * num_images_per_prompt,
881
+ num_images_per_prompt=num_images_per_prompt,
882
+ device=device,
883
+ dtype=self.controlnet.dtype,
884
+ do_classifier_free_guidance=do_classifier_free_guidance,
885
+ )
886
+
887
+ controlnet_conditioning_images.append(image_)
888
+
889
+ controlnet_conditioning_image = controlnet_conditioning_images
890
+ else:
891
+ assert False
892
+
893
+ # 5. Prepare timesteps
894
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
895
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
896
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
897
+
898
+ # 6. Prepare latent variables
899
+ latents = self.prepare_latents(
900
+ image,
901
+ latent_timestep,
902
+ batch_size,
903
+ num_images_per_prompt,
904
+ prompt_embeds.dtype,
905
+ device,
906
+ generator,
907
+ )
908
+
909
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
910
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
911
+
912
+ # 8. Denoising loop
913
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
914
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
915
+ for i, t in enumerate(timesteps):
916
+ # expand the latents if we are doing classifier free guidance
917
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
918
+
919
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
920
+
921
+ # compute the percentage of total steps we are at
922
+ current_sampling_percent = i / len(timesteps)
923
+
924
+ if (
925
+ current_sampling_percent < controlnet_guidance_start
926
+ or current_sampling_percent > controlnet_guidance_end
927
+ ):
928
+ # do not apply the controlnet
929
+ down_block_res_samples = None
930
+ mid_block_res_sample = None
931
+ else:
932
+ # apply the controlnet
933
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
934
+ latent_model_input,
935
+ t,
936
+ encoder_hidden_states=prompt_embeds,
937
+ controlnet_cond=controlnet_conditioning_image,
938
+ conditioning_scale=controlnet_conditioning_scale,
939
+ return_dict=False,
940
+ )
941
+
942
+ # predict the noise residual
943
+ noise_pred = self.unet(
944
+ latent_model_input,
945
+ t,
946
+ encoder_hidden_states=prompt_embeds,
947
+ cross_attention_kwargs=cross_attention_kwargs,
948
+ down_block_additional_residuals=down_block_res_samples,
949
+ mid_block_additional_residual=mid_block_res_sample,
950
+ ).sample
951
+
952
+ # perform guidance
953
+ if do_classifier_free_guidance:
954
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
955
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
956
+
957
+ # compute the previous noisy sample x_t -> x_t-1
958
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
959
+
960
+ # call the callback, if provided
961
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
962
+ progress_bar.update()
963
+ if callback is not None and i % callback_steps == 0:
964
+ callback(i, t, latents)
965
+
966
+ # If we do sequential model offloading, let's offload unet and controlnet
967
+ # manually for max memory savings
968
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
969
+ self.unet.to("cpu")
970
+ self.controlnet.to("cpu")
971
+ torch.cuda.empty_cache()
972
+
973
+ if output_type == "latent":
974
+ image = latents
975
+ has_nsfw_concept = None
976
+ elif output_type == "pil":
977
+ # 8. Post-processing
978
+ image = self.decode_latents(latents)
979
+
980
+ # 9. Run safety checker
981
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
982
+
983
+ # 10. Convert to PIL
984
+ image = self.numpy_to_pil(image)
985
+ else:
986
+ # 8. Post-processing
987
+ image = self.decode_latents(latents)
988
+
989
+ # 9. Run safety checker
990
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
991
+
992
+ # Offload last model to CPU
993
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
994
+ self.final_offload_hook.offload()
995
+
996
+ if not return_dict:
997
+ return (image, has_nsfw_concept)
998
+
999
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)