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