diffusers 0.15.1__py3-none-any.whl → 0.16.1__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (57) hide show
  1. diffusers/__init__.py +7 -2
  2. diffusers/configuration_utils.py +4 -0
  3. diffusers/loaders.py +262 -12
  4. diffusers/models/attention.py +31 -12
  5. diffusers/models/attention_processor.py +189 -0
  6. diffusers/models/controlnet.py +9 -2
  7. diffusers/models/embeddings.py +66 -0
  8. diffusers/models/modeling_pytorch_flax_utils.py +6 -0
  9. diffusers/models/modeling_utils.py +5 -2
  10. diffusers/models/transformer_2d.py +1 -1
  11. diffusers/models/unet_2d_condition.py +45 -6
  12. diffusers/models/vae.py +3 -0
  13. diffusers/pipelines/__init__.py +8 -0
  14. diffusers/pipelines/alt_diffusion/modeling_roberta_series.py +25 -10
  15. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +8 -0
  16. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +8 -0
  17. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -1
  18. diffusers/pipelines/deepfloyd_if/__init__.py +54 -0
  19. diffusers/pipelines/deepfloyd_if/pipeline_if.py +854 -0
  20. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +979 -0
  21. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +1097 -0
  22. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +1098 -0
  23. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +1208 -0
  24. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +947 -0
  25. diffusers/pipelines/deepfloyd_if/safety_checker.py +59 -0
  26. diffusers/pipelines/deepfloyd_if/timesteps.py +579 -0
  27. diffusers/pipelines/deepfloyd_if/watermark.py +46 -0
  28. diffusers/pipelines/pipeline_utils.py +54 -25
  29. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +37 -20
  30. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion_controlnet.py +1 -1
  31. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +12 -1
  32. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +10 -2
  33. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +10 -8
  34. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_controlnet.py +59 -4
  35. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +9 -2
  36. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +10 -2
  37. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +9 -2
  38. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +22 -12
  39. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +9 -2
  40. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +34 -30
  41. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +93 -10
  42. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +45 -6
  43. diffusers/schedulers/scheduling_ddpm.py +63 -16
  44. diffusers/schedulers/scheduling_heun_discrete.py +51 -1
  45. diffusers/utils/__init__.py +4 -1
  46. diffusers/utils/dummy_torch_and_transformers_objects.py +80 -5
  47. diffusers/utils/dynamic_modules_utils.py +1 -1
  48. diffusers/utils/hub_utils.py +4 -1
  49. diffusers/utils/import_utils.py +41 -0
  50. diffusers/utils/pil_utils.py +24 -0
  51. diffusers/utils/testing_utils.py +10 -0
  52. {diffusers-0.15.1.dist-info → diffusers-0.16.1.dist-info}/METADATA +1 -1
  53. {diffusers-0.15.1.dist-info → diffusers-0.16.1.dist-info}/RECORD +57 -47
  54. {diffusers-0.15.1.dist-info → diffusers-0.16.1.dist-info}/LICENSE +0 -0
  55. {diffusers-0.15.1.dist-info → diffusers-0.16.1.dist-info}/WHEEL +0 -0
  56. {diffusers-0.15.1.dist-info → diffusers-0.16.1.dist-info}/entry_points.txt +0 -0
  57. {diffusers-0.15.1.dist-info → diffusers-0.16.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1097 @@
1
+ import html
2
+ import inspect
3
+ import re
4
+ import urllib.parse as ul
5
+ from typing import Any, Callable, Dict, List, Optional, Union
6
+
7
+ import numpy as np
8
+ import PIL
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from transformers import CLIPImageProcessor, T5EncoderModel, T5Tokenizer
12
+
13
+ from ...models import UNet2DConditionModel
14
+ from ...schedulers import DDPMScheduler
15
+ from ...utils import (
16
+ BACKENDS_MAPPING,
17
+ PIL_INTERPOLATION,
18
+ is_accelerate_available,
19
+ is_accelerate_version,
20
+ is_bs4_available,
21
+ is_ftfy_available,
22
+ logging,
23
+ randn_tensor,
24
+ replace_example_docstring,
25
+ )
26
+ from ..pipeline_utils import DiffusionPipeline
27
+ from . import IFPipelineOutput
28
+ from .safety_checker import IFSafetyChecker
29
+ from .watermark import IFWatermarker
30
+
31
+
32
+ if is_bs4_available():
33
+ from bs4 import BeautifulSoup
34
+
35
+ if is_ftfy_available():
36
+ import ftfy
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if_img2img.resize
43
+ def resize(images: PIL.Image.Image, img_size: int) -> PIL.Image.Image:
44
+ w, h = images.size
45
+
46
+ coef = w / h
47
+
48
+ w, h = img_size, img_size
49
+
50
+ if coef >= 1:
51
+ w = int(round(img_size / 8 * coef) * 8)
52
+ else:
53
+ h = int(round(img_size / 8 / coef) * 8)
54
+
55
+ images = images.resize((w, h), resample=PIL_INTERPOLATION["bicubic"], reducing_gap=None)
56
+
57
+ return images
58
+
59
+
60
+ EXAMPLE_DOC_STRING = """
61
+ Examples:
62
+ ```py
63
+ >>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
64
+ >>> from diffusers.utils import pt_to_pil
65
+ >>> import torch
66
+ >>> from PIL import Image
67
+ >>> import requests
68
+ >>> from io import BytesIO
69
+
70
+ >>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
71
+ >>> response = requests.get(url)
72
+ >>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
73
+ >>> original_image = original_image.resize((768, 512))
74
+
75
+ >>> pipe = IFImg2ImgPipeline.from_pretrained(
76
+ ... "DeepFloyd/IF-I-XL-v1.0",
77
+ ... variant="fp16",
78
+ ... torch_dtype=torch.float16,
79
+ ... )
80
+ >>> pipe.enable_model_cpu_offload()
81
+
82
+ >>> prompt = "A fantasy landscape in style minecraft"
83
+ >>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
84
+
85
+ >>> image = pipe(
86
+ ... image=original_image,
87
+ ... prompt_embeds=prompt_embeds,
88
+ ... negative_prompt_embeds=negative_embeds,
89
+ ... output_type="pt",
90
+ ... ).images
91
+
92
+ >>> # save intermediate image
93
+ >>> pil_image = pt_to_pil(image)
94
+ >>> pil_image[0].save("./if_stage_I.png")
95
+
96
+ >>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
97
+ ... "DeepFloyd/IF-II-L-v1.0",
98
+ ... text_encoder=None,
99
+ ... variant="fp16",
100
+ ... torch_dtype=torch.float16,
101
+ ... )
102
+ >>> super_res_1_pipe.enable_model_cpu_offload()
103
+
104
+ >>> image = super_res_1_pipe(
105
+ ... image=image,
106
+ ... original_image=original_image,
107
+ ... prompt_embeds=prompt_embeds,
108
+ ... negative_prompt_embeds=negative_embeds,
109
+ ... ).images
110
+ >>> image[0].save("./if_stage_II.png")
111
+ ```
112
+ """
113
+
114
+
115
+ class IFImg2ImgSuperResolutionPipeline(DiffusionPipeline):
116
+ tokenizer: T5Tokenizer
117
+ text_encoder: T5EncoderModel
118
+
119
+ unet: UNet2DConditionModel
120
+ scheduler: DDPMScheduler
121
+ image_noising_scheduler: DDPMScheduler
122
+
123
+ feature_extractor: Optional[CLIPImageProcessor]
124
+ safety_checker: Optional[IFSafetyChecker]
125
+
126
+ watermarker: Optional[IFWatermarker]
127
+
128
+ bad_punct_regex = re.compile(
129
+ r"[" + "#®•©™&@·º½¾¿¡§~" + "\)" + "\(" + "\]" + "\[" + "\}" + "\{" + "\|" + "\\" + "\/" + "\*" + r"]{1,}"
130
+ ) # noqa
131
+
132
+ _optional_components = ["tokenizer", "text_encoder", "safety_checker", "feature_extractor"]
133
+
134
+ def __init__(
135
+ self,
136
+ tokenizer: T5Tokenizer,
137
+ text_encoder: T5EncoderModel,
138
+ unet: UNet2DConditionModel,
139
+ scheduler: DDPMScheduler,
140
+ image_noising_scheduler: DDPMScheduler,
141
+ safety_checker: Optional[IFSafetyChecker],
142
+ feature_extractor: Optional[CLIPImageProcessor],
143
+ watermarker: Optional[IFWatermarker],
144
+ requires_safety_checker: bool = True,
145
+ ):
146
+ super().__init__()
147
+
148
+ if safety_checker is None and requires_safety_checker:
149
+ logger.warning(
150
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
151
+ " that you abide to the conditions of the IF license and do not expose unfiltered"
152
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
153
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
154
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
155
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
156
+ )
157
+
158
+ if safety_checker is not None and feature_extractor is None:
159
+ raise ValueError(
160
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
161
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
162
+ )
163
+
164
+ if unet.config.in_channels != 6:
165
+ logger.warn(
166
+ "It seems like you have loaded a checkpoint that shall not be used for super resolution from {unet.config._name_or_path} as it accepts {unet.config.in_channels} input channels instead of 6. Please make sure to pass a super resolution checkpoint as the `'unet'`: IFSuperResolutionPipeline.from_pretrained(unet=super_resolution_unet, ...)`."
167
+ )
168
+
169
+ self.register_modules(
170
+ tokenizer=tokenizer,
171
+ text_encoder=text_encoder,
172
+ unet=unet,
173
+ scheduler=scheduler,
174
+ image_noising_scheduler=image_noising_scheduler,
175
+ safety_checker=safety_checker,
176
+ feature_extractor=feature_extractor,
177
+ watermarker=watermarker,
178
+ )
179
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
180
+
181
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline.enable_sequential_cpu_offload
182
+ def enable_sequential_cpu_offload(self, gpu_id=0):
183
+ r"""
184
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, the pipeline's
185
+ models have their state dicts saved to CPU and then are moved to a `torch.device('meta') and loaded to GPU only
186
+ when their specific submodule has its `forward` method called.
187
+ """
188
+ if is_accelerate_available():
189
+ from accelerate import cpu_offload
190
+ else:
191
+ raise ImportError("Please install accelerate via `pip install accelerate`")
192
+
193
+ device = torch.device(f"cuda:{gpu_id}")
194
+
195
+ models = [
196
+ self.text_encoder,
197
+ self.unet,
198
+ ]
199
+ for cpu_offloaded_model in models:
200
+ if cpu_offloaded_model is not None:
201
+ cpu_offload(cpu_offloaded_model, device)
202
+
203
+ if self.safety_checker is not None:
204
+ cpu_offload(self.safety_checker, execution_device=device, offload_buffers=True)
205
+
206
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline.enable_model_cpu_offload
207
+ def enable_model_cpu_offload(self, gpu_id=0):
208
+ r"""
209
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
210
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
211
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
212
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
213
+ """
214
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
215
+ from accelerate import cpu_offload_with_hook
216
+ else:
217
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
218
+
219
+ device = torch.device(f"cuda:{gpu_id}")
220
+
221
+ if self.device.type != "cpu":
222
+ self.to("cpu", silence_dtype_warnings=True)
223
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
224
+
225
+ hook = None
226
+
227
+ if self.text_encoder is not None:
228
+ _, hook = cpu_offload_with_hook(self.text_encoder, device, prev_module_hook=hook)
229
+
230
+ # Accelerate will move the next model to the device _before_ calling the offload hook of the
231
+ # previous model. This will cause both models to be present on the device at the same time.
232
+ # IF uses T5 for its text encoder which is really large. We can manually call the offload
233
+ # hook for the text encoder to ensure it's moved to the cpu before the unet is moved to
234
+ # the GPU.
235
+ self.text_encoder_offload_hook = hook
236
+
237
+ _, hook = cpu_offload_with_hook(self.unet, device, prev_module_hook=hook)
238
+
239
+ # if the safety checker isn't called, `unet_offload_hook` will have to be called to manually offload the unet
240
+ self.unet_offload_hook = hook
241
+
242
+ if self.safety_checker is not None:
243
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
244
+
245
+ # We'll offload the last model manually.
246
+ self.final_offload_hook = hook
247
+
248
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline.remove_all_hooks
249
+ def remove_all_hooks(self):
250
+ if is_accelerate_available():
251
+ from accelerate.hooks import remove_hook_from_module
252
+ else:
253
+ raise ImportError("Please install accelerate via `pip install accelerate`")
254
+
255
+ for model in [self.text_encoder, self.unet, self.safety_checker]:
256
+ if model is not None:
257
+ remove_hook_from_module(model, recurse=True)
258
+
259
+ self.unet_offload_hook = None
260
+ self.text_encoder_offload_hook = None
261
+ self.final_offload_hook = None
262
+
263
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
264
+ def _text_preprocessing(self, text, clean_caption=False):
265
+ if clean_caption and not is_bs4_available():
266
+ logger.warn(BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`"))
267
+ logger.warn("Setting `clean_caption` to False...")
268
+ clean_caption = False
269
+
270
+ if clean_caption and not is_ftfy_available():
271
+ logger.warn(BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`"))
272
+ logger.warn("Setting `clean_caption` to False...")
273
+ clean_caption = False
274
+
275
+ if not isinstance(text, (tuple, list)):
276
+ text = [text]
277
+
278
+ def process(text: str):
279
+ if clean_caption:
280
+ text = self._clean_caption(text)
281
+ text = self._clean_caption(text)
282
+ else:
283
+ text = text.lower().strip()
284
+ return text
285
+
286
+ return [process(t) for t in text]
287
+
288
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
289
+ def _clean_caption(self, caption):
290
+ caption = str(caption)
291
+ caption = ul.unquote_plus(caption)
292
+ caption = caption.strip().lower()
293
+ caption = re.sub("<person>", "person", caption)
294
+ # urls:
295
+ caption = re.sub(
296
+ r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
297
+ "",
298
+ caption,
299
+ ) # regex for urls
300
+ caption = re.sub(
301
+ r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
302
+ "",
303
+ caption,
304
+ ) # regex for urls
305
+ # html:
306
+ caption = BeautifulSoup(caption, features="html.parser").text
307
+
308
+ # @<nickname>
309
+ caption = re.sub(r"@[\w\d]+\b", "", caption)
310
+
311
+ # 31C0—31EF CJK Strokes
312
+ # 31F0—31FF Katakana Phonetic Extensions
313
+ # 3200—32FF Enclosed CJK Letters and Months
314
+ # 3300—33FF CJK Compatibility
315
+ # 3400—4DBF CJK Unified Ideographs Extension A
316
+ # 4DC0—4DFF Yijing Hexagram Symbols
317
+ # 4E00—9FFF CJK Unified Ideographs
318
+ caption = re.sub(r"[\u31c0-\u31ef]+", "", caption)
319
+ caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)
320
+ caption = re.sub(r"[\u3200-\u32ff]+", "", caption)
321
+ caption = re.sub(r"[\u3300-\u33ff]+", "", caption)
322
+ caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)
323
+ caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)
324
+ caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)
325
+ #######################################################
326
+
327
+ # все виды тире / all types of dash --> "-"
328
+ caption = re.sub(
329
+ r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
330
+ "-",
331
+ caption,
332
+ )
333
+
334
+ # кавычки к одному стандарту
335
+ caption = re.sub(r"[`´«»“”¨]", '"', caption)
336
+ caption = re.sub(r"[‘’]", "'", caption)
337
+
338
+ # &quot;
339
+ caption = re.sub(r"&quot;?", "", caption)
340
+ # &amp
341
+ caption = re.sub(r"&amp", "", caption)
342
+
343
+ # ip adresses:
344
+ caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)
345
+
346
+ # article ids:
347
+ caption = re.sub(r"\d:\d\d\s+$", "", caption)
348
+
349
+ # \n
350
+ caption = re.sub(r"\\n", " ", caption)
351
+
352
+ # "#123"
353
+ caption = re.sub(r"#\d{1,3}\b", "", caption)
354
+ # "#12345.."
355
+ caption = re.sub(r"#\d{5,}\b", "", caption)
356
+ # "123456.."
357
+ caption = re.sub(r"\b\d{6,}\b", "", caption)
358
+ # filenames:
359
+ caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption)
360
+
361
+ #
362
+ caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""
363
+ caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""
364
+
365
+ caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFT
366
+ caption = re.sub(r"\s+\.\s+", r" ", caption) # " . "
367
+
368
+ # this-is-my-cute-cat / this_is_my_cute_cat
369
+ regex2 = re.compile(r"(?:\-|\_)")
370
+ if len(re.findall(regex2, caption)) > 3:
371
+ caption = re.sub(regex2, " ", caption)
372
+
373
+ caption = ftfy.fix_text(caption)
374
+ caption = html.unescape(html.unescape(caption))
375
+
376
+ caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
377
+ caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
378
+ caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
379
+
380
+ caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
381
+ caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)
382
+ caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)
383
+ caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption)
384
+ caption = re.sub(r"\bpage\s+\d+\b", "", caption)
385
+
386
+ caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a...
387
+
388
+ caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)
389
+
390
+ caption = re.sub(r"\b\s+\:\s+", r": ", caption)
391
+ caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)
392
+ caption = re.sub(r"\s+", " ", caption)
393
+
394
+ caption.strip()
395
+
396
+ caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
397
+ caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
398
+ caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
399
+ caption = re.sub(r"^\.\S+$", "", caption)
400
+
401
+ return caption.strip()
402
+
403
+ @property
404
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
405
+ def _execution_device(self):
406
+ r"""
407
+ Returns the device on which the pipeline's models will be executed. After calling
408
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
409
+ hooks.
410
+ """
411
+ if not hasattr(self.unet, "_hf_hook"):
412
+ return self.device
413
+ for module in self.unet.modules():
414
+ if (
415
+ hasattr(module, "_hf_hook")
416
+ and hasattr(module._hf_hook, "execution_device")
417
+ and module._hf_hook.execution_device is not None
418
+ ):
419
+ return torch.device(module._hf_hook.execution_device)
420
+ return self.device
421
+
422
+ @torch.no_grad()
423
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline.encode_prompt
424
+ def encode_prompt(
425
+ self,
426
+ prompt,
427
+ do_classifier_free_guidance=True,
428
+ num_images_per_prompt=1,
429
+ device=None,
430
+ negative_prompt=None,
431
+ prompt_embeds: Optional[torch.FloatTensor] = None,
432
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
433
+ clean_caption: bool = False,
434
+ ):
435
+ r"""
436
+ Encodes the prompt into text encoder hidden states.
437
+
438
+ Args:
439
+ prompt (`str` or `List[str]`, *optional*):
440
+ prompt to be encoded
441
+ device: (`torch.device`, *optional*):
442
+ torch device to place the resulting embeddings on
443
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
444
+ number of images that should be generated per prompt
445
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
446
+ whether to use classifier free guidance or not
447
+ negative_prompt (`str` or `List[str]`, *optional*):
448
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
449
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
450
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
451
+ prompt_embeds (`torch.FloatTensor`, *optional*):
452
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
453
+ provided, text embeddings will be generated from `prompt` input argument.
454
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
455
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
456
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
457
+ argument.
458
+ """
459
+ if prompt is not None and negative_prompt is not None:
460
+ if type(prompt) is not type(negative_prompt):
461
+ raise TypeError(
462
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
463
+ f" {type(prompt)}."
464
+ )
465
+
466
+ if device is None:
467
+ device = self._execution_device
468
+
469
+ if prompt is not None and isinstance(prompt, str):
470
+ batch_size = 1
471
+ elif prompt is not None and isinstance(prompt, list):
472
+ batch_size = len(prompt)
473
+ else:
474
+ batch_size = prompt_embeds.shape[0]
475
+
476
+ # while T5 can handle much longer input sequences than 77, the text encoder was trained with a max length of 77 for IF
477
+ max_length = 77
478
+
479
+ if prompt_embeds is None:
480
+ prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)
481
+ text_inputs = self.tokenizer(
482
+ prompt,
483
+ padding="max_length",
484
+ max_length=max_length,
485
+ truncation=True,
486
+ add_special_tokens=True,
487
+ return_tensors="pt",
488
+ )
489
+ text_input_ids = text_inputs.input_ids
490
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
491
+
492
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
493
+ text_input_ids, untruncated_ids
494
+ ):
495
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_length - 1 : -1])
496
+ logger.warning(
497
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
498
+ f" {max_length} tokens: {removed_text}"
499
+ )
500
+
501
+ attention_mask = text_inputs.attention_mask.to(device)
502
+
503
+ prompt_embeds = self.text_encoder(
504
+ text_input_ids.to(device),
505
+ attention_mask=attention_mask,
506
+ )
507
+ prompt_embeds = prompt_embeds[0]
508
+
509
+ if self.text_encoder is not None:
510
+ dtype = self.text_encoder.dtype
511
+ elif self.unet is not None:
512
+ dtype = self.unet.dtype
513
+ else:
514
+ dtype = None
515
+
516
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
517
+
518
+ bs_embed, seq_len, _ = prompt_embeds.shape
519
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
520
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
521
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
522
+
523
+ # get unconditional embeddings for classifier free guidance
524
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
525
+ uncond_tokens: List[str]
526
+ if negative_prompt is None:
527
+ uncond_tokens = [""] * batch_size
528
+ elif isinstance(negative_prompt, str):
529
+ uncond_tokens = [negative_prompt]
530
+ elif batch_size != len(negative_prompt):
531
+ raise ValueError(
532
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
533
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
534
+ " the batch size of `prompt`."
535
+ )
536
+ else:
537
+ uncond_tokens = negative_prompt
538
+
539
+ uncond_tokens = self._text_preprocessing(uncond_tokens, clean_caption=clean_caption)
540
+ max_length = prompt_embeds.shape[1]
541
+ uncond_input = self.tokenizer(
542
+ uncond_tokens,
543
+ padding="max_length",
544
+ max_length=max_length,
545
+ truncation=True,
546
+ return_attention_mask=True,
547
+ add_special_tokens=True,
548
+ return_tensors="pt",
549
+ )
550
+ attention_mask = uncond_input.attention_mask.to(device)
551
+
552
+ negative_prompt_embeds = self.text_encoder(
553
+ uncond_input.input_ids.to(device),
554
+ attention_mask=attention_mask,
555
+ )
556
+ negative_prompt_embeds = negative_prompt_embeds[0]
557
+
558
+ if do_classifier_free_guidance:
559
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
560
+ seq_len = negative_prompt_embeds.shape[1]
561
+
562
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
563
+
564
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
565
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
566
+
567
+ # For classifier free guidance, we need to do two forward passes.
568
+ # Here we concatenate the unconditional and text embeddings into a single batch
569
+ # to avoid doing two forward passes
570
+ else:
571
+ negative_prompt_embeds = None
572
+
573
+ return prompt_embeds, negative_prompt_embeds
574
+
575
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline.run_safety_checker
576
+ def run_safety_checker(self, image, device, dtype):
577
+ if self.safety_checker is not None:
578
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
579
+ image, nsfw_detected, watermark_detected = self.safety_checker(
580
+ images=image,
581
+ clip_input=safety_checker_input.pixel_values.to(dtype=dtype),
582
+ )
583
+ else:
584
+ nsfw_detected = None
585
+ watermark_detected = None
586
+
587
+ if hasattr(self, "unet_offload_hook") and self.unet_offload_hook is not None:
588
+ self.unet_offload_hook.offload()
589
+
590
+ return image, nsfw_detected, watermark_detected
591
+
592
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline.prepare_extra_step_kwargs
593
+ def prepare_extra_step_kwargs(self, generator, eta):
594
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
595
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
596
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
597
+ # and should be between [0, 1]
598
+
599
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
600
+ extra_step_kwargs = {}
601
+ if accepts_eta:
602
+ extra_step_kwargs["eta"] = eta
603
+
604
+ # check if the scheduler accepts generator
605
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
606
+ if accepts_generator:
607
+ extra_step_kwargs["generator"] = generator
608
+ return extra_step_kwargs
609
+
610
+ def check_inputs(
611
+ self,
612
+ prompt,
613
+ image,
614
+ original_image,
615
+ batch_size,
616
+ callback_steps,
617
+ negative_prompt=None,
618
+ prompt_embeds=None,
619
+ negative_prompt_embeds=None,
620
+ ):
621
+ if (callback_steps is None) or (
622
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
623
+ ):
624
+ raise ValueError(
625
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
626
+ f" {type(callback_steps)}."
627
+ )
628
+
629
+ if prompt is not None and prompt_embeds is not None:
630
+ raise ValueError(
631
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
632
+ " only forward one of the two."
633
+ )
634
+ elif prompt is None and prompt_embeds is None:
635
+ raise ValueError(
636
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
637
+ )
638
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
639
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
640
+
641
+ if negative_prompt is not None and negative_prompt_embeds is not None:
642
+ raise ValueError(
643
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
644
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
645
+ )
646
+
647
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
648
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
649
+ raise ValueError(
650
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
651
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
652
+ f" {negative_prompt_embeds.shape}."
653
+ )
654
+
655
+ # image
656
+
657
+ if isinstance(image, list):
658
+ check_image_type = image[0]
659
+ else:
660
+ check_image_type = image
661
+
662
+ if (
663
+ not isinstance(check_image_type, torch.Tensor)
664
+ and not isinstance(check_image_type, PIL.Image.Image)
665
+ and not isinstance(check_image_type, np.ndarray)
666
+ ):
667
+ raise ValueError(
668
+ "`image` has to be of type `torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, or List[...] but is"
669
+ f" {type(check_image_type)}"
670
+ )
671
+
672
+ if isinstance(image, list):
673
+ image_batch_size = len(image)
674
+ elif isinstance(image, torch.Tensor):
675
+ image_batch_size = image.shape[0]
676
+ elif isinstance(image, PIL.Image.Image):
677
+ image_batch_size = 1
678
+ elif isinstance(image, np.ndarray):
679
+ image_batch_size = image.shape[0]
680
+ else:
681
+ assert False
682
+
683
+ if batch_size != image_batch_size:
684
+ raise ValueError(f"image batch size: {image_batch_size} must be same as prompt batch size {batch_size}")
685
+
686
+ # original_image
687
+
688
+ if isinstance(original_image, list):
689
+ check_image_type = original_image[0]
690
+ else:
691
+ check_image_type = original_image
692
+
693
+ if (
694
+ not isinstance(check_image_type, torch.Tensor)
695
+ and not isinstance(check_image_type, PIL.Image.Image)
696
+ and not isinstance(check_image_type, np.ndarray)
697
+ ):
698
+ raise ValueError(
699
+ "`original_image` has to be of type `torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, or List[...] but is"
700
+ f" {type(check_image_type)}"
701
+ )
702
+
703
+ if isinstance(original_image, list):
704
+ image_batch_size = len(original_image)
705
+ elif isinstance(original_image, torch.Tensor):
706
+ image_batch_size = original_image.shape[0]
707
+ elif isinstance(original_image, PIL.Image.Image):
708
+ image_batch_size = 1
709
+ elif isinstance(original_image, np.ndarray):
710
+ image_batch_size = original_image.shape[0]
711
+ else:
712
+ assert False
713
+
714
+ if batch_size != image_batch_size:
715
+ raise ValueError(
716
+ f"original_image batch size: {image_batch_size} must be same as prompt batch size {batch_size}"
717
+ )
718
+
719
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if_img2img.IFImg2ImgPipeline.preprocess_image with preprocess_image -> preprocess_original_image
720
+ def preprocess_original_image(self, image: PIL.Image.Image) -> torch.Tensor:
721
+ if not isinstance(image, list):
722
+ image = [image]
723
+
724
+ def numpy_to_pt(images):
725
+ if images.ndim == 3:
726
+ images = images[..., None]
727
+
728
+ images = torch.from_numpy(images.transpose(0, 3, 1, 2))
729
+ return images
730
+
731
+ if isinstance(image[0], PIL.Image.Image):
732
+ new_image = []
733
+
734
+ for image_ in image:
735
+ image_ = image_.convert("RGB")
736
+ image_ = resize(image_, self.unet.sample_size)
737
+ image_ = np.array(image_)
738
+ image_ = image_.astype(np.float32)
739
+ image_ = image_ / 127.5 - 1
740
+ new_image.append(image_)
741
+
742
+ image = new_image
743
+
744
+ image = np.stack(image, axis=0) # to np
745
+ image = numpy_to_pt(image) # to pt
746
+
747
+ elif isinstance(image[0], np.ndarray):
748
+ image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
749
+ image = numpy_to_pt(image)
750
+
751
+ elif isinstance(image[0], torch.Tensor):
752
+ image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
753
+
754
+ return image
755
+
756
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if_superresolution.IFSuperResolutionPipeline.preprocess_image
757
+ def preprocess_image(self, image: PIL.Image.Image, num_images_per_prompt, device) -> torch.Tensor:
758
+ if not isinstance(image, torch.Tensor) and not isinstance(image, list):
759
+ image = [image]
760
+
761
+ if isinstance(image[0], PIL.Image.Image):
762
+ image = [np.array(i).astype(np.float32) / 255.0 for i in image]
763
+
764
+ image = np.stack(image, axis=0) # to np
765
+ torch.from_numpy(image.transpose(0, 3, 1, 2))
766
+ elif isinstance(image[0], np.ndarray):
767
+ image = np.stack(image, axis=0) # to np
768
+ if image.ndim == 5:
769
+ image = image[0]
770
+
771
+ image = torch.from_numpy(image.transpose(0, 3, 1, 2))
772
+ elif isinstance(image, list) and isinstance(image[0], torch.Tensor):
773
+ dims = image[0].ndim
774
+
775
+ if dims == 3:
776
+ image = torch.stack(image, dim=0)
777
+ elif dims == 4:
778
+ image = torch.concat(image, dim=0)
779
+ else:
780
+ raise ValueError(f"Image must have 3 or 4 dimensions, instead got {dims}")
781
+
782
+ image = image.to(device=device, dtype=self.unet.dtype)
783
+
784
+ image = image.repeat_interleave(num_images_per_prompt, dim=0)
785
+
786
+ return image
787
+
788
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if_img2img.IFImg2ImgPipeline.get_timesteps
789
+ def get_timesteps(self, num_inference_steps, strength):
790
+ # get the original timestep using init_timestep
791
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
792
+
793
+ t_start = max(num_inference_steps - init_timestep, 0)
794
+ timesteps = self.scheduler.timesteps[t_start:]
795
+
796
+ return timesteps, num_inference_steps - t_start
797
+
798
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if_img2img.IFImg2ImgPipeline.prepare_intermediate_images
799
+ def prepare_intermediate_images(
800
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None
801
+ ):
802
+ _, channels, height, width = image.shape
803
+
804
+ batch_size = batch_size * num_images_per_prompt
805
+
806
+ shape = (batch_size, channels, height, width)
807
+
808
+ if isinstance(generator, list) and len(generator) != batch_size:
809
+ raise ValueError(
810
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
811
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
812
+ )
813
+
814
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
815
+
816
+ image = image.repeat_interleave(num_images_per_prompt, dim=0)
817
+ image = self.scheduler.add_noise(image, noise, timestep)
818
+
819
+ return image
820
+
821
+ @torch.no_grad()
822
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
823
+ def __call__(
824
+ self,
825
+ image: Union[PIL.Image.Image, np.ndarray, torch.FloatTensor],
826
+ original_image: Union[
827
+ PIL.Image.Image, torch.Tensor, np.ndarray, List[PIL.Image.Image], List[torch.Tensor], List[np.ndarray]
828
+ ] = None,
829
+ strength: float = 0.8,
830
+ prompt: Union[str, List[str]] = None,
831
+ num_inference_steps: int = 50,
832
+ timesteps: List[int] = None,
833
+ guidance_scale: float = 4.0,
834
+ negative_prompt: Optional[Union[str, List[str]]] = None,
835
+ num_images_per_prompt: Optional[int] = 1,
836
+ eta: float = 0.0,
837
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
838
+ prompt_embeds: Optional[torch.FloatTensor] = None,
839
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
840
+ output_type: Optional[str] = "pil",
841
+ return_dict: bool = True,
842
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
843
+ callback_steps: int = 1,
844
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
845
+ noise_level: int = 250,
846
+ clean_caption: bool = True,
847
+ ):
848
+ """
849
+ Function invoked when calling the pipeline for generation.
850
+
851
+ Args:
852
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
853
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
854
+ process.
855
+ original_image (`torch.FloatTensor` or `PIL.Image.Image`):
856
+ The original image that `image` was varied from.
857
+ strength (`float`, *optional*, defaults to 0.8):
858
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
859
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
860
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
861
+ be maximum and the denoising process will run for the full number of iterations specified in
862
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
863
+ prompt (`str` or `List[str]`, *optional*):
864
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
865
+ instead.
866
+ num_inference_steps (`int`, *optional*, defaults to 50):
867
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
868
+ expense of slower inference.
869
+ timesteps (`List[int]`, *optional*):
870
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
871
+ timesteps are used. Must be in descending order.
872
+ guidance_scale (`float`, *optional*, defaults to 7.5):
873
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
874
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
875
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
876
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
877
+ usually at the expense of lower image quality.
878
+ negative_prompt (`str` or `List[str]`, *optional*):
879
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
880
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
881
+ less than `1`).
882
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
883
+ The number of images to generate per prompt.
884
+ eta (`float`, *optional*, defaults to 0.0):
885
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
886
+ [`schedulers.DDIMScheduler`], will be ignored for others.
887
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
888
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
889
+ to make generation deterministic.
890
+ prompt_embeds (`torch.FloatTensor`, *optional*):
891
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
892
+ provided, text embeddings will be generated from `prompt` input argument.
893
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
894
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
895
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
896
+ argument.
897
+ output_type (`str`, *optional*, defaults to `"pil"`):
898
+ The output format of the generate image. Choose between
899
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
900
+ return_dict (`bool`, *optional*, defaults to `True`):
901
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
902
+ callback (`Callable`, *optional*):
903
+ A function that will be called every `callback_steps` steps during inference. The function will be
904
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
905
+ callback_steps (`int`, *optional*, defaults to 1):
906
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
907
+ called at every step.
908
+ cross_attention_kwargs (`dict`, *optional*):
909
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
910
+ `self.processor` in
911
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
912
+ noise_level (`int`, *optional*, defaults to 250):
913
+ The amount of noise to add to the upscaled image. Must be in the range `[0, 1000)`
914
+ clean_caption (`bool`, *optional*, defaults to `True`):
915
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
916
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
917
+ prompt.
918
+
919
+ Examples:
920
+
921
+ Returns:
922
+ [`~pipelines.stable_diffusion.IFPipelineOutput`] or `tuple`:
923
+ [`~pipelines.stable_diffusion.IFPipelineOutput`] if `return_dict` is True, otherwise a `tuple. When
924
+ returning a tuple, the first element is a list with the generated images, and the second element is a list
925
+ of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw)
926
+ or watermarked content, according to the `safety_checker`.
927
+ """
928
+ # 1. Check inputs. Raise error if not correct
929
+ if prompt is not None and isinstance(prompt, str):
930
+ batch_size = 1
931
+ elif prompt is not None and isinstance(prompt, list):
932
+ batch_size = len(prompt)
933
+ else:
934
+ batch_size = prompt_embeds.shape[0]
935
+
936
+ self.check_inputs(
937
+ prompt,
938
+ image,
939
+ original_image,
940
+ batch_size,
941
+ callback_steps,
942
+ negative_prompt,
943
+ prompt_embeds,
944
+ negative_prompt_embeds,
945
+ )
946
+
947
+ # 2. Define call parameters
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
+ do_classifier_free_guidance = guidance_scale > 1.0
953
+
954
+ device = self._execution_device
955
+
956
+ # 3. Encode input prompt
957
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
958
+ prompt,
959
+ do_classifier_free_guidance,
960
+ num_images_per_prompt=num_images_per_prompt,
961
+ device=device,
962
+ negative_prompt=negative_prompt,
963
+ prompt_embeds=prompt_embeds,
964
+ negative_prompt_embeds=negative_prompt_embeds,
965
+ clean_caption=clean_caption,
966
+ )
967
+
968
+ if do_classifier_free_guidance:
969
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
970
+
971
+ dtype = prompt_embeds.dtype
972
+
973
+ # 4. Prepare timesteps
974
+ if timesteps is not None:
975
+ self.scheduler.set_timesteps(timesteps=timesteps, device=device)
976
+ timesteps = self.scheduler.timesteps
977
+ num_inference_steps = len(timesteps)
978
+ else:
979
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
980
+ timesteps = self.scheduler.timesteps
981
+
982
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength)
983
+
984
+ # 5. prepare original image
985
+ original_image = self.preprocess_original_image(original_image)
986
+ original_image = original_image.to(device=device, dtype=dtype)
987
+
988
+ # 6. Prepare intermediate images
989
+ noise_timestep = timesteps[0:1]
990
+ noise_timestep = noise_timestep.repeat(batch_size * num_images_per_prompt)
991
+
992
+ intermediate_images = self.prepare_intermediate_images(
993
+ original_image,
994
+ noise_timestep,
995
+ batch_size,
996
+ num_images_per_prompt,
997
+ dtype,
998
+ device,
999
+ generator,
1000
+ )
1001
+
1002
+ # 7. Prepare upscaled image and noise level
1003
+ _, _, height, width = original_image.shape
1004
+
1005
+ image = self.preprocess_image(image, num_images_per_prompt, device)
1006
+
1007
+ upscaled = F.interpolate(image, (height, width), mode="bilinear", align_corners=True)
1008
+
1009
+ noise_level = torch.tensor([noise_level] * upscaled.shape[0], device=upscaled.device)
1010
+ noise = randn_tensor(upscaled.shape, generator=generator, device=upscaled.device, dtype=upscaled.dtype)
1011
+ upscaled = self.image_noising_scheduler.add_noise(upscaled, noise, timesteps=noise_level)
1012
+
1013
+ if do_classifier_free_guidance:
1014
+ noise_level = torch.cat([noise_level] * 2)
1015
+
1016
+ # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1017
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1018
+
1019
+ # HACK: see comment in `enable_model_cpu_offload`
1020
+ if hasattr(self, "text_encoder_offload_hook") and self.text_encoder_offload_hook is not None:
1021
+ self.text_encoder_offload_hook.offload()
1022
+
1023
+ # 9. Denoising loop
1024
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1025
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1026
+ for i, t in enumerate(timesteps):
1027
+ model_input = torch.cat([intermediate_images, upscaled], dim=1)
1028
+
1029
+ model_input = torch.cat([model_input] * 2) if do_classifier_free_guidance else model_input
1030
+ model_input = self.scheduler.scale_model_input(model_input, t)
1031
+
1032
+ # predict the noise residual
1033
+ noise_pred = self.unet(
1034
+ model_input,
1035
+ t,
1036
+ encoder_hidden_states=prompt_embeds,
1037
+ class_labels=noise_level,
1038
+ cross_attention_kwargs=cross_attention_kwargs,
1039
+ ).sample
1040
+
1041
+ # perform guidance
1042
+ if do_classifier_free_guidance:
1043
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1044
+ noise_pred_uncond, _ = noise_pred_uncond.split(model_input.shape[1] // 2, dim=1)
1045
+ noise_pred_text, predicted_variance = noise_pred_text.split(model_input.shape[1] // 2, dim=1)
1046
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1047
+ noise_pred = torch.cat([noise_pred, predicted_variance], dim=1)
1048
+
1049
+ # compute the previous noisy sample x_t -> x_t-1
1050
+ intermediate_images = self.scheduler.step(
1051
+ noise_pred, t, intermediate_images, **extra_step_kwargs
1052
+ ).prev_sample
1053
+
1054
+ # call the callback, if provided
1055
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1056
+ progress_bar.update()
1057
+ if callback is not None and i % callback_steps == 0:
1058
+ callback(i, t, intermediate_images)
1059
+
1060
+ image = intermediate_images
1061
+
1062
+ if output_type == "pil":
1063
+ # 10. Post-processing
1064
+ image = (image / 2 + 0.5).clamp(0, 1)
1065
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
1066
+
1067
+ # 11. Run safety checker
1068
+ image, nsfw_detected, watermark_detected = self.run_safety_checker(image, device, prompt_embeds.dtype)
1069
+
1070
+ # 12. Convert to PIL
1071
+ image = self.numpy_to_pil(image)
1072
+
1073
+ # 13. Apply watermark
1074
+ if self.watermarker is not None:
1075
+ self.watermarker.apply_watermark(image, self.unet.config.sample_size)
1076
+ elif output_type == "pt":
1077
+ nsfw_detected = None
1078
+ watermark_detected = None
1079
+
1080
+ if hasattr(self, "unet_offload_hook") and self.unet_offload_hook is not None:
1081
+ self.unet_offload_hook.offload()
1082
+ else:
1083
+ # 10. Post-processing
1084
+ image = (image / 2 + 0.5).clamp(0, 1)
1085
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
1086
+
1087
+ # 11. Run safety checker
1088
+ image, nsfw_detected, watermark_detected = self.run_safety_checker(image, device, prompt_embeds.dtype)
1089
+
1090
+ # Offload last model to CPU
1091
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1092
+ self.final_offload_hook.offload()
1093
+
1094
+ if not return_dict:
1095
+ return (image, nsfw_detected, watermark_detected)
1096
+
1097
+ return IFPipelineOutput(images=image, nsfw_detected=nsfw_detected, watermark_detected=watermark_detected)