diffusers 0.17.1__py3-none-any.whl → 0.18.2__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diffusers/__init__.py +26 -1
- diffusers/configuration_utils.py +34 -29
- diffusers/dependency_versions_table.py +4 -0
- diffusers/image_processor.py +125 -12
- diffusers/loaders.py +169 -203
- diffusers/models/attention.py +24 -1
- diffusers/models/attention_flax.py +10 -5
- diffusers/models/attention_processor.py +3 -0
- diffusers/models/autoencoder_kl.py +114 -33
- diffusers/models/controlnet.py +131 -14
- diffusers/models/controlnet_flax.py +37 -26
- diffusers/models/cross_attention.py +17 -17
- diffusers/models/embeddings.py +67 -0
- diffusers/models/modeling_flax_utils.py +64 -56
- diffusers/models/modeling_utils.py +193 -104
- diffusers/models/prior_transformer.py +207 -37
- diffusers/models/resnet.py +26 -26
- diffusers/models/transformer_2d.py +36 -41
- diffusers/models/transformer_temporal.py +24 -21
- diffusers/models/unet_1d.py +31 -25
- diffusers/models/unet_2d.py +43 -30
- diffusers/models/unet_2d_blocks.py +210 -89
- diffusers/models/unet_2d_blocks_flax.py +12 -12
- diffusers/models/unet_2d_condition.py +172 -64
- diffusers/models/unet_2d_condition_flax.py +38 -24
- diffusers/models/unet_3d_blocks.py +34 -31
- diffusers/models/unet_3d_condition.py +101 -34
- diffusers/models/vae.py +5 -5
- diffusers/models/vae_flax.py +37 -34
- diffusers/models/vq_model.py +23 -14
- diffusers/pipelines/__init__.py +24 -1
- diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +1 -1
- diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +5 -3
- diffusers/pipelines/consistency_models/__init__.py +1 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +337 -0
- diffusers/pipelines/controlnet/multicontrolnet.py +120 -1
- diffusers/pipelines/controlnet/pipeline_controlnet.py +59 -17
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +60 -15
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +60 -17
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +1 -1
- diffusers/pipelines/kandinsky/__init__.py +1 -1
- diffusers/pipelines/kandinsky/pipeline_kandinsky.py +4 -6
- diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +1 -0
- diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +1 -0
- diffusers/pipelines/kandinsky2_2/__init__.py +7 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +317 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +372 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +434 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +398 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +531 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +541 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +605 -0
- diffusers/pipelines/pipeline_flax_utils.py +2 -2
- diffusers/pipelines/pipeline_utils.py +124 -146
- diffusers/pipelines/shap_e/__init__.py +27 -0
- diffusers/pipelines/shap_e/camera.py +147 -0
- diffusers/pipelines/shap_e/pipeline_shap_e.py +390 -0
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +349 -0
- diffusers/pipelines/shap_e/renderer.py +709 -0
- diffusers/pipelines/stable_diffusion/__init__.py +2 -0
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +261 -66
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +3 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +5 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +4 -2
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +719 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +832 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +17 -7
- diffusers/pipelines/stable_diffusion_xl/__init__.py +26 -0
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +823 -0
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +896 -0
- diffusers/pipelines/stable_diffusion_xl/watermark.py +31 -0
- diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -1
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +5 -1
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +771 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +92 -6
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
- diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +209 -91
- diffusers/schedulers/__init__.py +3 -0
- diffusers/schedulers/scheduling_consistency_models.py +380 -0
- diffusers/schedulers/scheduling_ddim.py +28 -6
- diffusers/schedulers/scheduling_ddim_inverse.py +19 -4
- diffusers/schedulers/scheduling_ddim_parallel.py +642 -0
- diffusers/schedulers/scheduling_ddpm.py +53 -7
- diffusers/schedulers/scheduling_ddpm_parallel.py +604 -0
- diffusers/schedulers/scheduling_deis_multistep.py +66 -11
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +55 -13
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +19 -4
- diffusers/schedulers/scheduling_dpmsolver_sde.py +73 -11
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +23 -7
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +58 -9
- diffusers/schedulers/scheduling_euler_discrete.py +58 -8
- diffusers/schedulers/scheduling_heun_discrete.py +89 -14
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +73 -11
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +73 -11
- diffusers/schedulers/scheduling_lms_discrete.py +57 -8
- diffusers/schedulers/scheduling_pndm.py +46 -10
- diffusers/schedulers/scheduling_repaint.py +19 -4
- diffusers/schedulers/scheduling_sde_ve.py +5 -1
- diffusers/schedulers/scheduling_unclip.py +43 -4
- diffusers/schedulers/scheduling_unipc_multistep.py +48 -7
- diffusers/training_utils.py +1 -1
- diffusers/utils/__init__.py +2 -1
- diffusers/utils/dummy_pt_objects.py +60 -0
- diffusers/utils/dummy_torch_and_transformers_and_invisible_watermark_objects.py +32 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +180 -0
- diffusers/utils/hub_utils.py +1 -1
- diffusers/utils/import_utils.py +20 -3
- diffusers/utils/logging.py +15 -18
- diffusers/utils/outputs.py +3 -3
- diffusers/utils/testing_utils.py +15 -0
- {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/METADATA +4 -2
- {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/RECORD +120 -94
- {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/WHEEL +1 -1
- {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/LICENSE +0 -0
- {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/entry_points.txt +0 -0
- {diffusers-0.17.1.dist-info → diffusers-0.18.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,398 @@
|
|
1
|
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
from typing import List, Optional, Union
|
16
|
+
|
17
|
+
import numpy as np
|
18
|
+
import PIL
|
19
|
+
import torch
|
20
|
+
from PIL import Image
|
21
|
+
|
22
|
+
from ...models import UNet2DConditionModel, VQModel
|
23
|
+
from ...pipelines import DiffusionPipeline
|
24
|
+
from ...pipelines.pipeline_utils import ImagePipelineOutput
|
25
|
+
from ...schedulers import DDPMScheduler
|
26
|
+
from ...utils import (
|
27
|
+
is_accelerate_available,
|
28
|
+
is_accelerate_version,
|
29
|
+
logging,
|
30
|
+
randn_tensor,
|
31
|
+
replace_example_docstring,
|
32
|
+
)
|
33
|
+
|
34
|
+
|
35
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
36
|
+
|
37
|
+
EXAMPLE_DOC_STRING = """
|
38
|
+
Examples:
|
39
|
+
```py
|
40
|
+
>>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline
|
41
|
+
>>> from diffusers.utils import load_image
|
42
|
+
>>> import torch
|
43
|
+
|
44
|
+
>>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
|
45
|
+
... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
|
46
|
+
... )
|
47
|
+
>>> pipe_prior.to("cuda")
|
48
|
+
|
49
|
+
>>> prompt = "A red cartoon frog, 4k"
|
50
|
+
>>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)
|
51
|
+
|
52
|
+
>>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(
|
53
|
+
... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
|
54
|
+
... )
|
55
|
+
>>> pipe.to("cuda")
|
56
|
+
|
57
|
+
>>> init_image = load_image(
|
58
|
+
... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
|
59
|
+
... "/kandinsky/frog.png"
|
60
|
+
... )
|
61
|
+
|
62
|
+
>>> image = pipe(
|
63
|
+
... image=init_image,
|
64
|
+
... image_embeds=image_emb,
|
65
|
+
... negative_image_embeds=zero_image_emb,
|
66
|
+
... height=768,
|
67
|
+
... width=768,
|
68
|
+
... num_inference_steps=100,
|
69
|
+
... strength=0.2,
|
70
|
+
... ).images
|
71
|
+
|
72
|
+
>>> image[0].save("red_frog.png")
|
73
|
+
```
|
74
|
+
"""
|
75
|
+
|
76
|
+
|
77
|
+
# Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2.downscale_height_and_width
|
78
|
+
def downscale_height_and_width(height, width, scale_factor=8):
|
79
|
+
new_height = height // scale_factor**2
|
80
|
+
if height % scale_factor**2 != 0:
|
81
|
+
new_height += 1
|
82
|
+
new_width = width // scale_factor**2
|
83
|
+
if width % scale_factor**2 != 0:
|
84
|
+
new_width += 1
|
85
|
+
return new_height * scale_factor, new_width * scale_factor
|
86
|
+
|
87
|
+
|
88
|
+
# Copied from diffusers.pipelines.kandinsky.pipeline_kandinsky_img2img.prepare_image
|
89
|
+
def prepare_image(pil_image, w=512, h=512):
|
90
|
+
pil_image = pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1)
|
91
|
+
arr = np.array(pil_image.convert("RGB"))
|
92
|
+
arr = arr.astype(np.float32) / 127.5 - 1
|
93
|
+
arr = np.transpose(arr, [2, 0, 1])
|
94
|
+
image = torch.from_numpy(arr).unsqueeze(0)
|
95
|
+
return image
|
96
|
+
|
97
|
+
|
98
|
+
class KandinskyV22Img2ImgPipeline(DiffusionPipeline):
|
99
|
+
"""
|
100
|
+
Pipeline for image-to-image generation using Kandinsky
|
101
|
+
|
102
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
103
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
104
|
+
|
105
|
+
Args:
|
106
|
+
scheduler ([`DDIMScheduler`]):
|
107
|
+
A scheduler to be used in combination with `unet` to generate image latents.
|
108
|
+
unet ([`UNet2DConditionModel`]):
|
109
|
+
Conditional U-Net architecture to denoise the image embedding.
|
110
|
+
movq ([`VQModel`]):
|
111
|
+
MoVQ Decoder to generate the image from the latents.
|
112
|
+
"""
|
113
|
+
|
114
|
+
def __init__(
|
115
|
+
self,
|
116
|
+
unet: UNet2DConditionModel,
|
117
|
+
scheduler: DDPMScheduler,
|
118
|
+
movq: VQModel,
|
119
|
+
):
|
120
|
+
super().__init__()
|
121
|
+
|
122
|
+
self.register_modules(
|
123
|
+
unet=unet,
|
124
|
+
scheduler=scheduler,
|
125
|
+
movq=movq,
|
126
|
+
)
|
127
|
+
self.movq_scale_factor = 2 ** (len(self.movq.config.block_out_channels) - 1)
|
128
|
+
|
129
|
+
# Copied from diffusers.pipelines.kandinsky.pipeline_kandinsky_img2img.KandinskyImg2ImgPipeline.get_timesteps
|
130
|
+
def get_timesteps(self, num_inference_steps, strength, device):
|
131
|
+
# get the original timestep using init_timestep
|
132
|
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
133
|
+
|
134
|
+
t_start = max(num_inference_steps - init_timestep, 0)
|
135
|
+
timesteps = self.scheduler.timesteps[t_start:]
|
136
|
+
|
137
|
+
return timesteps, num_inference_steps - t_start
|
138
|
+
|
139
|
+
def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
|
140
|
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
141
|
+
raise ValueError(
|
142
|
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
143
|
+
)
|
144
|
+
|
145
|
+
image = image.to(device=device, dtype=dtype)
|
146
|
+
|
147
|
+
batch_size = batch_size * num_images_per_prompt
|
148
|
+
|
149
|
+
if image.shape[1] == 4:
|
150
|
+
init_latents = image
|
151
|
+
|
152
|
+
else:
|
153
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
154
|
+
raise ValueError(
|
155
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
156
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
157
|
+
)
|
158
|
+
|
159
|
+
elif isinstance(generator, list):
|
160
|
+
init_latents = [
|
161
|
+
self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
|
162
|
+
]
|
163
|
+
init_latents = torch.cat(init_latents, dim=0)
|
164
|
+
else:
|
165
|
+
init_latents = self.movq.encode(image).latent_dist.sample(generator)
|
166
|
+
|
167
|
+
init_latents = self.movq.config.scaling_factor * init_latents
|
168
|
+
|
169
|
+
init_latents = torch.cat([init_latents], dim=0)
|
170
|
+
|
171
|
+
shape = init_latents.shape
|
172
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
173
|
+
|
174
|
+
# get latents
|
175
|
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
176
|
+
|
177
|
+
latents = init_latents
|
178
|
+
|
179
|
+
return latents
|
180
|
+
|
181
|
+
# Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2.KandinskyV22Pipeline.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.unet,
|
197
|
+
self.movq,
|
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
|
+
# Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2.KandinskyV22Pipeline.enable_model_cpu_offload
|
204
|
+
def enable_model_cpu_offload(self, gpu_id=0):
|
205
|
+
r"""
|
206
|
+
Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
|
207
|
+
to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
|
208
|
+
method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
|
209
|
+
`enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
|
210
|
+
"""
|
211
|
+
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
|
212
|
+
from accelerate import cpu_offload_with_hook
|
213
|
+
else:
|
214
|
+
raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
|
215
|
+
|
216
|
+
device = torch.device(f"cuda:{gpu_id}")
|
217
|
+
|
218
|
+
if self.device.type != "cpu":
|
219
|
+
self.to("cpu", silence_dtype_warnings=True)
|
220
|
+
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
|
221
|
+
|
222
|
+
hook = None
|
223
|
+
for cpu_offloaded_model in [self.unet, self.movq]:
|
224
|
+
_, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
|
225
|
+
|
226
|
+
# We'll offload the last model manually.
|
227
|
+
self.final_offload_hook = hook
|
228
|
+
|
229
|
+
@property
|
230
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
|
231
|
+
def _execution_device(self):
|
232
|
+
r"""
|
233
|
+
Returns the device on which the pipeline's models will be executed. After calling
|
234
|
+
`pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
|
235
|
+
hooks.
|
236
|
+
"""
|
237
|
+
if not hasattr(self.unet, "_hf_hook"):
|
238
|
+
return self.device
|
239
|
+
for module in self.unet.modules():
|
240
|
+
if (
|
241
|
+
hasattr(module, "_hf_hook")
|
242
|
+
and hasattr(module._hf_hook, "execution_device")
|
243
|
+
and module._hf_hook.execution_device is not None
|
244
|
+
):
|
245
|
+
return torch.device(module._hf_hook.execution_device)
|
246
|
+
return self.device
|
247
|
+
|
248
|
+
@torch.no_grad()
|
249
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
250
|
+
def __call__(
|
251
|
+
self,
|
252
|
+
image_embeds: Union[torch.FloatTensor, List[torch.FloatTensor]],
|
253
|
+
image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]],
|
254
|
+
negative_image_embeds: Union[torch.FloatTensor, List[torch.FloatTensor]],
|
255
|
+
height: int = 512,
|
256
|
+
width: int = 512,
|
257
|
+
num_inference_steps: int = 100,
|
258
|
+
guidance_scale: float = 4.0,
|
259
|
+
strength: float = 0.3,
|
260
|
+
num_images_per_prompt: int = 1,
|
261
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
262
|
+
output_type: Optional[str] = "pil",
|
263
|
+
return_dict: bool = True,
|
264
|
+
):
|
265
|
+
"""
|
266
|
+
Function invoked when calling the pipeline for generation.
|
267
|
+
|
268
|
+
Args:
|
269
|
+
image_embeds (`torch.FloatTensor` or `List[torch.FloatTensor]`):
|
270
|
+
The clip image embeddings for text prompt, that will be used to condition the image generation.
|
271
|
+
image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
272
|
+
`Image`, or tensor representing an image batch, that will be used as the starting point for the
|
273
|
+
process. Can also accpet image latents as `image`, if passing latents directly, it will not be encoded
|
274
|
+
again.
|
275
|
+
strength (`float`, *optional*, defaults to 0.8):
|
276
|
+
Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
|
277
|
+
will be used as a starting point, adding more noise to it the larger the `strength`. The number of
|
278
|
+
denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
|
279
|
+
be maximum and the denoising process will run for the full number of iterations specified in
|
280
|
+
`num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
|
281
|
+
negative_image_embeds (`torch.FloatTensor` or `List[torch.FloatTensor]`):
|
282
|
+
The clip image embeddings for negative text prompt, will be used to condition the image generation.
|
283
|
+
height (`int`, *optional*, defaults to 512):
|
284
|
+
The height in pixels of the generated image.
|
285
|
+
width (`int`, *optional*, defaults to 512):
|
286
|
+
The width in pixels of the generated image.
|
287
|
+
num_inference_steps (`int`, *optional*, defaults to 100):
|
288
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
289
|
+
expense of slower inference.
|
290
|
+
guidance_scale (`float`, *optional*, defaults to 4.0):
|
291
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
292
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
293
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
294
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
295
|
+
usually at the expense of lower image quality.
|
296
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
297
|
+
The number of images to generate per prompt.
|
298
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
299
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
300
|
+
to make generation deterministic.
|
301
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
302
|
+
The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"`
|
303
|
+
(`np.array`) or `"pt"` (`torch.Tensor`).
|
304
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
305
|
+
Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
|
306
|
+
|
307
|
+
Examples:
|
308
|
+
|
309
|
+
Returns:
|
310
|
+
[`~pipelines.ImagePipelineOutput`] or `tuple`
|
311
|
+
"""
|
312
|
+
device = self._execution_device
|
313
|
+
|
314
|
+
do_classifier_free_guidance = guidance_scale > 1.0
|
315
|
+
|
316
|
+
if isinstance(image_embeds, list):
|
317
|
+
image_embeds = torch.cat(image_embeds, dim=0)
|
318
|
+
batch_size = image_embeds.shape[0]
|
319
|
+
if isinstance(negative_image_embeds, list):
|
320
|
+
negative_image_embeds = torch.cat(negative_image_embeds, dim=0)
|
321
|
+
|
322
|
+
if do_classifier_free_guidance:
|
323
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
324
|
+
negative_image_embeds = negative_image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
325
|
+
|
326
|
+
image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0).to(dtype=self.unet.dtype, device=device)
|
327
|
+
|
328
|
+
if not isinstance(image, list):
|
329
|
+
image = [image]
|
330
|
+
if not all(isinstance(i, (PIL.Image.Image, torch.Tensor)) for i in image):
|
331
|
+
raise ValueError(
|
332
|
+
f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support PIL image and pytorch tensor"
|
333
|
+
)
|
334
|
+
|
335
|
+
image = torch.cat([prepare_image(i, width, height) for i in image], dim=0)
|
336
|
+
image = image.to(dtype=image_embeds.dtype, device=device)
|
337
|
+
|
338
|
+
latents = self.movq.encode(image)["latents"]
|
339
|
+
latents = latents.repeat_interleave(num_images_per_prompt, dim=0)
|
340
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
341
|
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
342
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
343
|
+
height, width = downscale_height_and_width(height, width, self.movq_scale_factor)
|
344
|
+
latents = self.prepare_latents(
|
345
|
+
latents, latent_timestep, batch_size, num_images_per_prompt, image_embeds.dtype, device, generator
|
346
|
+
)
|
347
|
+
for i, t in enumerate(self.progress_bar(timesteps)):
|
348
|
+
# expand the latents if we are doing classifier free guidance
|
349
|
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
350
|
+
|
351
|
+
added_cond_kwargs = {"image_embeds": image_embeds}
|
352
|
+
noise_pred = self.unet(
|
353
|
+
sample=latent_model_input,
|
354
|
+
timestep=t,
|
355
|
+
encoder_hidden_states=None,
|
356
|
+
added_cond_kwargs=added_cond_kwargs,
|
357
|
+
return_dict=False,
|
358
|
+
)[0]
|
359
|
+
|
360
|
+
if do_classifier_free_guidance:
|
361
|
+
noise_pred, variance_pred = noise_pred.split(latents.shape[1], dim=1)
|
362
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
363
|
+
_, variance_pred_text = variance_pred.chunk(2)
|
364
|
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
365
|
+
noise_pred = torch.cat([noise_pred, variance_pred_text], dim=1)
|
366
|
+
|
367
|
+
if not (
|
368
|
+
hasattr(self.scheduler.config, "variance_type")
|
369
|
+
and self.scheduler.config.variance_type in ["learned", "learned_range"]
|
370
|
+
):
|
371
|
+
noise_pred, _ = noise_pred.split(latents.shape[1], dim=1)
|
372
|
+
|
373
|
+
# compute the previous noisy sample x_t -> x_t-1
|
374
|
+
latents = self.scheduler.step(
|
375
|
+
noise_pred,
|
376
|
+
t,
|
377
|
+
latents,
|
378
|
+
generator=generator,
|
379
|
+
)[0]
|
380
|
+
|
381
|
+
# post-processing
|
382
|
+
image = self.movq.decode(latents, force_not_quantize=True)["sample"]
|
383
|
+
|
384
|
+
if output_type not in ["pt", "np", "pil"]:
|
385
|
+
raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}")
|
386
|
+
|
387
|
+
if output_type in ["np", "pil"]:
|
388
|
+
image = image * 0.5 + 0.5
|
389
|
+
image = image.clamp(0, 1)
|
390
|
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
391
|
+
|
392
|
+
if output_type == "pil":
|
393
|
+
image = self.numpy_to_pil(image)
|
394
|
+
|
395
|
+
if not return_dict:
|
396
|
+
return (image,)
|
397
|
+
|
398
|
+
return ImagePipelineOutput(images=image)
|