diffusers 0.29.2__py3-none-any.whl → 0.30.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffusers/__init__.py +94 -3
- diffusers/commands/env.py +1 -5
- diffusers/configuration_utils.py +4 -9
- diffusers/dependency_versions_table.py +2 -2
- diffusers/image_processor.py +1 -2
- diffusers/loaders/__init__.py +17 -2
- diffusers/loaders/ip_adapter.py +10 -7
- diffusers/loaders/lora_base.py +752 -0
- diffusers/loaders/lora_pipeline.py +2222 -0
- diffusers/loaders/peft.py +213 -5
- diffusers/loaders/single_file.py +1 -12
- diffusers/loaders/single_file_model.py +31 -10
- diffusers/loaders/single_file_utils.py +262 -2
- diffusers/loaders/textual_inversion.py +1 -6
- diffusers/loaders/unet.py +23 -208
- diffusers/models/__init__.py +20 -0
- diffusers/models/activations.py +22 -0
- diffusers/models/attention.py +386 -7
- diffusers/models/attention_processor.py +1795 -629
- diffusers/models/autoencoders/__init__.py +2 -0
- diffusers/models/autoencoders/autoencoder_kl.py +14 -3
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1035 -0
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
- diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
- diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
- diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
- diffusers/models/autoencoders/vq_model.py +4 -4
- diffusers/models/controlnet.py +2 -3
- diffusers/models/controlnet_hunyuan.py +401 -0
- diffusers/models/controlnet_sd3.py +11 -11
- diffusers/models/controlnet_sparsectrl.py +789 -0
- diffusers/models/controlnet_xs.py +40 -10
- diffusers/models/downsampling.py +68 -0
- diffusers/models/embeddings.py +319 -36
- diffusers/models/model_loading_utils.py +1 -3
- diffusers/models/modeling_flax_utils.py +1 -6
- diffusers/models/modeling_utils.py +4 -16
- diffusers/models/normalization.py +203 -12
- diffusers/models/transformers/__init__.py +6 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +527 -0
- diffusers/models/transformers/cogvideox_transformer_3d.py +345 -0
- diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
- diffusers/models/transformers/latte_transformer_3d.py +327 -0
- diffusers/models/transformers/lumina_nextdit2d.py +340 -0
- diffusers/models/transformers/pixart_transformer_2d.py +102 -1
- diffusers/models/transformers/prior_transformer.py +1 -1
- diffusers/models/transformers/stable_audio_transformer.py +458 -0
- diffusers/models/transformers/transformer_flux.py +455 -0
- diffusers/models/transformers/transformer_sd3.py +18 -4
- diffusers/models/unets/unet_1d_blocks.py +1 -1
- diffusers/models/unets/unet_2d_condition.py +8 -1
- diffusers/models/unets/unet_3d_blocks.py +51 -920
- diffusers/models/unets/unet_3d_condition.py +4 -1
- diffusers/models/unets/unet_i2vgen_xl.py +4 -1
- diffusers/models/unets/unet_kandinsky3.py +1 -1
- diffusers/models/unets/unet_motion_model.py +1330 -84
- diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
- diffusers/models/unets/unet_stable_cascade.py +1 -3
- diffusers/models/unets/uvit_2d.py +1 -1
- diffusers/models/upsampling.py +64 -0
- diffusers/models/vq_model.py +8 -4
- diffusers/optimization.py +1 -1
- diffusers/pipelines/__init__.py +100 -3
- diffusers/pipelines/animatediff/__init__.py +4 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
- diffusers/pipelines/aura_flow/__init__.py +48 -0
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
- diffusers/pipelines/auto_pipeline.py +97 -19
- diffusers/pipelines/cogvideo/__init__.py +48 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +687 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
- diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
- diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
- diffusers/pipelines/flux/__init__.py +47 -0
- diffusers/pipelines/flux/pipeline_flux.py +749 -0
- diffusers/pipelines/flux/pipeline_output.py +21 -0
- diffusers/pipelines/free_init_utils.py +2 -0
- diffusers/pipelines/free_noise_utils.py +236 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
- diffusers/pipelines/kolors/__init__.py +54 -0
- diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
- diffusers/pipelines/kolors/pipeline_output.py +21 -0
- diffusers/pipelines/kolors/text_encoder.py +889 -0
- diffusers/pipelines/kolors/tokenizer.py +334 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
- diffusers/pipelines/latte/__init__.py +48 -0
- diffusers/pipelines/latte/pipeline_latte.py +881 -0
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
- diffusers/pipelines/lumina/__init__.py +48 -0
- diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
- diffusers/pipelines/pag/__init__.py +67 -0
- diffusers/pipelines/pag/pag_utils.py +237 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
- diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
- diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
- diffusers/pipelines/pia/pipeline_pia.py +30 -37
- diffusers/pipelines/pipeline_flax_utils.py +4 -9
- diffusers/pipelines/pipeline_loading_utils.py +0 -3
- diffusers/pipelines/pipeline_utils.py +2 -14
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
- diffusers/pipelines/stable_audio/__init__.py +50 -0
- diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
- diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
- diffusers/schedulers/__init__.py +8 -0
- diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
- diffusers/schedulers/scheduling_ddim.py +1 -1
- diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
- diffusers/schedulers/scheduling_ddpm.py +1 -1
- diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
- diffusers/schedulers/scheduling_deis_multistep.py +2 -2
- diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
- diffusers/schedulers/scheduling_ipndm.py +1 -1
- diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
- diffusers/schedulers/scheduling_utils.py +1 -3
- diffusers/schedulers/scheduling_utils_flax.py +1 -3
- diffusers/training_utils.py +99 -14
- diffusers/utils/__init__.py +2 -2
- diffusers/utils/dummy_pt_objects.py +210 -0
- diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
- diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
- diffusers/utils/dynamic_modules_utils.py +1 -11
- diffusers/utils/export_utils.py +1 -4
- diffusers/utils/hub_utils.py +45 -42
- diffusers/utils/import_utils.py +19 -16
- diffusers/utils/loading_utils.py +76 -3
- diffusers/utils/testing_utils.py +11 -8
- {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/METADATA +73 -83
- {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/RECORD +217 -164
- {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/WHEEL +1 -1
- diffusers/loaders/autoencoder.py +0 -146
- diffusers/loaders/controlnet.py +0 -136
- diffusers/loaders/lora.py +0 -1728
- {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/LICENSE +0 -0
- {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/entry_points.txt +0 -0
- {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1201 @@
|
|
1
|
+
# Copyright 2024 Stability AI and The HuggingFace Team. All rights reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
import inspect
|
16
|
+
from typing import Callable, Dict, List, Optional, Union
|
17
|
+
|
18
|
+
import torch
|
19
|
+
from transformers import (
|
20
|
+
CLIPTextModelWithProjection,
|
21
|
+
CLIPTokenizer,
|
22
|
+
T5EncoderModel,
|
23
|
+
T5TokenizerFast,
|
24
|
+
)
|
25
|
+
|
26
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
27
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
28
|
+
from ...loaders import SD3LoraLoaderMixin
|
29
|
+
from ...models.autoencoders import AutoencoderKL
|
30
|
+
from ...models.transformers import SD3Transformer2DModel
|
31
|
+
from ...schedulers import FlowMatchEulerDiscreteScheduler
|
32
|
+
from ...utils import (
|
33
|
+
USE_PEFT_BACKEND,
|
34
|
+
is_torch_xla_available,
|
35
|
+
logging,
|
36
|
+
replace_example_docstring,
|
37
|
+
scale_lora_layers,
|
38
|
+
unscale_lora_layers,
|
39
|
+
)
|
40
|
+
from ...utils.torch_utils import randn_tensor
|
41
|
+
from ..pipeline_utils import DiffusionPipeline
|
42
|
+
from .pipeline_output import StableDiffusion3PipelineOutput
|
43
|
+
|
44
|
+
|
45
|
+
if is_torch_xla_available():
|
46
|
+
import torch_xla.core.xla_model as xm
|
47
|
+
|
48
|
+
XLA_AVAILABLE = True
|
49
|
+
else:
|
50
|
+
XLA_AVAILABLE = False
|
51
|
+
|
52
|
+
|
53
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
54
|
+
|
55
|
+
EXAMPLE_DOC_STRING = """
|
56
|
+
Examples:
|
57
|
+
```py
|
58
|
+
>>> import torch
|
59
|
+
>>> from diffusers import StableDiffusion3InpaintPipeline
|
60
|
+
>>> from diffusers.utils import load_image
|
61
|
+
|
62
|
+
>>> pipe = StableDiffusion3InpaintPipeline.from_pretrained(
|
63
|
+
... "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
|
64
|
+
... )
|
65
|
+
>>> pipe.to("cuda")
|
66
|
+
>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
|
67
|
+
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
|
68
|
+
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
|
69
|
+
>>> source = load_image(img_url)
|
70
|
+
>>> mask = load_image(mask_url)
|
71
|
+
>>> image = pipe(prompt=prompt, image=source, mask_image=mask).images[0]
|
72
|
+
>>> image.save("sd3_inpainting.png")
|
73
|
+
```
|
74
|
+
"""
|
75
|
+
|
76
|
+
|
77
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
78
|
+
def retrieve_latents(
|
79
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
80
|
+
):
|
81
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
82
|
+
return encoder_output.latent_dist.sample(generator)
|
83
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
84
|
+
return encoder_output.latent_dist.mode()
|
85
|
+
elif hasattr(encoder_output, "latents"):
|
86
|
+
return encoder_output.latents
|
87
|
+
else:
|
88
|
+
raise AttributeError("Could not access latents of provided encoder_output")
|
89
|
+
|
90
|
+
|
91
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
92
|
+
def retrieve_timesteps(
|
93
|
+
scheduler,
|
94
|
+
num_inference_steps: Optional[int] = None,
|
95
|
+
device: Optional[Union[str, torch.device]] = None,
|
96
|
+
timesteps: Optional[List[int]] = None,
|
97
|
+
sigmas: Optional[List[float]] = None,
|
98
|
+
**kwargs,
|
99
|
+
):
|
100
|
+
"""
|
101
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
102
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
103
|
+
|
104
|
+
Args:
|
105
|
+
scheduler (`SchedulerMixin`):
|
106
|
+
The scheduler to get timesteps from.
|
107
|
+
num_inference_steps (`int`):
|
108
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
109
|
+
must be `None`.
|
110
|
+
device (`str` or `torch.device`, *optional*):
|
111
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
112
|
+
timesteps (`List[int]`, *optional*):
|
113
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
114
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
115
|
+
sigmas (`List[float]`, *optional*):
|
116
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
117
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
118
|
+
|
119
|
+
Returns:
|
120
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
121
|
+
second element is the number of inference steps.
|
122
|
+
"""
|
123
|
+
if timesteps is not None and sigmas is not None:
|
124
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
125
|
+
if timesteps is not None:
|
126
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
127
|
+
if not accepts_timesteps:
|
128
|
+
raise ValueError(
|
129
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
130
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
131
|
+
)
|
132
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
133
|
+
timesteps = scheduler.timesteps
|
134
|
+
num_inference_steps = len(timesteps)
|
135
|
+
elif sigmas is not None:
|
136
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
137
|
+
if not accept_sigmas:
|
138
|
+
raise ValueError(
|
139
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
140
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
141
|
+
)
|
142
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
143
|
+
timesteps = scheduler.timesteps
|
144
|
+
num_inference_steps = len(timesteps)
|
145
|
+
else:
|
146
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
147
|
+
timesteps = scheduler.timesteps
|
148
|
+
return timesteps, num_inference_steps
|
149
|
+
|
150
|
+
|
151
|
+
class StableDiffusion3InpaintPipeline(DiffusionPipeline):
|
152
|
+
r"""
|
153
|
+
Args:
|
154
|
+
transformer ([`SD3Transformer2DModel`]):
|
155
|
+
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
|
156
|
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
157
|
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
158
|
+
vae ([`AutoencoderKL`]):
|
159
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
160
|
+
text_encoder ([`CLIPTextModelWithProjection`]):
|
161
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
162
|
+
specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant,
|
163
|
+
with an additional added projection layer that is initialized with a diagonal matrix with the `hidden_size`
|
164
|
+
as its dimension.
|
165
|
+
text_encoder_2 ([`CLIPTextModelWithProjection`]):
|
166
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
167
|
+
specifically the
|
168
|
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
169
|
+
variant.
|
170
|
+
text_encoder_3 ([`T5EncoderModel`]):
|
171
|
+
Frozen text-encoder. Stable Diffusion 3 uses
|
172
|
+
[T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
|
173
|
+
[t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
|
174
|
+
tokenizer (`CLIPTokenizer`):
|
175
|
+
Tokenizer of class
|
176
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
177
|
+
tokenizer_2 (`CLIPTokenizer`):
|
178
|
+
Second Tokenizer of class
|
179
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
180
|
+
tokenizer_3 (`T5TokenizerFast`):
|
181
|
+
Tokenizer of class
|
182
|
+
[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
|
183
|
+
"""
|
184
|
+
|
185
|
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->text_encoder_3->transformer->vae"
|
186
|
+
_optional_components = []
|
187
|
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "negative_pooled_prompt_embeds"]
|
188
|
+
|
189
|
+
def __init__(
|
190
|
+
self,
|
191
|
+
transformer: SD3Transformer2DModel,
|
192
|
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
193
|
+
vae: AutoencoderKL,
|
194
|
+
text_encoder: CLIPTextModelWithProjection,
|
195
|
+
tokenizer: CLIPTokenizer,
|
196
|
+
text_encoder_2: CLIPTextModelWithProjection,
|
197
|
+
tokenizer_2: CLIPTokenizer,
|
198
|
+
text_encoder_3: T5EncoderModel,
|
199
|
+
tokenizer_3: T5TokenizerFast,
|
200
|
+
):
|
201
|
+
super().__init__()
|
202
|
+
|
203
|
+
self.register_modules(
|
204
|
+
vae=vae,
|
205
|
+
text_encoder=text_encoder,
|
206
|
+
text_encoder_2=text_encoder_2,
|
207
|
+
text_encoder_3=text_encoder_3,
|
208
|
+
tokenizer=tokenizer,
|
209
|
+
tokenizer_2=tokenizer_2,
|
210
|
+
tokenizer_3=tokenizer_3,
|
211
|
+
transformer=transformer,
|
212
|
+
scheduler=scheduler,
|
213
|
+
)
|
214
|
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
215
|
+
self.image_processor = VaeImageProcessor(
|
216
|
+
vae_scale_factor=self.vae_scale_factor, vae_latent_channels=self.vae.config.latent_channels
|
217
|
+
)
|
218
|
+
self.mask_processor = VaeImageProcessor(
|
219
|
+
vae_scale_factor=self.vae_scale_factor,
|
220
|
+
vae_latent_channels=self.vae.config.latent_channels,
|
221
|
+
do_normalize=False,
|
222
|
+
do_binarize=True,
|
223
|
+
do_convert_grayscale=True,
|
224
|
+
)
|
225
|
+
self.tokenizer_max_length = self.tokenizer.model_max_length
|
226
|
+
self.default_sample_size = self.transformer.config.sample_size
|
227
|
+
|
228
|
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline._get_t5_prompt_embeds
|
229
|
+
def _get_t5_prompt_embeds(
|
230
|
+
self,
|
231
|
+
prompt: Union[str, List[str]] = None,
|
232
|
+
num_images_per_prompt: int = 1,
|
233
|
+
max_sequence_length: int = 256,
|
234
|
+
device: Optional[torch.device] = None,
|
235
|
+
dtype: Optional[torch.dtype] = None,
|
236
|
+
):
|
237
|
+
device = device or self._execution_device
|
238
|
+
dtype = dtype or self.text_encoder.dtype
|
239
|
+
|
240
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
241
|
+
batch_size = len(prompt)
|
242
|
+
|
243
|
+
if self.text_encoder_3 is None:
|
244
|
+
return torch.zeros(
|
245
|
+
(
|
246
|
+
batch_size * num_images_per_prompt,
|
247
|
+
self.tokenizer_max_length,
|
248
|
+
self.transformer.config.joint_attention_dim,
|
249
|
+
),
|
250
|
+
device=device,
|
251
|
+
dtype=dtype,
|
252
|
+
)
|
253
|
+
|
254
|
+
text_inputs = self.tokenizer_3(
|
255
|
+
prompt,
|
256
|
+
padding="max_length",
|
257
|
+
max_length=max_sequence_length,
|
258
|
+
truncation=True,
|
259
|
+
add_special_tokens=True,
|
260
|
+
return_tensors="pt",
|
261
|
+
)
|
262
|
+
text_input_ids = text_inputs.input_ids
|
263
|
+
untruncated_ids = self.tokenizer_3(prompt, padding="longest", return_tensors="pt").input_ids
|
264
|
+
|
265
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
266
|
+
removed_text = self.tokenizer_3.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
267
|
+
logger.warning(
|
268
|
+
"The following part of your input was truncated because `max_sequence_length` is set to "
|
269
|
+
f" {max_sequence_length} tokens: {removed_text}"
|
270
|
+
)
|
271
|
+
|
272
|
+
prompt_embeds = self.text_encoder_3(text_input_ids.to(device))[0]
|
273
|
+
|
274
|
+
dtype = self.text_encoder_3.dtype
|
275
|
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
276
|
+
|
277
|
+
_, seq_len, _ = prompt_embeds.shape
|
278
|
+
|
279
|
+
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
|
280
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
281
|
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
282
|
+
|
283
|
+
return prompt_embeds
|
284
|
+
|
285
|
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline._get_clip_prompt_embeds
|
286
|
+
def _get_clip_prompt_embeds(
|
287
|
+
self,
|
288
|
+
prompt: Union[str, List[str]],
|
289
|
+
num_images_per_prompt: int = 1,
|
290
|
+
device: Optional[torch.device] = None,
|
291
|
+
clip_skip: Optional[int] = None,
|
292
|
+
clip_model_index: int = 0,
|
293
|
+
):
|
294
|
+
device = device or self._execution_device
|
295
|
+
|
296
|
+
clip_tokenizers = [self.tokenizer, self.tokenizer_2]
|
297
|
+
clip_text_encoders = [self.text_encoder, self.text_encoder_2]
|
298
|
+
|
299
|
+
tokenizer = clip_tokenizers[clip_model_index]
|
300
|
+
text_encoder = clip_text_encoders[clip_model_index]
|
301
|
+
|
302
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
303
|
+
batch_size = len(prompt)
|
304
|
+
|
305
|
+
text_inputs = tokenizer(
|
306
|
+
prompt,
|
307
|
+
padding="max_length",
|
308
|
+
max_length=self.tokenizer_max_length,
|
309
|
+
truncation=True,
|
310
|
+
return_tensors="pt",
|
311
|
+
)
|
312
|
+
|
313
|
+
text_input_ids = text_inputs.input_ids
|
314
|
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
315
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
316
|
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
|
317
|
+
logger.warning(
|
318
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
319
|
+
f" {self.tokenizer_max_length} tokens: {removed_text}"
|
320
|
+
)
|
321
|
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
|
322
|
+
pooled_prompt_embeds = prompt_embeds[0]
|
323
|
+
|
324
|
+
if clip_skip is None:
|
325
|
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
326
|
+
else:
|
327
|
+
prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
|
328
|
+
|
329
|
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
330
|
+
|
331
|
+
_, seq_len, _ = prompt_embeds.shape
|
332
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
333
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
334
|
+
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
335
|
+
|
336
|
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
337
|
+
pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
|
338
|
+
|
339
|
+
return prompt_embeds, pooled_prompt_embeds
|
340
|
+
|
341
|
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline.encode_prompt
|
342
|
+
def encode_prompt(
|
343
|
+
self,
|
344
|
+
prompt: Union[str, List[str]],
|
345
|
+
prompt_2: Union[str, List[str]],
|
346
|
+
prompt_3: Union[str, List[str]],
|
347
|
+
device: Optional[torch.device] = None,
|
348
|
+
num_images_per_prompt: int = 1,
|
349
|
+
do_classifier_free_guidance: bool = True,
|
350
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
351
|
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
352
|
+
negative_prompt_3: Optional[Union[str, List[str]]] = None,
|
353
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
354
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
355
|
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
356
|
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
357
|
+
clip_skip: Optional[int] = None,
|
358
|
+
max_sequence_length: int = 256,
|
359
|
+
lora_scale: Optional[float] = None,
|
360
|
+
):
|
361
|
+
r"""
|
362
|
+
|
363
|
+
Args:
|
364
|
+
prompt (`str` or `List[str]`, *optional*):
|
365
|
+
prompt to be encoded
|
366
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
367
|
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
368
|
+
used in all text-encoders
|
369
|
+
prompt_3 (`str` or `List[str]`, *optional*):
|
370
|
+
The prompt or prompts to be sent to the `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
|
371
|
+
used in all text-encoders
|
372
|
+
device: (`torch.device`):
|
373
|
+
torch device
|
374
|
+
num_images_per_prompt (`int`):
|
375
|
+
number of images that should be generated per prompt
|
376
|
+
do_classifier_free_guidance (`bool`):
|
377
|
+
whether to use classifier free guidance or not
|
378
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
379
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
380
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
381
|
+
less than `1`).
|
382
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
383
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
384
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
|
385
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
386
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
|
387
|
+
`text_encoder_3`. If not defined, `negative_prompt` is used in both text-encoders
|
388
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
389
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
390
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
391
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
392
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
393
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
394
|
+
argument.
|
395
|
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
396
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
397
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
398
|
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
399
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
400
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
401
|
+
input argument.
|
402
|
+
clip_skip (`int`, *optional*):
|
403
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
404
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
405
|
+
lora_scale (`float`, *optional*):
|
406
|
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
407
|
+
"""
|
408
|
+
device = device or self._execution_device
|
409
|
+
|
410
|
+
# set lora scale so that monkey patched LoRA
|
411
|
+
# function of text encoder can correctly access it
|
412
|
+
if lora_scale is not None and isinstance(self, SD3LoraLoaderMixin):
|
413
|
+
self._lora_scale = lora_scale
|
414
|
+
|
415
|
+
# dynamically adjust the LoRA scale
|
416
|
+
if self.text_encoder is not None and USE_PEFT_BACKEND:
|
417
|
+
scale_lora_layers(self.text_encoder, lora_scale)
|
418
|
+
if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
|
419
|
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
420
|
+
|
421
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
422
|
+
if prompt is not None:
|
423
|
+
batch_size = len(prompt)
|
424
|
+
else:
|
425
|
+
batch_size = prompt_embeds.shape[0]
|
426
|
+
|
427
|
+
if prompt_embeds is None:
|
428
|
+
prompt_2 = prompt_2 or prompt
|
429
|
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
430
|
+
|
431
|
+
prompt_3 = prompt_3 or prompt
|
432
|
+
prompt_3 = [prompt_3] if isinstance(prompt_3, str) else prompt_3
|
433
|
+
|
434
|
+
prompt_embed, pooled_prompt_embed = self._get_clip_prompt_embeds(
|
435
|
+
prompt=prompt,
|
436
|
+
device=device,
|
437
|
+
num_images_per_prompt=num_images_per_prompt,
|
438
|
+
clip_skip=clip_skip,
|
439
|
+
clip_model_index=0,
|
440
|
+
)
|
441
|
+
prompt_2_embed, pooled_prompt_2_embed = self._get_clip_prompt_embeds(
|
442
|
+
prompt=prompt_2,
|
443
|
+
device=device,
|
444
|
+
num_images_per_prompt=num_images_per_prompt,
|
445
|
+
clip_skip=clip_skip,
|
446
|
+
clip_model_index=1,
|
447
|
+
)
|
448
|
+
clip_prompt_embeds = torch.cat([prompt_embed, prompt_2_embed], dim=-1)
|
449
|
+
|
450
|
+
t5_prompt_embed = self._get_t5_prompt_embeds(
|
451
|
+
prompt=prompt_3,
|
452
|
+
num_images_per_prompt=num_images_per_prompt,
|
453
|
+
max_sequence_length=max_sequence_length,
|
454
|
+
device=device,
|
455
|
+
)
|
456
|
+
|
457
|
+
clip_prompt_embeds = torch.nn.functional.pad(
|
458
|
+
clip_prompt_embeds, (0, t5_prompt_embed.shape[-1] - clip_prompt_embeds.shape[-1])
|
459
|
+
)
|
460
|
+
|
461
|
+
prompt_embeds = torch.cat([clip_prompt_embeds, t5_prompt_embed], dim=-2)
|
462
|
+
pooled_prompt_embeds = torch.cat([pooled_prompt_embed, pooled_prompt_2_embed], dim=-1)
|
463
|
+
|
464
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
465
|
+
negative_prompt = negative_prompt or ""
|
466
|
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
467
|
+
negative_prompt_3 = negative_prompt_3 or negative_prompt
|
468
|
+
|
469
|
+
# normalize str to list
|
470
|
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
471
|
+
negative_prompt_2 = (
|
472
|
+
batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
|
473
|
+
)
|
474
|
+
negative_prompt_3 = (
|
475
|
+
batch_size * [negative_prompt_3] if isinstance(negative_prompt_3, str) else negative_prompt_3
|
476
|
+
)
|
477
|
+
|
478
|
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
479
|
+
raise TypeError(
|
480
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
481
|
+
f" {type(prompt)}."
|
482
|
+
)
|
483
|
+
elif batch_size != len(negative_prompt):
|
484
|
+
raise ValueError(
|
485
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
486
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
487
|
+
" the batch size of `prompt`."
|
488
|
+
)
|
489
|
+
|
490
|
+
negative_prompt_embed, negative_pooled_prompt_embed = self._get_clip_prompt_embeds(
|
491
|
+
negative_prompt,
|
492
|
+
device=device,
|
493
|
+
num_images_per_prompt=num_images_per_prompt,
|
494
|
+
clip_skip=None,
|
495
|
+
clip_model_index=0,
|
496
|
+
)
|
497
|
+
negative_prompt_2_embed, negative_pooled_prompt_2_embed = self._get_clip_prompt_embeds(
|
498
|
+
negative_prompt_2,
|
499
|
+
device=device,
|
500
|
+
num_images_per_prompt=num_images_per_prompt,
|
501
|
+
clip_skip=None,
|
502
|
+
clip_model_index=1,
|
503
|
+
)
|
504
|
+
negative_clip_prompt_embeds = torch.cat([negative_prompt_embed, negative_prompt_2_embed], dim=-1)
|
505
|
+
|
506
|
+
t5_negative_prompt_embed = self._get_t5_prompt_embeds(
|
507
|
+
prompt=negative_prompt_3,
|
508
|
+
num_images_per_prompt=num_images_per_prompt,
|
509
|
+
max_sequence_length=max_sequence_length,
|
510
|
+
device=device,
|
511
|
+
)
|
512
|
+
|
513
|
+
negative_clip_prompt_embeds = torch.nn.functional.pad(
|
514
|
+
negative_clip_prompt_embeds,
|
515
|
+
(0, t5_negative_prompt_embed.shape[-1] - negative_clip_prompt_embeds.shape[-1]),
|
516
|
+
)
|
517
|
+
|
518
|
+
negative_prompt_embeds = torch.cat([negative_clip_prompt_embeds, t5_negative_prompt_embed], dim=-2)
|
519
|
+
negative_pooled_prompt_embeds = torch.cat(
|
520
|
+
[negative_pooled_prompt_embed, negative_pooled_prompt_2_embed], dim=-1
|
521
|
+
)
|
522
|
+
|
523
|
+
if self.text_encoder is not None:
|
524
|
+
if isinstance(self, SD3LoraLoaderMixin) and USE_PEFT_BACKEND:
|
525
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
526
|
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
527
|
+
|
528
|
+
if self.text_encoder_2 is not None:
|
529
|
+
if isinstance(self, SD3LoraLoaderMixin) and USE_PEFT_BACKEND:
|
530
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
531
|
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
532
|
+
|
533
|
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
534
|
+
|
535
|
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.check_inputs
|
536
|
+
def check_inputs(
|
537
|
+
self,
|
538
|
+
prompt,
|
539
|
+
prompt_2,
|
540
|
+
prompt_3,
|
541
|
+
strength,
|
542
|
+
negative_prompt=None,
|
543
|
+
negative_prompt_2=None,
|
544
|
+
negative_prompt_3=None,
|
545
|
+
prompt_embeds=None,
|
546
|
+
negative_prompt_embeds=None,
|
547
|
+
pooled_prompt_embeds=None,
|
548
|
+
negative_pooled_prompt_embeds=None,
|
549
|
+
callback_on_step_end_tensor_inputs=None,
|
550
|
+
max_sequence_length=None,
|
551
|
+
):
|
552
|
+
if strength < 0 or strength > 1:
|
553
|
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
554
|
+
|
555
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
556
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
557
|
+
):
|
558
|
+
raise ValueError(
|
559
|
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
560
|
+
)
|
561
|
+
|
562
|
+
if prompt is not None and prompt_embeds is not None:
|
563
|
+
raise ValueError(
|
564
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
565
|
+
" only forward one of the two."
|
566
|
+
)
|
567
|
+
elif prompt_2 is not None and prompt_embeds is not None:
|
568
|
+
raise ValueError(
|
569
|
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
570
|
+
" only forward one of the two."
|
571
|
+
)
|
572
|
+
elif prompt_3 is not None and prompt_embeds is not None:
|
573
|
+
raise ValueError(
|
574
|
+
f"Cannot forward both `prompt_3`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
575
|
+
" only forward one of the two."
|
576
|
+
)
|
577
|
+
elif prompt is None and prompt_embeds is None:
|
578
|
+
raise ValueError(
|
579
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
580
|
+
)
|
581
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
582
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
583
|
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
584
|
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
585
|
+
elif prompt_3 is not None and (not isinstance(prompt_3, str) and not isinstance(prompt_3, list)):
|
586
|
+
raise ValueError(f"`prompt_3` has to be of type `str` or `list` but is {type(prompt_3)}")
|
587
|
+
|
588
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
589
|
+
raise ValueError(
|
590
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
591
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
592
|
+
)
|
593
|
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
594
|
+
raise ValueError(
|
595
|
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
596
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
597
|
+
)
|
598
|
+
elif negative_prompt_3 is not None and negative_prompt_embeds is not None:
|
599
|
+
raise ValueError(
|
600
|
+
f"Cannot forward both `negative_prompt_3`: {negative_prompt_3} and `negative_prompt_embeds`:"
|
601
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
602
|
+
)
|
603
|
+
|
604
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
605
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
606
|
+
raise ValueError(
|
607
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
608
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
609
|
+
f" {negative_prompt_embeds.shape}."
|
610
|
+
)
|
611
|
+
|
612
|
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
613
|
+
raise ValueError(
|
614
|
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
615
|
+
)
|
616
|
+
|
617
|
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
618
|
+
raise ValueError(
|
619
|
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
620
|
+
)
|
621
|
+
|
622
|
+
if max_sequence_length is not None and max_sequence_length > 512:
|
623
|
+
raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
|
624
|
+
|
625
|
+
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
|
626
|
+
def get_timesteps(self, num_inference_steps, strength, device):
|
627
|
+
# get the original timestep using init_timestep
|
628
|
+
init_timestep = min(num_inference_steps * strength, num_inference_steps)
|
629
|
+
|
630
|
+
t_start = int(max(num_inference_steps - init_timestep, 0))
|
631
|
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
632
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
633
|
+
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
634
|
+
|
635
|
+
return timesteps, num_inference_steps - t_start
|
636
|
+
|
637
|
+
def prepare_latents(
|
638
|
+
self,
|
639
|
+
batch_size,
|
640
|
+
num_channels_latents,
|
641
|
+
height,
|
642
|
+
width,
|
643
|
+
dtype,
|
644
|
+
device,
|
645
|
+
generator,
|
646
|
+
latents=None,
|
647
|
+
image=None,
|
648
|
+
timestep=None,
|
649
|
+
is_strength_max=True,
|
650
|
+
return_noise=False,
|
651
|
+
return_image_latents=False,
|
652
|
+
):
|
653
|
+
shape = (
|
654
|
+
batch_size,
|
655
|
+
num_channels_latents,
|
656
|
+
int(height) // self.vae_scale_factor,
|
657
|
+
int(width) // self.vae_scale_factor,
|
658
|
+
)
|
659
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
660
|
+
raise ValueError(
|
661
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
662
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
663
|
+
)
|
664
|
+
|
665
|
+
if (image is None or timestep is None) and not is_strength_max:
|
666
|
+
raise ValueError(
|
667
|
+
"Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
|
668
|
+
"However, either the image or the noise timestep has not been provided."
|
669
|
+
)
|
670
|
+
|
671
|
+
if return_image_latents or (latents is None and not is_strength_max):
|
672
|
+
image = image.to(device=device, dtype=dtype)
|
673
|
+
|
674
|
+
if image.shape[1] == 16:
|
675
|
+
image_latents = image
|
676
|
+
else:
|
677
|
+
image_latents = self._encode_vae_image(image=image, generator=generator)
|
678
|
+
image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
|
679
|
+
|
680
|
+
if latents is None:
|
681
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
682
|
+
# if strength is 1. then initialise the latents to noise, else initial to image + noise
|
683
|
+
latents = noise if is_strength_max else self.scheduler.scale_noise(image_latents, timestep, noise)
|
684
|
+
else:
|
685
|
+
noise = latents.to(device)
|
686
|
+
latents = noise
|
687
|
+
|
688
|
+
outputs = (latents,)
|
689
|
+
|
690
|
+
if return_noise:
|
691
|
+
outputs += (noise,)
|
692
|
+
|
693
|
+
if return_image_latents:
|
694
|
+
outputs += (image_latents,)
|
695
|
+
|
696
|
+
return outputs
|
697
|
+
|
698
|
+
def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
|
699
|
+
if isinstance(generator, list):
|
700
|
+
image_latents = [
|
701
|
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
702
|
+
for i in range(image.shape[0])
|
703
|
+
]
|
704
|
+
image_latents = torch.cat(image_latents, dim=0)
|
705
|
+
else:
|
706
|
+
image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
707
|
+
|
708
|
+
image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
709
|
+
|
710
|
+
return image_latents
|
711
|
+
|
712
|
+
def prepare_mask_latents(
|
713
|
+
self,
|
714
|
+
mask,
|
715
|
+
masked_image,
|
716
|
+
batch_size,
|
717
|
+
num_images_per_prompt,
|
718
|
+
height,
|
719
|
+
width,
|
720
|
+
dtype,
|
721
|
+
device,
|
722
|
+
generator,
|
723
|
+
do_classifier_free_guidance,
|
724
|
+
):
|
725
|
+
# resize the mask to latents shape as we concatenate the mask to the latents
|
726
|
+
# we do that before converting to dtype to avoid breaking in case we're using cpu_offload
|
727
|
+
# and half precision
|
728
|
+
mask = torch.nn.functional.interpolate(
|
729
|
+
mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
|
730
|
+
)
|
731
|
+
mask = mask.to(device=device, dtype=dtype)
|
732
|
+
|
733
|
+
batch_size = batch_size * num_images_per_prompt
|
734
|
+
|
735
|
+
masked_image = masked_image.to(device=device, dtype=dtype)
|
736
|
+
|
737
|
+
if masked_image.shape[1] == 16:
|
738
|
+
masked_image_latents = masked_image
|
739
|
+
else:
|
740
|
+
masked_image_latents = retrieve_latents(self.vae.encode(masked_image), generator=generator)
|
741
|
+
|
742
|
+
masked_image_latents = (masked_image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
743
|
+
|
744
|
+
# duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
|
745
|
+
if mask.shape[0] < batch_size:
|
746
|
+
if not batch_size % mask.shape[0] == 0:
|
747
|
+
raise ValueError(
|
748
|
+
"The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
|
749
|
+
f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
|
750
|
+
" of masks that you pass is divisible by the total requested batch size."
|
751
|
+
)
|
752
|
+
mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
|
753
|
+
if masked_image_latents.shape[0] < batch_size:
|
754
|
+
if not batch_size % masked_image_latents.shape[0] == 0:
|
755
|
+
raise ValueError(
|
756
|
+
"The passed images and the required batch size don't match. Images are supposed to be duplicated"
|
757
|
+
f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
|
758
|
+
" Make sure the number of images that you pass is divisible by the total requested batch size."
|
759
|
+
)
|
760
|
+
masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
|
761
|
+
|
762
|
+
mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
|
763
|
+
masked_image_latents = (
|
764
|
+
torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
|
765
|
+
)
|
766
|
+
|
767
|
+
# aligning device to prevent device errors when concating it with the latent model input
|
768
|
+
masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
|
769
|
+
return mask, masked_image_latents
|
770
|
+
|
771
|
+
@property
|
772
|
+
def guidance_scale(self):
|
773
|
+
return self._guidance_scale
|
774
|
+
|
775
|
+
@property
|
776
|
+
def clip_skip(self):
|
777
|
+
return self._clip_skip
|
778
|
+
|
779
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
780
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
781
|
+
# corresponds to doing no classifier free guidance.
|
782
|
+
@property
|
783
|
+
def do_classifier_free_guidance(self):
|
784
|
+
return self._guidance_scale > 1
|
785
|
+
|
786
|
+
@property
|
787
|
+
def num_timesteps(self):
|
788
|
+
return self._num_timesteps
|
789
|
+
|
790
|
+
@property
|
791
|
+
def interrupt(self):
|
792
|
+
return self._interrupt
|
793
|
+
|
794
|
+
@torch.no_grad()
|
795
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
796
|
+
def __call__(
|
797
|
+
self,
|
798
|
+
prompt: Union[str, List[str]] = None,
|
799
|
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
800
|
+
prompt_3: Optional[Union[str, List[str]]] = None,
|
801
|
+
image: PipelineImageInput = None,
|
802
|
+
mask_image: PipelineImageInput = None,
|
803
|
+
masked_image_latents: PipelineImageInput = None,
|
804
|
+
height: int = None,
|
805
|
+
width: int = None,
|
806
|
+
padding_mask_crop: Optional[int] = None,
|
807
|
+
strength: float = 0.6,
|
808
|
+
num_inference_steps: int = 50,
|
809
|
+
timesteps: List[int] = None,
|
810
|
+
guidance_scale: float = 7.0,
|
811
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
812
|
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
813
|
+
negative_prompt_3: Optional[Union[str, List[str]]] = None,
|
814
|
+
num_images_per_prompt: Optional[int] = 1,
|
815
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
816
|
+
latents: Optional[torch.Tensor] = None,
|
817
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
818
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
819
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
820
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
821
|
+
output_type: Optional[str] = "pil",
|
822
|
+
return_dict: bool = True,
|
823
|
+
clip_skip: Optional[int] = None,
|
824
|
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
825
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
826
|
+
max_sequence_length: int = 256,
|
827
|
+
):
|
828
|
+
r"""
|
829
|
+
Function invoked when calling the pipeline for generation.
|
830
|
+
|
831
|
+
Args:
|
832
|
+
prompt (`str` or `List[str]`, *optional*):
|
833
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
834
|
+
instead.
|
835
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
836
|
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
837
|
+
will be used instead
|
838
|
+
prompt_3 (`str` or `List[str]`, *optional*):
|
839
|
+
The prompt or prompts to be sent to `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
|
840
|
+
will be used instead
|
841
|
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
842
|
+
`Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
|
843
|
+
numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
|
844
|
+
or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
|
845
|
+
list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
|
846
|
+
latents as `image`, but if passing latents directly it is not encoded again.
|
847
|
+
mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
848
|
+
`Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
|
849
|
+
are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
|
850
|
+
single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
|
851
|
+
color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
|
852
|
+
H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
|
853
|
+
1)`, or `(H, W)`.
|
854
|
+
mask_image_latent (`torch.Tensor`, `List[torch.Tensor]`):
|
855
|
+
`Tensor` representing an image batch to mask `image` generated by VAE. If not provided, the mask
|
856
|
+
latents tensor will ge generated by `mask_image`.
|
857
|
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
858
|
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
859
|
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
860
|
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
861
|
+
padding_mask_crop (`int`, *optional*, defaults to `None`):
|
862
|
+
The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
|
863
|
+
image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
|
864
|
+
with the same aspect ration of the image and contains all masked area, and then expand that area based
|
865
|
+
on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
|
866
|
+
resizing to the original image size for inpainting. This is useful when the masked area is small while
|
867
|
+
the image is large and contain information irrelevant for inpainting, such as background.
|
868
|
+
strength (`float`, *optional*, defaults to 1.0):
|
869
|
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
870
|
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
871
|
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
872
|
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
873
|
+
essentially ignores `image`.
|
874
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
875
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
876
|
+
expense of slower inference.
|
877
|
+
timesteps (`List[int]`, *optional*):
|
878
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
879
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
880
|
+
passed will be used. Must be in descending order.
|
881
|
+
guidance_scale (`float`, *optional*, defaults to 7.0):
|
882
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
883
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
884
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
885
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
886
|
+
usually at the expense of lower image quality.
|
887
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
888
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
889
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
890
|
+
less than `1`).
|
891
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
892
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
893
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used instead
|
894
|
+
negative_prompt_3 (`str` or `List[str]`, *optional*):
|
895
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
|
896
|
+
`text_encoder_3`. If not defined, `negative_prompt` is used instead
|
897
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
898
|
+
The number of images to generate per prompt.
|
899
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
900
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
901
|
+
to make generation deterministic.
|
902
|
+
latents (`torch.FloatTensor`, *optional*):
|
903
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
904
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
905
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
906
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
907
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
908
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
909
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
910
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
911
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
912
|
+
argument.
|
913
|
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
914
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
915
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
916
|
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
917
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
918
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
919
|
+
input argument.
|
920
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
921
|
+
The output format of the generate image. Choose between
|
922
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
923
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
924
|
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
925
|
+
of a plain tuple.
|
926
|
+
callback_on_step_end (`Callable`, *optional*):
|
927
|
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
928
|
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
929
|
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
930
|
+
`callback_on_step_end_tensor_inputs`.
|
931
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
932
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
933
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
934
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
935
|
+
max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
|
936
|
+
|
937
|
+
Examples:
|
938
|
+
|
939
|
+
Returns:
|
940
|
+
[`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`] or `tuple`:
|
941
|
+
[`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`] if `return_dict` is True, otherwise a
|
942
|
+
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
943
|
+
"""
|
944
|
+
|
945
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
946
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
947
|
+
|
948
|
+
height = height or self.transformer.config.sample_size * self.vae_scale_factor
|
949
|
+
width = width or self.transformer.config.sample_size * self.vae_scale_factor
|
950
|
+
|
951
|
+
# 1. Check inputs. Raise error if not correct
|
952
|
+
self.check_inputs(
|
953
|
+
prompt,
|
954
|
+
prompt_2,
|
955
|
+
prompt_3,
|
956
|
+
strength,
|
957
|
+
negative_prompt=negative_prompt,
|
958
|
+
negative_prompt_2=negative_prompt_2,
|
959
|
+
negative_prompt_3=negative_prompt_3,
|
960
|
+
prompt_embeds=prompt_embeds,
|
961
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
962
|
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
963
|
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
964
|
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
965
|
+
max_sequence_length=max_sequence_length,
|
966
|
+
)
|
967
|
+
|
968
|
+
self._guidance_scale = guidance_scale
|
969
|
+
self._clip_skip = clip_skip
|
970
|
+
self._interrupt = False
|
971
|
+
|
972
|
+
# 2. Define call parameters
|
973
|
+
if prompt is not None and isinstance(prompt, str):
|
974
|
+
batch_size = 1
|
975
|
+
elif prompt is not None and isinstance(prompt, list):
|
976
|
+
batch_size = len(prompt)
|
977
|
+
else:
|
978
|
+
batch_size = prompt_embeds.shape[0]
|
979
|
+
|
980
|
+
device = self._execution_device
|
981
|
+
|
982
|
+
(
|
983
|
+
prompt_embeds,
|
984
|
+
negative_prompt_embeds,
|
985
|
+
pooled_prompt_embeds,
|
986
|
+
negative_pooled_prompt_embeds,
|
987
|
+
) = self.encode_prompt(
|
988
|
+
prompt=prompt,
|
989
|
+
prompt_2=prompt_2,
|
990
|
+
prompt_3=prompt_3,
|
991
|
+
negative_prompt=negative_prompt,
|
992
|
+
negative_prompt_2=negative_prompt_2,
|
993
|
+
negative_prompt_3=negative_prompt_3,
|
994
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
995
|
+
prompt_embeds=prompt_embeds,
|
996
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
997
|
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
998
|
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
999
|
+
device=device,
|
1000
|
+
clip_skip=self.clip_skip,
|
1001
|
+
num_images_per_prompt=num_images_per_prompt,
|
1002
|
+
max_sequence_length=max_sequence_length,
|
1003
|
+
)
|
1004
|
+
|
1005
|
+
if self.do_classifier_free_guidance:
|
1006
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1007
|
+
pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
|
1008
|
+
|
1009
|
+
# 3. Prepare timesteps
|
1010
|
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
1011
|
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
1012
|
+
# check that number of inference steps is not < 1 - as this doesn't make sense
|
1013
|
+
if num_inference_steps < 1:
|
1014
|
+
raise ValueError(
|
1015
|
+
f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
|
1016
|
+
f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
|
1017
|
+
)
|
1018
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
1019
|
+
|
1020
|
+
# create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
|
1021
|
+
is_strength_max = strength == 1.0
|
1022
|
+
|
1023
|
+
# 4. Preprocess mask and image
|
1024
|
+
if padding_mask_crop is not None:
|
1025
|
+
crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
|
1026
|
+
resize_mode = "fill"
|
1027
|
+
else:
|
1028
|
+
crops_coords = None
|
1029
|
+
resize_mode = "default"
|
1030
|
+
|
1031
|
+
original_image = image
|
1032
|
+
init_image = self.image_processor.preprocess(
|
1033
|
+
image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
|
1034
|
+
)
|
1035
|
+
init_image = init_image.to(dtype=torch.float32)
|
1036
|
+
|
1037
|
+
# 5. Prepare latent variables
|
1038
|
+
num_channels_latents = self.vae.config.latent_channels
|
1039
|
+
num_channels_transformer = self.transformer.config.in_channels
|
1040
|
+
return_image_latents = num_channels_transformer == 16
|
1041
|
+
|
1042
|
+
latents_outputs = self.prepare_latents(
|
1043
|
+
batch_size * num_images_per_prompt,
|
1044
|
+
num_channels_latents,
|
1045
|
+
height,
|
1046
|
+
width,
|
1047
|
+
prompt_embeds.dtype,
|
1048
|
+
device,
|
1049
|
+
generator,
|
1050
|
+
latents,
|
1051
|
+
image=init_image,
|
1052
|
+
timestep=latent_timestep,
|
1053
|
+
is_strength_max=is_strength_max,
|
1054
|
+
return_noise=True,
|
1055
|
+
return_image_latents=return_image_latents,
|
1056
|
+
)
|
1057
|
+
|
1058
|
+
if return_image_latents:
|
1059
|
+
latents, noise, image_latents = latents_outputs
|
1060
|
+
else:
|
1061
|
+
latents, noise = latents_outputs
|
1062
|
+
|
1063
|
+
# 6. Prepare mask latent variables
|
1064
|
+
mask_condition = self.mask_processor.preprocess(
|
1065
|
+
mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
|
1066
|
+
)
|
1067
|
+
|
1068
|
+
if masked_image_latents is None:
|
1069
|
+
masked_image = init_image * (mask_condition < 0.5)
|
1070
|
+
else:
|
1071
|
+
masked_image = masked_image_latents
|
1072
|
+
|
1073
|
+
mask, masked_image_latents = self.prepare_mask_latents(
|
1074
|
+
mask_condition,
|
1075
|
+
masked_image,
|
1076
|
+
batch_size,
|
1077
|
+
num_images_per_prompt,
|
1078
|
+
height,
|
1079
|
+
width,
|
1080
|
+
prompt_embeds.dtype,
|
1081
|
+
device,
|
1082
|
+
generator,
|
1083
|
+
self.do_classifier_free_guidance,
|
1084
|
+
)
|
1085
|
+
|
1086
|
+
# match the inpainting pipeline and will be updated with input + mask inpainting model later
|
1087
|
+
if num_channels_transformer == 33:
|
1088
|
+
# default case for runwayml/stable-diffusion-inpainting
|
1089
|
+
num_channels_mask = mask.shape[1]
|
1090
|
+
num_channels_masked_image = masked_image_latents.shape[1]
|
1091
|
+
if (
|
1092
|
+
num_channels_latents + num_channels_mask + num_channels_masked_image
|
1093
|
+
!= self.transformer.config.in_channels
|
1094
|
+
):
|
1095
|
+
raise ValueError(
|
1096
|
+
f"Incorrect configuration settings! The config of `pipeline.transformer`: {self.transformer.config} expects"
|
1097
|
+
f" {self.transformer.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
|
1098
|
+
f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
|
1099
|
+
f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
|
1100
|
+
" `pipeline.transformer` or your `mask_image` or `image` input."
|
1101
|
+
)
|
1102
|
+
elif num_channels_transformer != 16:
|
1103
|
+
raise ValueError(
|
1104
|
+
f"The transformer {self.transformer.__class__} should have 16 input channels or 33 input channels, not {self.transformer.config.in_channels}."
|
1105
|
+
)
|
1106
|
+
|
1107
|
+
# 7. Denoising loop
|
1108
|
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
1109
|
+
self._num_timesteps = len(timesteps)
|
1110
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1111
|
+
for i, t in enumerate(timesteps):
|
1112
|
+
if self.interrupt:
|
1113
|
+
continue
|
1114
|
+
|
1115
|
+
# expand the latents if we are doing classifier free guidance
|
1116
|
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1117
|
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
1118
|
+
timestep = t.expand(latent_model_input.shape[0])
|
1119
|
+
|
1120
|
+
if num_channels_transformer == 33:
|
1121
|
+
latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
|
1122
|
+
|
1123
|
+
noise_pred = self.transformer(
|
1124
|
+
hidden_states=latent_model_input,
|
1125
|
+
timestep=timestep,
|
1126
|
+
encoder_hidden_states=prompt_embeds,
|
1127
|
+
pooled_projections=pooled_prompt_embeds,
|
1128
|
+
return_dict=False,
|
1129
|
+
)[0]
|
1130
|
+
|
1131
|
+
# perform guidance
|
1132
|
+
if self.do_classifier_free_guidance:
|
1133
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1134
|
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1135
|
+
|
1136
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1137
|
+
latents_dtype = latents.dtype
|
1138
|
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
1139
|
+
if num_channels_transformer == 16:
|
1140
|
+
init_latents_proper = image_latents
|
1141
|
+
if self.do_classifier_free_guidance:
|
1142
|
+
init_mask, _ = mask.chunk(2)
|
1143
|
+
else:
|
1144
|
+
init_mask = mask
|
1145
|
+
|
1146
|
+
if i < len(timesteps) - 1:
|
1147
|
+
noise_timestep = timesteps[i + 1]
|
1148
|
+
init_latents_proper = self.scheduler.scale_noise(
|
1149
|
+
init_latents_proper, torch.tensor([noise_timestep]), noise
|
1150
|
+
)
|
1151
|
+
|
1152
|
+
latents = (1 - init_mask) * init_latents_proper + init_mask * latents
|
1153
|
+
|
1154
|
+
if latents.dtype != latents_dtype:
|
1155
|
+
if torch.backends.mps.is_available():
|
1156
|
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
1157
|
+
latents = latents.to(latents_dtype)
|
1158
|
+
|
1159
|
+
if callback_on_step_end is not None:
|
1160
|
+
callback_kwargs = {}
|
1161
|
+
for k in callback_on_step_end_tensor_inputs:
|
1162
|
+
callback_kwargs[k] = locals()[k]
|
1163
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1164
|
+
|
1165
|
+
latents = callback_outputs.pop("latents", latents)
|
1166
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1167
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1168
|
+
negative_pooled_prompt_embeds = callback_outputs.pop(
|
1169
|
+
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
1170
|
+
)
|
1171
|
+
mask = callback_outputs.pop("mask", mask)
|
1172
|
+
masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)
|
1173
|
+
|
1174
|
+
# call the callback, if provided
|
1175
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1176
|
+
progress_bar.update()
|
1177
|
+
|
1178
|
+
if XLA_AVAILABLE:
|
1179
|
+
xm.mark_step()
|
1180
|
+
|
1181
|
+
if not output_type == "latent":
|
1182
|
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
1183
|
+
0
|
1184
|
+
]
|
1185
|
+
else:
|
1186
|
+
image = latents
|
1187
|
+
|
1188
|
+
do_denormalize = [True] * image.shape[0]
|
1189
|
+
|
1190
|
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
1191
|
+
|
1192
|
+
if padding_mask_crop is not None:
|
1193
|
+
image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
|
1194
|
+
|
1195
|
+
# Offload all models
|
1196
|
+
self.maybe_free_model_hooks()
|
1197
|
+
|
1198
|
+
if not return_dict:
|
1199
|
+
return (image,)
|
1200
|
+
|
1201
|
+
return StableDiffusion3PipelineOutput(images=image)
|