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,1247 @@
|
|
1
|
+
# Copyright 2024 Stability AI, Kwai-Kolors Team 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
|
+
import inspect
|
15
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
16
|
+
|
17
|
+
import PIL.Image
|
18
|
+
import torch
|
19
|
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
20
|
+
|
21
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
22
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
23
|
+
from ...loaders import IPAdapterMixin, StableDiffusionXLLoraLoaderMixin
|
24
|
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
25
|
+
from ...models.attention_processor import AttnProcessor2_0, FusedAttnProcessor2_0, XFormersAttnProcessor
|
26
|
+
from ...schedulers import KarrasDiffusionSchedulers
|
27
|
+
from ...utils import is_torch_xla_available, logging, replace_example_docstring
|
28
|
+
from ...utils.torch_utils import randn_tensor
|
29
|
+
from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
30
|
+
from .pipeline_output import KolorsPipelineOutput
|
31
|
+
from .text_encoder import ChatGLMModel
|
32
|
+
from .tokenizer import ChatGLMTokenizer
|
33
|
+
|
34
|
+
|
35
|
+
if is_torch_xla_available():
|
36
|
+
import torch_xla.core.xla_model as xm
|
37
|
+
|
38
|
+
XLA_AVAILABLE = True
|
39
|
+
else:
|
40
|
+
XLA_AVAILABLE = False
|
41
|
+
|
42
|
+
|
43
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
44
|
+
|
45
|
+
|
46
|
+
EXAMPLE_DOC_STRING = """
|
47
|
+
Examples:
|
48
|
+
```py
|
49
|
+
>>> import torch
|
50
|
+
>>> from diffusers import KolorsImg2ImgPipeline
|
51
|
+
>>> from diffusers.utils import load_image
|
52
|
+
|
53
|
+
>>> pipe = KolorsImg2ImgPipeline.from_pretrained(
|
54
|
+
... "Kwai-Kolors/Kolors-diffusers", variant="fp16", torch_dtype=torch.float16
|
55
|
+
... )
|
56
|
+
>>> pipe = pipe.to("cuda")
|
57
|
+
>>> url = (
|
58
|
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/kolors/bunny_source.png"
|
59
|
+
... )
|
60
|
+
|
61
|
+
|
62
|
+
>>> init_image = load_image(url)
|
63
|
+
>>> prompt = "high quality image of a capybara wearing sunglasses. In the background of the image there are trees, poles, grass and other objects. At the bottom of the object there is the road., 8k, highly detailed."
|
64
|
+
>>> image = pipe(prompt, image=init_image).images[0]
|
65
|
+
```
|
66
|
+
"""
|
67
|
+
|
68
|
+
|
69
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
70
|
+
def retrieve_latents(
|
71
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
72
|
+
):
|
73
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
74
|
+
return encoder_output.latent_dist.sample(generator)
|
75
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
76
|
+
return encoder_output.latent_dist.mode()
|
77
|
+
elif hasattr(encoder_output, "latents"):
|
78
|
+
return encoder_output.latents
|
79
|
+
else:
|
80
|
+
raise AttributeError("Could not access latents of provided encoder_output")
|
81
|
+
|
82
|
+
|
83
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
84
|
+
def retrieve_timesteps(
|
85
|
+
scheduler,
|
86
|
+
num_inference_steps: Optional[int] = None,
|
87
|
+
device: Optional[Union[str, torch.device]] = None,
|
88
|
+
timesteps: Optional[List[int]] = None,
|
89
|
+
sigmas: Optional[List[float]] = None,
|
90
|
+
**kwargs,
|
91
|
+
):
|
92
|
+
"""
|
93
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
94
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
95
|
+
|
96
|
+
Args:
|
97
|
+
scheduler (`SchedulerMixin`):
|
98
|
+
The scheduler to get timesteps from.
|
99
|
+
num_inference_steps (`int`):
|
100
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
101
|
+
must be `None`.
|
102
|
+
device (`str` or `torch.device`, *optional*):
|
103
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
104
|
+
timesteps (`List[int]`, *optional*):
|
105
|
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
106
|
+
`num_inference_steps` and `sigmas` must be `None`.
|
107
|
+
sigmas (`List[float]`, *optional*):
|
108
|
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
109
|
+
`num_inference_steps` and `timesteps` must be `None`.
|
110
|
+
|
111
|
+
Returns:
|
112
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
113
|
+
second element is the number of inference steps.
|
114
|
+
"""
|
115
|
+
if timesteps is not None and sigmas is not None:
|
116
|
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
117
|
+
if timesteps is not None:
|
118
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
119
|
+
if not accepts_timesteps:
|
120
|
+
raise ValueError(
|
121
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
122
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
123
|
+
)
|
124
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
125
|
+
timesteps = scheduler.timesteps
|
126
|
+
num_inference_steps = len(timesteps)
|
127
|
+
elif sigmas is not None:
|
128
|
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
129
|
+
if not accept_sigmas:
|
130
|
+
raise ValueError(
|
131
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
132
|
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
133
|
+
)
|
134
|
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
135
|
+
timesteps = scheduler.timesteps
|
136
|
+
num_inference_steps = len(timesteps)
|
137
|
+
else:
|
138
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
139
|
+
timesteps = scheduler.timesteps
|
140
|
+
return timesteps, num_inference_steps
|
141
|
+
|
142
|
+
|
143
|
+
class KolorsImg2ImgPipeline(DiffusionPipeline, StableDiffusionMixin, StableDiffusionXLLoraLoaderMixin, IPAdapterMixin):
|
144
|
+
r"""
|
145
|
+
Pipeline for text-to-image generation using Kolors.
|
146
|
+
|
147
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
148
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
149
|
+
|
150
|
+
The pipeline also inherits the following loading methods:
|
151
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
152
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
153
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
154
|
+
|
155
|
+
Args:
|
156
|
+
vae ([`AutoencoderKL`]):
|
157
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
158
|
+
text_encoder ([`ChatGLMModel`]):
|
159
|
+
Frozen text-encoder. Kolors uses [ChatGLM3-6B](https://huggingface.co/THUDM/chatglm3-6b).
|
160
|
+
tokenizer (`ChatGLMTokenizer`):
|
161
|
+
Tokenizer of class
|
162
|
+
[ChatGLMTokenizer](https://huggingface.co/THUDM/chatglm3-6b/blob/main/tokenization_chatglm.py).
|
163
|
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
164
|
+
scheduler ([`SchedulerMixin`]):
|
165
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
166
|
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
167
|
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"False"`):
|
168
|
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
169
|
+
`Kwai-Kolors/Kolors-diffusers`.
|
170
|
+
"""
|
171
|
+
|
172
|
+
model_cpu_offload_seq = "text_encoder->image_encoder-unet->vae"
|
173
|
+
_optional_components = [
|
174
|
+
"image_encoder",
|
175
|
+
"feature_extractor",
|
176
|
+
]
|
177
|
+
_callback_tensor_inputs = [
|
178
|
+
"latents",
|
179
|
+
"prompt_embeds",
|
180
|
+
"negative_prompt_embeds",
|
181
|
+
"add_text_embeds",
|
182
|
+
"add_time_ids",
|
183
|
+
"negative_pooled_prompt_embeds",
|
184
|
+
"negative_add_time_ids",
|
185
|
+
]
|
186
|
+
|
187
|
+
def __init__(
|
188
|
+
self,
|
189
|
+
vae: AutoencoderKL,
|
190
|
+
text_encoder: ChatGLMModel,
|
191
|
+
tokenizer: ChatGLMTokenizer,
|
192
|
+
unet: UNet2DConditionModel,
|
193
|
+
scheduler: KarrasDiffusionSchedulers,
|
194
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
195
|
+
feature_extractor: CLIPImageProcessor = None,
|
196
|
+
force_zeros_for_empty_prompt: bool = False,
|
197
|
+
):
|
198
|
+
super().__init__()
|
199
|
+
|
200
|
+
self.register_modules(
|
201
|
+
vae=vae,
|
202
|
+
text_encoder=text_encoder,
|
203
|
+
tokenizer=tokenizer,
|
204
|
+
unet=unet,
|
205
|
+
scheduler=scheduler,
|
206
|
+
image_encoder=image_encoder,
|
207
|
+
feature_extractor=feature_extractor,
|
208
|
+
)
|
209
|
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
210
|
+
self.vae_scale_factor = (
|
211
|
+
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
|
212
|
+
)
|
213
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
214
|
+
|
215
|
+
self.default_sample_size = self.unet.config.sample_size
|
216
|
+
|
217
|
+
# Copied from diffusers.pipelines.kolors.pipeline_kolors.KolorsPipeline.encode_prompt
|
218
|
+
def encode_prompt(
|
219
|
+
self,
|
220
|
+
prompt,
|
221
|
+
device: Optional[torch.device] = None,
|
222
|
+
num_images_per_prompt: int = 1,
|
223
|
+
do_classifier_free_guidance: bool = True,
|
224
|
+
negative_prompt=None,
|
225
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
226
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
227
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
228
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
229
|
+
max_sequence_length: int = 256,
|
230
|
+
):
|
231
|
+
r"""
|
232
|
+
Encodes the prompt into text encoder hidden states.
|
233
|
+
|
234
|
+
Args:
|
235
|
+
prompt (`str` or `List[str]`, *optional*):
|
236
|
+
prompt to be encoded
|
237
|
+
device: (`torch.device`):
|
238
|
+
torch device
|
239
|
+
num_images_per_prompt (`int`):
|
240
|
+
number of images that should be generated per prompt
|
241
|
+
do_classifier_free_guidance (`bool`):
|
242
|
+
whether to use classifier free guidance or not
|
243
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
244
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
245
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
246
|
+
less than `1`).
|
247
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
248
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
249
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
250
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
251
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
252
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
253
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
254
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
255
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
256
|
+
argument.
|
257
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
258
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
259
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
260
|
+
input argument.
|
261
|
+
max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
|
262
|
+
"""
|
263
|
+
# from IPython import embed; embed(); exit()
|
264
|
+
device = device or self._execution_device
|
265
|
+
|
266
|
+
if prompt is not None and isinstance(prompt, str):
|
267
|
+
batch_size = 1
|
268
|
+
elif prompt is not None and isinstance(prompt, list):
|
269
|
+
batch_size = len(prompt)
|
270
|
+
else:
|
271
|
+
batch_size = prompt_embeds.shape[0]
|
272
|
+
|
273
|
+
# Define tokenizers and text encoders
|
274
|
+
tokenizers = [self.tokenizer]
|
275
|
+
text_encoders = [self.text_encoder]
|
276
|
+
|
277
|
+
if prompt_embeds is None:
|
278
|
+
prompt_embeds_list = []
|
279
|
+
for tokenizer, text_encoder in zip(tokenizers, text_encoders):
|
280
|
+
text_inputs = tokenizer(
|
281
|
+
prompt,
|
282
|
+
padding="max_length",
|
283
|
+
max_length=max_sequence_length,
|
284
|
+
truncation=True,
|
285
|
+
return_tensors="pt",
|
286
|
+
).to(device)
|
287
|
+
output = text_encoder(
|
288
|
+
input_ids=text_inputs["input_ids"],
|
289
|
+
attention_mask=text_inputs["attention_mask"],
|
290
|
+
position_ids=text_inputs["position_ids"],
|
291
|
+
output_hidden_states=True,
|
292
|
+
)
|
293
|
+
|
294
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, max_sequence_length, hidden_size]
|
295
|
+
# clone to have a contiguous tensor
|
296
|
+
prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
|
297
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, hidden_size]
|
298
|
+
pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone()
|
299
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
300
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
301
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
302
|
+
|
303
|
+
prompt_embeds_list.append(prompt_embeds)
|
304
|
+
|
305
|
+
prompt_embeds = prompt_embeds_list[0]
|
306
|
+
|
307
|
+
# get unconditional embeddings for classifier free guidance
|
308
|
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
309
|
+
|
310
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
311
|
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
312
|
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
313
|
+
uncond_tokens: List[str]
|
314
|
+
if negative_prompt is None:
|
315
|
+
uncond_tokens = [""] * batch_size
|
316
|
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
317
|
+
raise TypeError(
|
318
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
319
|
+
f" {type(prompt)}."
|
320
|
+
)
|
321
|
+
elif isinstance(negative_prompt, str):
|
322
|
+
uncond_tokens = [negative_prompt]
|
323
|
+
elif batch_size != len(negative_prompt):
|
324
|
+
raise ValueError(
|
325
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
326
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
327
|
+
" the batch size of `prompt`."
|
328
|
+
)
|
329
|
+
else:
|
330
|
+
uncond_tokens = negative_prompt
|
331
|
+
|
332
|
+
negative_prompt_embeds_list = []
|
333
|
+
|
334
|
+
for tokenizer, text_encoder in zip(tokenizers, text_encoders):
|
335
|
+
uncond_input = tokenizer(
|
336
|
+
uncond_tokens,
|
337
|
+
padding="max_length",
|
338
|
+
max_length=max_sequence_length,
|
339
|
+
truncation=True,
|
340
|
+
return_tensors="pt",
|
341
|
+
).to(device)
|
342
|
+
output = text_encoder(
|
343
|
+
input_ids=uncond_input["input_ids"],
|
344
|
+
attention_mask=uncond_input["attention_mask"],
|
345
|
+
position_ids=uncond_input["position_ids"],
|
346
|
+
output_hidden_states=True,
|
347
|
+
)
|
348
|
+
|
349
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, max_sequence_length, hidden_size]
|
350
|
+
# clone to have a contiguous tensor
|
351
|
+
negative_prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
|
352
|
+
# [max_sequence_length, batch, hidden_size] -> [batch, hidden_size]
|
353
|
+
negative_pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone()
|
354
|
+
|
355
|
+
if do_classifier_free_guidance:
|
356
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
357
|
+
seq_len = negative_prompt_embeds.shape[1]
|
358
|
+
|
359
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=text_encoder.dtype, device=device)
|
360
|
+
|
361
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
362
|
+
negative_prompt_embeds = negative_prompt_embeds.view(
|
363
|
+
batch_size * num_images_per_prompt, seq_len, -1
|
364
|
+
)
|
365
|
+
|
366
|
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
367
|
+
|
368
|
+
negative_prompt_embeds = negative_prompt_embeds_list[0]
|
369
|
+
|
370
|
+
bs_embed = pooled_prompt_embeds.shape[0]
|
371
|
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
372
|
+
bs_embed * num_images_per_prompt, -1
|
373
|
+
)
|
374
|
+
|
375
|
+
if do_classifier_free_guidance:
|
376
|
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
377
|
+
bs_embed * num_images_per_prompt, -1
|
378
|
+
)
|
379
|
+
|
380
|
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
381
|
+
|
382
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
383
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
384
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
385
|
+
|
386
|
+
if not isinstance(image, torch.Tensor):
|
387
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
388
|
+
|
389
|
+
image = image.to(device=device, dtype=dtype)
|
390
|
+
if output_hidden_states:
|
391
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
392
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
393
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
394
|
+
torch.zeros_like(image), output_hidden_states=True
|
395
|
+
).hidden_states[-2]
|
396
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
397
|
+
num_images_per_prompt, dim=0
|
398
|
+
)
|
399
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
400
|
+
else:
|
401
|
+
image_embeds = self.image_encoder(image).image_embeds
|
402
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
403
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
404
|
+
|
405
|
+
return image_embeds, uncond_image_embeds
|
406
|
+
|
407
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
408
|
+
def prepare_ip_adapter_image_embeds(
|
409
|
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
410
|
+
):
|
411
|
+
image_embeds = []
|
412
|
+
if do_classifier_free_guidance:
|
413
|
+
negative_image_embeds = []
|
414
|
+
if ip_adapter_image_embeds is None:
|
415
|
+
if not isinstance(ip_adapter_image, list):
|
416
|
+
ip_adapter_image = [ip_adapter_image]
|
417
|
+
|
418
|
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
419
|
+
raise ValueError(
|
420
|
+
f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
|
421
|
+
)
|
422
|
+
|
423
|
+
for single_ip_adapter_image, image_proj_layer in zip(
|
424
|
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
425
|
+
):
|
426
|
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
427
|
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
428
|
+
single_ip_adapter_image, device, 1, output_hidden_state
|
429
|
+
)
|
430
|
+
|
431
|
+
image_embeds.append(single_image_embeds[None, :])
|
432
|
+
if do_classifier_free_guidance:
|
433
|
+
negative_image_embeds.append(single_negative_image_embeds[None, :])
|
434
|
+
else:
|
435
|
+
for single_image_embeds in ip_adapter_image_embeds:
|
436
|
+
if do_classifier_free_guidance:
|
437
|
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
438
|
+
negative_image_embeds.append(single_negative_image_embeds)
|
439
|
+
image_embeds.append(single_image_embeds)
|
440
|
+
|
441
|
+
ip_adapter_image_embeds = []
|
442
|
+
for i, single_image_embeds in enumerate(image_embeds):
|
443
|
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
444
|
+
if do_classifier_free_guidance:
|
445
|
+
single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
|
446
|
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
|
447
|
+
|
448
|
+
single_image_embeds = single_image_embeds.to(device=device)
|
449
|
+
ip_adapter_image_embeds.append(single_image_embeds)
|
450
|
+
|
451
|
+
return ip_adapter_image_embeds
|
452
|
+
|
453
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
454
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
455
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
456
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
457
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
458
|
+
# and should be between [0, 1]
|
459
|
+
|
460
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
461
|
+
extra_step_kwargs = {}
|
462
|
+
if accepts_eta:
|
463
|
+
extra_step_kwargs["eta"] = eta
|
464
|
+
|
465
|
+
# check if the scheduler accepts generator
|
466
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
467
|
+
if accepts_generator:
|
468
|
+
extra_step_kwargs["generator"] = generator
|
469
|
+
return extra_step_kwargs
|
470
|
+
|
471
|
+
def check_inputs(
|
472
|
+
self,
|
473
|
+
prompt,
|
474
|
+
strength,
|
475
|
+
num_inference_steps,
|
476
|
+
height,
|
477
|
+
width,
|
478
|
+
negative_prompt=None,
|
479
|
+
prompt_embeds=None,
|
480
|
+
pooled_prompt_embeds=None,
|
481
|
+
negative_prompt_embeds=None,
|
482
|
+
negative_pooled_prompt_embeds=None,
|
483
|
+
ip_adapter_image=None,
|
484
|
+
ip_adapter_image_embeds=None,
|
485
|
+
callback_on_step_end_tensor_inputs=None,
|
486
|
+
max_sequence_length=None,
|
487
|
+
):
|
488
|
+
if strength < 0 or strength > 1:
|
489
|
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
490
|
+
|
491
|
+
if not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
|
492
|
+
raise ValueError(
|
493
|
+
f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
|
494
|
+
f" {type(num_inference_steps)}."
|
495
|
+
)
|
496
|
+
|
497
|
+
if height % 8 != 0 or width % 8 != 0:
|
498
|
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
499
|
+
|
500
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
501
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
502
|
+
):
|
503
|
+
raise ValueError(
|
504
|
+
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]}"
|
505
|
+
)
|
506
|
+
|
507
|
+
if prompt is not None and prompt_embeds is not None:
|
508
|
+
raise ValueError(
|
509
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
510
|
+
" only forward one of the two."
|
511
|
+
)
|
512
|
+
elif prompt is None and prompt_embeds is None:
|
513
|
+
raise ValueError(
|
514
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
515
|
+
)
|
516
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
517
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
518
|
+
|
519
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
520
|
+
raise ValueError(
|
521
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
522
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
523
|
+
)
|
524
|
+
|
525
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
526
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
527
|
+
raise ValueError(
|
528
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
529
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
530
|
+
f" {negative_prompt_embeds.shape}."
|
531
|
+
)
|
532
|
+
|
533
|
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
534
|
+
raise ValueError(
|
535
|
+
"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`."
|
536
|
+
)
|
537
|
+
|
538
|
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
539
|
+
raise ValueError(
|
540
|
+
"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`."
|
541
|
+
)
|
542
|
+
|
543
|
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
544
|
+
raise ValueError(
|
545
|
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
546
|
+
)
|
547
|
+
|
548
|
+
if ip_adapter_image_embeds is not None:
|
549
|
+
if not isinstance(ip_adapter_image_embeds, list):
|
550
|
+
raise ValueError(
|
551
|
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
552
|
+
)
|
553
|
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
554
|
+
raise ValueError(
|
555
|
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
556
|
+
)
|
557
|
+
|
558
|
+
if max_sequence_length is not None and max_sequence_length > 256:
|
559
|
+
raise ValueError(f"`max_sequence_length` cannot be greater than 256 but is {max_sequence_length}")
|
560
|
+
|
561
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps
|
562
|
+
def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
|
563
|
+
# get the original timestep using init_timestep
|
564
|
+
if denoising_start is None:
|
565
|
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
566
|
+
t_start = max(num_inference_steps - init_timestep, 0)
|
567
|
+
else:
|
568
|
+
t_start = 0
|
569
|
+
|
570
|
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
571
|
+
|
572
|
+
# Strength is irrelevant if we directly request a timestep to start at;
|
573
|
+
# that is, strength is determined by the denoising_start instead.
|
574
|
+
if denoising_start is not None:
|
575
|
+
discrete_timestep_cutoff = int(
|
576
|
+
round(
|
577
|
+
self.scheduler.config.num_train_timesteps
|
578
|
+
- (denoising_start * self.scheduler.config.num_train_timesteps)
|
579
|
+
)
|
580
|
+
)
|
581
|
+
|
582
|
+
num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
|
583
|
+
if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
|
584
|
+
# if the scheduler is a 2nd order scheduler we might have to do +1
|
585
|
+
# because `num_inference_steps` might be even given that every timestep
|
586
|
+
# (except the highest one) is duplicated. If `num_inference_steps` is even it would
|
587
|
+
# mean that we cut the timesteps in the middle of the denoising step
|
588
|
+
# (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
|
589
|
+
# we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
|
590
|
+
num_inference_steps = num_inference_steps + 1
|
591
|
+
|
592
|
+
# because t_n+1 >= t_n, we slice the timesteps starting from the end
|
593
|
+
timesteps = timesteps[-num_inference_steps:]
|
594
|
+
return timesteps, num_inference_steps
|
595
|
+
|
596
|
+
return timesteps, num_inference_steps - t_start
|
597
|
+
|
598
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.prepare_latents
|
599
|
+
def prepare_latents(
|
600
|
+
self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
|
601
|
+
):
|
602
|
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
603
|
+
raise ValueError(
|
604
|
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
605
|
+
)
|
606
|
+
|
607
|
+
latents_mean = latents_std = None
|
608
|
+
if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
|
609
|
+
latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
|
610
|
+
if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
|
611
|
+
latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
|
612
|
+
|
613
|
+
# Offload text encoder if `enable_model_cpu_offload` was enabled
|
614
|
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
615
|
+
self.text_encoder_2.to("cpu")
|
616
|
+
torch.cuda.empty_cache()
|
617
|
+
|
618
|
+
image = image.to(device=device, dtype=dtype)
|
619
|
+
|
620
|
+
batch_size = batch_size * num_images_per_prompt
|
621
|
+
|
622
|
+
if image.shape[1] == 4:
|
623
|
+
init_latents = image
|
624
|
+
|
625
|
+
else:
|
626
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
627
|
+
if self.vae.config.force_upcast:
|
628
|
+
image = image.float()
|
629
|
+
self.vae.to(dtype=torch.float32)
|
630
|
+
|
631
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
632
|
+
raise ValueError(
|
633
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
634
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
635
|
+
)
|
636
|
+
|
637
|
+
elif isinstance(generator, list):
|
638
|
+
if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
|
639
|
+
image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
|
640
|
+
elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
|
641
|
+
raise ValueError(
|
642
|
+
f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
|
643
|
+
)
|
644
|
+
|
645
|
+
init_latents = [
|
646
|
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
647
|
+
for i in range(batch_size)
|
648
|
+
]
|
649
|
+
init_latents = torch.cat(init_latents, dim=0)
|
650
|
+
else:
|
651
|
+
init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
652
|
+
|
653
|
+
if self.vae.config.force_upcast:
|
654
|
+
self.vae.to(dtype)
|
655
|
+
|
656
|
+
init_latents = init_latents.to(dtype)
|
657
|
+
if latents_mean is not None and latents_std is not None:
|
658
|
+
latents_mean = latents_mean.to(device=device, dtype=dtype)
|
659
|
+
latents_std = latents_std.to(device=device, dtype=dtype)
|
660
|
+
init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
|
661
|
+
else:
|
662
|
+
init_latents = self.vae.config.scaling_factor * init_latents
|
663
|
+
|
664
|
+
if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
|
665
|
+
# expand init_latents for batch_size
|
666
|
+
additional_image_per_prompt = batch_size // init_latents.shape[0]
|
667
|
+
init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
|
668
|
+
elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
|
669
|
+
raise ValueError(
|
670
|
+
f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
|
671
|
+
)
|
672
|
+
else:
|
673
|
+
init_latents = torch.cat([init_latents], dim=0)
|
674
|
+
|
675
|
+
if add_noise:
|
676
|
+
shape = init_latents.shape
|
677
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
678
|
+
# get latents
|
679
|
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
680
|
+
|
681
|
+
latents = init_latents
|
682
|
+
|
683
|
+
return latents
|
684
|
+
|
685
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
|
686
|
+
def _get_add_time_ids(
|
687
|
+
self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
|
688
|
+
):
|
689
|
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
690
|
+
|
691
|
+
passed_add_embed_dim = (
|
692
|
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
|
693
|
+
)
|
694
|
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
695
|
+
|
696
|
+
if expected_add_embed_dim != passed_add_embed_dim:
|
697
|
+
raise ValueError(
|
698
|
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
699
|
+
)
|
700
|
+
|
701
|
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
702
|
+
return add_time_ids
|
703
|
+
|
704
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.upcast_vae
|
705
|
+
def upcast_vae(self):
|
706
|
+
dtype = self.vae.dtype
|
707
|
+
self.vae.to(dtype=torch.float32)
|
708
|
+
use_torch_2_0_or_xformers = isinstance(
|
709
|
+
self.vae.decoder.mid_block.attentions[0].processor,
|
710
|
+
(
|
711
|
+
AttnProcessor2_0,
|
712
|
+
XFormersAttnProcessor,
|
713
|
+
FusedAttnProcessor2_0,
|
714
|
+
),
|
715
|
+
)
|
716
|
+
# if xformers or torch_2_0 is used attention block does not need
|
717
|
+
# to be in float32 which can save lots of memory
|
718
|
+
if use_torch_2_0_or_xformers:
|
719
|
+
self.vae.post_quant_conv.to(dtype)
|
720
|
+
self.vae.decoder.conv_in.to(dtype)
|
721
|
+
self.vae.decoder.mid_block.to(dtype)
|
722
|
+
|
723
|
+
# Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
|
724
|
+
def get_guidance_scale_embedding(
|
725
|
+
self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
|
726
|
+
) -> torch.Tensor:
|
727
|
+
"""
|
728
|
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
729
|
+
|
730
|
+
Args:
|
731
|
+
w (`torch.Tensor`):
|
732
|
+
Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
|
733
|
+
embedding_dim (`int`, *optional*, defaults to 512):
|
734
|
+
Dimension of the embeddings to generate.
|
735
|
+
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
|
736
|
+
Data type of the generated embeddings.
|
737
|
+
|
738
|
+
Returns:
|
739
|
+
`torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
|
740
|
+
"""
|
741
|
+
assert len(w.shape) == 1
|
742
|
+
w = w * 1000.0
|
743
|
+
|
744
|
+
half_dim = embedding_dim // 2
|
745
|
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
746
|
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
747
|
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
748
|
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
749
|
+
if embedding_dim % 2 == 1: # zero pad
|
750
|
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
751
|
+
assert emb.shape == (w.shape[0], embedding_dim)
|
752
|
+
return emb
|
753
|
+
|
754
|
+
@property
|
755
|
+
def guidance_scale(self):
|
756
|
+
return self._guidance_scale
|
757
|
+
|
758
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
759
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
760
|
+
# corresponds to doing no classifier free guidance.
|
761
|
+
@property
|
762
|
+
def do_classifier_free_guidance(self):
|
763
|
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
764
|
+
|
765
|
+
@property
|
766
|
+
def cross_attention_kwargs(self):
|
767
|
+
return self._cross_attention_kwargs
|
768
|
+
|
769
|
+
@property
|
770
|
+
def denoising_start(self):
|
771
|
+
return self._denoising_start
|
772
|
+
|
773
|
+
@property
|
774
|
+
def denoising_end(self):
|
775
|
+
return self._denoising_end
|
776
|
+
|
777
|
+
@property
|
778
|
+
def num_timesteps(self):
|
779
|
+
return self._num_timesteps
|
780
|
+
|
781
|
+
@property
|
782
|
+
def interrupt(self):
|
783
|
+
return self._interrupt
|
784
|
+
|
785
|
+
@torch.no_grad()
|
786
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
787
|
+
def __call__(
|
788
|
+
self,
|
789
|
+
prompt: Union[str, List[str]] = None,
|
790
|
+
image: PipelineImageInput = None,
|
791
|
+
strength: float = 0.3,
|
792
|
+
height: Optional[int] = None,
|
793
|
+
width: Optional[int] = None,
|
794
|
+
num_inference_steps: int = 50,
|
795
|
+
timesteps: List[int] = None,
|
796
|
+
sigmas: List[float] = None,
|
797
|
+
denoising_start: Optional[float] = None,
|
798
|
+
denoising_end: Optional[float] = None,
|
799
|
+
guidance_scale: float = 5.0,
|
800
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
801
|
+
num_images_per_prompt: Optional[int] = 1,
|
802
|
+
eta: float = 0.0,
|
803
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
804
|
+
latents: Optional[torch.Tensor] = None,
|
805
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
806
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
807
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
808
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
809
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
810
|
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
811
|
+
output_type: Optional[str] = "pil",
|
812
|
+
return_dict: bool = True,
|
813
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
814
|
+
original_size: Optional[Tuple[int, int]] = None,
|
815
|
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
816
|
+
target_size: Optional[Tuple[int, int]] = None,
|
817
|
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
818
|
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
819
|
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
820
|
+
callback_on_step_end: Optional[
|
821
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
822
|
+
] = None,
|
823
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
824
|
+
max_sequence_length: int = 256,
|
825
|
+
):
|
826
|
+
r"""
|
827
|
+
Function invoked when calling the pipeline for generation.
|
828
|
+
|
829
|
+
Args:
|
830
|
+
prompt (`str` or `List[str]`, *optional*):
|
831
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
832
|
+
instead.
|
833
|
+
image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
|
834
|
+
The image(s) to modify with the pipeline.
|
835
|
+
strength (`float`, *optional*, defaults to 0.3):
|
836
|
+
Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
|
837
|
+
will be used as a starting point, adding more noise to it the larger the `strength`. The number of
|
838
|
+
denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
|
839
|
+
be maximum and the denoising process will run for the full number of iterations specified in
|
840
|
+
`num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
|
841
|
+
`denoising_start` being declared as an integer, the value of `strength` will be ignored.
|
842
|
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
843
|
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
844
|
+
Anything below 512 pixels won't work well for
|
845
|
+
[Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) and checkpoints
|
846
|
+
that are not specifically fine-tuned on low resolutions.
|
847
|
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
848
|
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
849
|
+
Anything below 512 pixels won't work well for
|
850
|
+
[Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) and checkpoints
|
851
|
+
that are not specifically fine-tuned on low resolutions.
|
852
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
853
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
854
|
+
expense of slower inference.
|
855
|
+
timesteps (`List[int]`, *optional*):
|
856
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
857
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
858
|
+
passed will be used. Must be in descending order.
|
859
|
+
sigmas (`List[float]`, *optional*):
|
860
|
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
861
|
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
862
|
+
will be used.
|
863
|
+
denoising_start (`float`, *optional*):
|
864
|
+
When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
|
865
|
+
bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
|
866
|
+
it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
|
867
|
+
strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
|
868
|
+
is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refine Image
|
869
|
+
Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
|
870
|
+
denoising_end (`float`, *optional*):
|
871
|
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
872
|
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
873
|
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
874
|
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
875
|
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
876
|
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
877
|
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
878
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
879
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
880
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
881
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
882
|
+
usually at the expense of lower image quality.
|
883
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
884
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
885
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
886
|
+
less than `1`).
|
887
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
888
|
+
The number of images to generate per prompt.
|
889
|
+
eta (`float`, *optional*, defaults to 0.0):
|
890
|
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
891
|
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
892
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
893
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
894
|
+
to make generation deterministic.
|
895
|
+
latents (`torch.Tensor`, *optional*):
|
896
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
897
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
898
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
899
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
900
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
901
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
902
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
903
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
904
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
905
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
906
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
907
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
908
|
+
argument.
|
909
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
910
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
911
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
912
|
+
input argument.
|
913
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
914
|
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
915
|
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
916
|
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
917
|
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
918
|
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
919
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
920
|
+
The output format of the generate image. Choose between
|
921
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
922
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
923
|
+
Whether or not to return a [`~pipelines.kolors.KolorsPipelineOutput`] instead of a plain tuple.
|
924
|
+
cross_attention_kwargs (`dict`, *optional*):
|
925
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
926
|
+
`self.processor` in
|
927
|
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
928
|
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
929
|
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
930
|
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
931
|
+
explained in section 2.2 of
|
932
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
933
|
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
934
|
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
935
|
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
936
|
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
937
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
938
|
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
939
|
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
940
|
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
941
|
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
942
|
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
943
|
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
944
|
+
micro-conditioning as explained in section 2.2 of
|
945
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
946
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
947
|
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
948
|
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
949
|
+
micro-conditioning as explained in section 2.2 of
|
950
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
951
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
952
|
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
953
|
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
954
|
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
955
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
956
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
957
|
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
958
|
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
959
|
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
960
|
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
961
|
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
962
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
963
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
964
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
965
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
966
|
+
max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
|
967
|
+
|
968
|
+
Examples:
|
969
|
+
|
970
|
+
Returns:
|
971
|
+
[`~pipelines.kolors.KolorsPipelineOutput`] or `tuple`: [`~pipelines.kolors.KolorsPipelineOutput`] if
|
972
|
+
`return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
|
973
|
+
generated images.
|
974
|
+
"""
|
975
|
+
|
976
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
977
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
978
|
+
|
979
|
+
# 0. Default height and width to unet
|
980
|
+
height = height or self.default_sample_size * self.vae_scale_factor
|
981
|
+
width = width or self.default_sample_size * self.vae_scale_factor
|
982
|
+
|
983
|
+
original_size = original_size or (height, width)
|
984
|
+
target_size = target_size or (height, width)
|
985
|
+
|
986
|
+
# 1. Check inputs. Raise error if not correct
|
987
|
+
self.check_inputs(
|
988
|
+
prompt,
|
989
|
+
strength,
|
990
|
+
num_inference_steps,
|
991
|
+
height,
|
992
|
+
width,
|
993
|
+
negative_prompt,
|
994
|
+
prompt_embeds,
|
995
|
+
pooled_prompt_embeds,
|
996
|
+
negative_prompt_embeds,
|
997
|
+
negative_pooled_prompt_embeds,
|
998
|
+
ip_adapter_image,
|
999
|
+
ip_adapter_image_embeds,
|
1000
|
+
callback_on_step_end_tensor_inputs,
|
1001
|
+
max_sequence_length=max_sequence_length,
|
1002
|
+
)
|
1003
|
+
|
1004
|
+
self._guidance_scale = guidance_scale
|
1005
|
+
self._cross_attention_kwargs = cross_attention_kwargs
|
1006
|
+
self._denoising_end = denoising_end
|
1007
|
+
self._denoising_start = denoising_start
|
1008
|
+
self._interrupt = False
|
1009
|
+
|
1010
|
+
# 2. Define call parameters
|
1011
|
+
if prompt is not None and isinstance(prompt, str):
|
1012
|
+
batch_size = 1
|
1013
|
+
elif prompt is not None and isinstance(prompt, list):
|
1014
|
+
batch_size = len(prompt)
|
1015
|
+
else:
|
1016
|
+
batch_size = prompt_embeds.shape[0]
|
1017
|
+
|
1018
|
+
device = self._execution_device
|
1019
|
+
|
1020
|
+
# 3. Encode input prompt
|
1021
|
+
(
|
1022
|
+
prompt_embeds,
|
1023
|
+
negative_prompt_embeds,
|
1024
|
+
pooled_prompt_embeds,
|
1025
|
+
negative_pooled_prompt_embeds,
|
1026
|
+
) = self.encode_prompt(
|
1027
|
+
prompt=prompt,
|
1028
|
+
device=device,
|
1029
|
+
num_images_per_prompt=num_images_per_prompt,
|
1030
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1031
|
+
negative_prompt=negative_prompt,
|
1032
|
+
prompt_embeds=prompt_embeds,
|
1033
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
1034
|
+
)
|
1035
|
+
|
1036
|
+
# 4. Preprocess image
|
1037
|
+
image = self.image_processor.preprocess(image)
|
1038
|
+
|
1039
|
+
# 5. Prepare timesteps
|
1040
|
+
def denoising_value_valid(dnv):
|
1041
|
+
return isinstance(dnv, float) and 0 < dnv < 1
|
1042
|
+
|
1043
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
1044
|
+
self.scheduler, num_inference_steps, device, timesteps, sigmas
|
1045
|
+
)
|
1046
|
+
|
1047
|
+
timesteps, num_inference_steps = self.get_timesteps(
|
1048
|
+
num_inference_steps,
|
1049
|
+
strength,
|
1050
|
+
device,
|
1051
|
+
denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
|
1052
|
+
)
|
1053
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
1054
|
+
|
1055
|
+
add_noise = True if self.denoising_start is None else False
|
1056
|
+
|
1057
|
+
# 6. Prepare latent variables
|
1058
|
+
if latents is None:
|
1059
|
+
latents = self.prepare_latents(
|
1060
|
+
image,
|
1061
|
+
latent_timestep,
|
1062
|
+
batch_size,
|
1063
|
+
num_images_per_prompt,
|
1064
|
+
prompt_embeds.dtype,
|
1065
|
+
device,
|
1066
|
+
generator,
|
1067
|
+
add_noise,
|
1068
|
+
)
|
1069
|
+
|
1070
|
+
# 7. Prepare extra step kwargs.
|
1071
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1072
|
+
|
1073
|
+
height, width = latents.shape[-2:]
|
1074
|
+
height = height * self.vae_scale_factor
|
1075
|
+
width = width * self.vae_scale_factor
|
1076
|
+
|
1077
|
+
original_size = original_size or (height, width)
|
1078
|
+
target_size = target_size or (height, width)
|
1079
|
+
|
1080
|
+
# 8. Prepare added time ids & embeddings
|
1081
|
+
add_text_embeds = pooled_prompt_embeds
|
1082
|
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
1083
|
+
|
1084
|
+
add_time_ids = self._get_add_time_ids(
|
1085
|
+
original_size,
|
1086
|
+
crops_coords_top_left,
|
1087
|
+
target_size,
|
1088
|
+
dtype=prompt_embeds.dtype,
|
1089
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1090
|
+
)
|
1091
|
+
if negative_original_size is not None and negative_target_size is not None:
|
1092
|
+
negative_add_time_ids = self._get_add_time_ids(
|
1093
|
+
negative_original_size,
|
1094
|
+
negative_crops_coords_top_left,
|
1095
|
+
negative_target_size,
|
1096
|
+
dtype=prompt_embeds.dtype,
|
1097
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1098
|
+
)
|
1099
|
+
else:
|
1100
|
+
negative_add_time_ids = add_time_ids
|
1101
|
+
|
1102
|
+
if self.do_classifier_free_guidance:
|
1103
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1104
|
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
1105
|
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
1106
|
+
|
1107
|
+
prompt_embeds = prompt_embeds.to(device)
|
1108
|
+
add_text_embeds = add_text_embeds.to(device)
|
1109
|
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
1110
|
+
|
1111
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1112
|
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
1113
|
+
ip_adapter_image,
|
1114
|
+
ip_adapter_image_embeds,
|
1115
|
+
device,
|
1116
|
+
batch_size * num_images_per_prompt,
|
1117
|
+
self.do_classifier_free_guidance,
|
1118
|
+
)
|
1119
|
+
|
1120
|
+
# 9. Denoising loop
|
1121
|
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
1122
|
+
|
1123
|
+
# 9.1 Apply denoising_end
|
1124
|
+
if (
|
1125
|
+
self.denoising_end is not None
|
1126
|
+
and self.denoising_start is not None
|
1127
|
+
and denoising_value_valid(self.denoising_end)
|
1128
|
+
and denoising_value_valid(self.denoising_start)
|
1129
|
+
and self.denoising_start >= self.denoising_end
|
1130
|
+
):
|
1131
|
+
raise ValueError(
|
1132
|
+
f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
|
1133
|
+
+ f" {self.denoising_end} when using type float."
|
1134
|
+
)
|
1135
|
+
elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
|
1136
|
+
discrete_timestep_cutoff = int(
|
1137
|
+
round(
|
1138
|
+
self.scheduler.config.num_train_timesteps
|
1139
|
+
- (self.denoising_end * self.scheduler.config.num_train_timesteps)
|
1140
|
+
)
|
1141
|
+
)
|
1142
|
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
1143
|
+
timesteps = timesteps[:num_inference_steps]
|
1144
|
+
|
1145
|
+
# 9.2 Optionally get Guidance Scale Embedding
|
1146
|
+
timestep_cond = None
|
1147
|
+
if self.unet.config.time_cond_proj_dim is not None:
|
1148
|
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
1149
|
+
timestep_cond = self.get_guidance_scale_embedding(
|
1150
|
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
1151
|
+
).to(device=device, dtype=latents.dtype)
|
1152
|
+
|
1153
|
+
self._num_timesteps = len(timesteps)
|
1154
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1155
|
+
for i, t in enumerate(timesteps):
|
1156
|
+
if self.interrupt:
|
1157
|
+
continue
|
1158
|
+
|
1159
|
+
# expand the latents if we are doing classifier free guidance
|
1160
|
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1161
|
+
|
1162
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1163
|
+
|
1164
|
+
# predict the noise residual
|
1165
|
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
1166
|
+
|
1167
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1168
|
+
added_cond_kwargs["image_embeds"] = image_embeds
|
1169
|
+
|
1170
|
+
noise_pred = self.unet(
|
1171
|
+
latent_model_input,
|
1172
|
+
t,
|
1173
|
+
encoder_hidden_states=prompt_embeds,
|
1174
|
+
timestep_cond=timestep_cond,
|
1175
|
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
1176
|
+
added_cond_kwargs=added_cond_kwargs,
|
1177
|
+
return_dict=False,
|
1178
|
+
)[0]
|
1179
|
+
|
1180
|
+
# perform guidance
|
1181
|
+
if self.do_classifier_free_guidance:
|
1182
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1183
|
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1184
|
+
|
1185
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1186
|
+
latents_dtype = latents.dtype
|
1187
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1188
|
+
if latents.dtype != latents_dtype:
|
1189
|
+
if torch.backends.mps.is_available():
|
1190
|
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
1191
|
+
latents = latents.to(latents_dtype)
|
1192
|
+
|
1193
|
+
if callback_on_step_end is not None:
|
1194
|
+
callback_kwargs = {}
|
1195
|
+
for k in callback_on_step_end_tensor_inputs:
|
1196
|
+
callback_kwargs[k] = locals()[k]
|
1197
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1198
|
+
|
1199
|
+
latents = callback_outputs.pop("latents", latents)
|
1200
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1201
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1202
|
+
add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
|
1203
|
+
negative_pooled_prompt_embeds = callback_outputs.pop(
|
1204
|
+
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
1205
|
+
)
|
1206
|
+
add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
|
1207
|
+
negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
|
1208
|
+
|
1209
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1210
|
+
progress_bar.update()
|
1211
|
+
|
1212
|
+
if XLA_AVAILABLE:
|
1213
|
+
xm.mark_step()
|
1214
|
+
|
1215
|
+
if not output_type == "latent":
|
1216
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
1217
|
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1218
|
+
|
1219
|
+
if needs_upcasting:
|
1220
|
+
self.upcast_vae()
|
1221
|
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
1222
|
+
elif latents.dtype != self.vae.dtype:
|
1223
|
+
if torch.backends.mps.is_available():
|
1224
|
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
1225
|
+
self.vae = self.vae.to(latents.dtype)
|
1226
|
+
|
1227
|
+
# unscale/denormalize the latents
|
1228
|
+
latents = latents / self.vae.config.scaling_factor
|
1229
|
+
|
1230
|
+
image = self.vae.decode(latents, return_dict=False)[0]
|
1231
|
+
|
1232
|
+
# cast back to fp16 if needed
|
1233
|
+
if needs_upcasting:
|
1234
|
+
self.vae.to(dtype=torch.float16)
|
1235
|
+
else:
|
1236
|
+
image = latents
|
1237
|
+
|
1238
|
+
if not output_type == "latent":
|
1239
|
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1240
|
+
|
1241
|
+
# Offload all models
|
1242
|
+
self.maybe_free_model_hooks()
|
1243
|
+
|
1244
|
+
if not return_dict:
|
1245
|
+
return (image,)
|
1246
|
+
|
1247
|
+
return KolorsPipelineOutput(images=image)
|