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,1042 @@
|
|
1
|
+
# Copyright 2024 HunyuanDiT Authors 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, Tuple, Union
|
17
|
+
|
18
|
+
import numpy as np
|
19
|
+
import torch
|
20
|
+
from transformers import BertModel, BertTokenizer, CLIPImageProcessor, MT5Tokenizer, T5EncoderModel
|
21
|
+
|
22
|
+
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
|
23
|
+
|
24
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
25
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
26
|
+
from ...models import AutoencoderKL, HunyuanDiT2DControlNetModel, HunyuanDiT2DModel, HunyuanDiT2DMultiControlNetModel
|
27
|
+
from ...models.embeddings import get_2d_rotary_pos_embed
|
28
|
+
from ...pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
29
|
+
from ...schedulers import DDPMScheduler
|
30
|
+
from ...utils import (
|
31
|
+
is_torch_xla_available,
|
32
|
+
logging,
|
33
|
+
replace_example_docstring,
|
34
|
+
)
|
35
|
+
from ...utils.torch_utils import randn_tensor
|
36
|
+
from ..pipeline_utils import DiffusionPipeline
|
37
|
+
|
38
|
+
|
39
|
+
if is_torch_xla_available():
|
40
|
+
import torch_xla.core.xla_model as xm
|
41
|
+
|
42
|
+
XLA_AVAILABLE = True
|
43
|
+
else:
|
44
|
+
XLA_AVAILABLE = False
|
45
|
+
|
46
|
+
|
47
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
48
|
+
|
49
|
+
EXAMPLE_DOC_STRING = """
|
50
|
+
Examples:
|
51
|
+
```py
|
52
|
+
from diffusers import HunyuanDiT2DControlNetModel, HunyuanDiTControlNetPipeline
|
53
|
+
import torch
|
54
|
+
|
55
|
+
controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
|
56
|
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny", torch_dtype=torch.float16
|
57
|
+
)
|
58
|
+
|
59
|
+
pipe = HunyuanDiTControlNetPipeline.from_pretrained(
|
60
|
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
61
|
+
)
|
62
|
+
pipe.to("cuda")
|
63
|
+
|
64
|
+
from diffusers.utils import load_image
|
65
|
+
|
66
|
+
cond_image = load_image(
|
67
|
+
"https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny/resolve/main/canny.jpg?download=true"
|
68
|
+
)
|
69
|
+
|
70
|
+
## You may also use English prompt as HunyuanDiT supports both English and Chinese
|
71
|
+
prompt = "在夜晚的酒店门前,一座古老的中国风格的狮子雕像矗立着,它的眼睛闪烁着光芒,仿佛在守护着这座建筑。背景是夜晚的酒店前,构图方式是特写,平视,居中构图。这张照片呈现了真实摄影风格,蕴含了中国雕塑文化,同时展现了神秘氛围"
|
72
|
+
# prompt="At night, an ancient Chinese-style lion statue stands in front of the hotel, its eyes gleaming as if guarding the building. The background is the hotel entrance at night, with a close-up, eye-level, and centered composition. This photo presents a realistic photographic style, embodies Chinese sculpture culture, and reveals a mysterious atmosphere."
|
73
|
+
image = pipe(
|
74
|
+
prompt,
|
75
|
+
height=1024,
|
76
|
+
width=1024,
|
77
|
+
control_image=cond_image,
|
78
|
+
num_inference_steps=50,
|
79
|
+
).images[0]
|
80
|
+
```
|
81
|
+
"""
|
82
|
+
|
83
|
+
STANDARD_RATIO = np.array(
|
84
|
+
[
|
85
|
+
1.0, # 1:1
|
86
|
+
4.0 / 3.0, # 4:3
|
87
|
+
3.0 / 4.0, # 3:4
|
88
|
+
16.0 / 9.0, # 16:9
|
89
|
+
9.0 / 16.0, # 9:16
|
90
|
+
]
|
91
|
+
)
|
92
|
+
STANDARD_SHAPE = [
|
93
|
+
[(1024, 1024), (1280, 1280)], # 1:1
|
94
|
+
[(1024, 768), (1152, 864), (1280, 960)], # 4:3
|
95
|
+
[(768, 1024), (864, 1152), (960, 1280)], # 3:4
|
96
|
+
[(1280, 768)], # 16:9
|
97
|
+
[(768, 1280)], # 9:16
|
98
|
+
]
|
99
|
+
STANDARD_AREA = [np.array([w * h for w, h in shapes]) for shapes in STANDARD_SHAPE]
|
100
|
+
SUPPORTED_SHAPE = [
|
101
|
+
(1024, 1024),
|
102
|
+
(1280, 1280), # 1:1
|
103
|
+
(1024, 768),
|
104
|
+
(1152, 864),
|
105
|
+
(1280, 960), # 4:3
|
106
|
+
(768, 1024),
|
107
|
+
(864, 1152),
|
108
|
+
(960, 1280), # 3:4
|
109
|
+
(1280, 768), # 16:9
|
110
|
+
(768, 1280), # 9:16
|
111
|
+
]
|
112
|
+
|
113
|
+
|
114
|
+
def map_to_standard_shapes(target_width, target_height):
|
115
|
+
target_ratio = target_width / target_height
|
116
|
+
closest_ratio_idx = np.argmin(np.abs(STANDARD_RATIO - target_ratio))
|
117
|
+
closest_area_idx = np.argmin(np.abs(STANDARD_AREA[closest_ratio_idx] - target_width * target_height))
|
118
|
+
width, height = STANDARD_SHAPE[closest_ratio_idx][closest_area_idx]
|
119
|
+
return width, height
|
120
|
+
|
121
|
+
|
122
|
+
def get_resize_crop_region_for_grid(src, tgt_size):
|
123
|
+
th = tw = tgt_size
|
124
|
+
h, w = src
|
125
|
+
|
126
|
+
r = h / w
|
127
|
+
|
128
|
+
# resize
|
129
|
+
if r > 1:
|
130
|
+
resize_height = th
|
131
|
+
resize_width = int(round(th / h * w))
|
132
|
+
else:
|
133
|
+
resize_width = tw
|
134
|
+
resize_height = int(round(tw / w * h))
|
135
|
+
|
136
|
+
crop_top = int(round((th - resize_height) / 2.0))
|
137
|
+
crop_left = int(round((tw - resize_width) / 2.0))
|
138
|
+
|
139
|
+
return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
|
140
|
+
|
141
|
+
|
142
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
143
|
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
144
|
+
"""
|
145
|
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
146
|
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
147
|
+
"""
|
148
|
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
149
|
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
150
|
+
# rescale the results from guidance (fixes overexposure)
|
151
|
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
152
|
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
153
|
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
154
|
+
return noise_cfg
|
155
|
+
|
156
|
+
|
157
|
+
class HunyuanDiTControlNetPipeline(DiffusionPipeline):
|
158
|
+
r"""
|
159
|
+
Pipeline for English/Chinese-to-image generation using HunyuanDiT.
|
160
|
+
|
161
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
162
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
163
|
+
|
164
|
+
HunyuanDiT uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned by
|
165
|
+
ourselves)
|
166
|
+
|
167
|
+
Args:
|
168
|
+
vae ([`AutoencoderKL`]):
|
169
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. We use
|
170
|
+
`sdxl-vae-fp16-fix`.
|
171
|
+
text_encoder (Optional[`~transformers.BertModel`, `~transformers.CLIPTextModel`]):
|
172
|
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
173
|
+
HunyuanDiT uses a fine-tuned [bilingual CLIP].
|
174
|
+
tokenizer (Optional[`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer`]):
|
175
|
+
A `BertTokenizer` or `CLIPTokenizer` to tokenize text.
|
176
|
+
transformer ([`HunyuanDiT2DModel`]):
|
177
|
+
The HunyuanDiT model designed by Tencent Hunyuan.
|
178
|
+
text_encoder_2 (`T5EncoderModel`):
|
179
|
+
The mT5 embedder. Specifically, it is 't5-v1_1-xxl'.
|
180
|
+
tokenizer_2 (`MT5Tokenizer`):
|
181
|
+
The tokenizer for the mT5 embedder.
|
182
|
+
scheduler ([`DDPMScheduler`]):
|
183
|
+
A scheduler to be used in combination with HunyuanDiT to denoise the encoded image latents.
|
184
|
+
controlnet ([`HunyuanDiT2DControlNetModel`] or `List[HunyuanDiT2DControlNetModel]` or [`HunyuanDiT2DControlNetModel`]):
|
185
|
+
Provides additional conditioning to the `unet` during the denoising process. If you set multiple
|
186
|
+
ControlNets as a list, the outputs from each ControlNet are added together to create one combined
|
187
|
+
additional conditioning.
|
188
|
+
"""
|
189
|
+
|
190
|
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
|
191
|
+
_optional_components = [
|
192
|
+
"safety_checker",
|
193
|
+
"feature_extractor",
|
194
|
+
"text_encoder_2",
|
195
|
+
"tokenizer_2",
|
196
|
+
"text_encoder",
|
197
|
+
"tokenizer",
|
198
|
+
]
|
199
|
+
_exclude_from_cpu_offload = ["safety_checker"]
|
200
|
+
_callback_tensor_inputs = [
|
201
|
+
"latents",
|
202
|
+
"prompt_embeds",
|
203
|
+
"negative_prompt_embeds",
|
204
|
+
"prompt_embeds_2",
|
205
|
+
"negative_prompt_embeds_2",
|
206
|
+
]
|
207
|
+
|
208
|
+
def __init__(
|
209
|
+
self,
|
210
|
+
vae: AutoencoderKL,
|
211
|
+
text_encoder: BertModel,
|
212
|
+
tokenizer: BertTokenizer,
|
213
|
+
transformer: HunyuanDiT2DModel,
|
214
|
+
scheduler: DDPMScheduler,
|
215
|
+
safety_checker: StableDiffusionSafetyChecker,
|
216
|
+
feature_extractor: CLIPImageProcessor,
|
217
|
+
controlnet: Union[
|
218
|
+
HunyuanDiT2DControlNetModel,
|
219
|
+
List[HunyuanDiT2DControlNetModel],
|
220
|
+
Tuple[HunyuanDiT2DControlNetModel],
|
221
|
+
HunyuanDiT2DMultiControlNetModel,
|
222
|
+
],
|
223
|
+
text_encoder_2=T5EncoderModel,
|
224
|
+
tokenizer_2=MT5Tokenizer,
|
225
|
+
requires_safety_checker: bool = True,
|
226
|
+
):
|
227
|
+
super().__init__()
|
228
|
+
|
229
|
+
self.register_modules(
|
230
|
+
vae=vae,
|
231
|
+
text_encoder=text_encoder,
|
232
|
+
tokenizer=tokenizer,
|
233
|
+
tokenizer_2=tokenizer_2,
|
234
|
+
transformer=transformer,
|
235
|
+
scheduler=scheduler,
|
236
|
+
safety_checker=safety_checker,
|
237
|
+
feature_extractor=feature_extractor,
|
238
|
+
text_encoder_2=text_encoder_2,
|
239
|
+
controlnet=controlnet,
|
240
|
+
)
|
241
|
+
|
242
|
+
if safety_checker is None and requires_safety_checker:
|
243
|
+
logger.warning(
|
244
|
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
245
|
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
246
|
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
247
|
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
248
|
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
249
|
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
250
|
+
)
|
251
|
+
|
252
|
+
if safety_checker is not None and feature_extractor is None:
|
253
|
+
raise ValueError(
|
254
|
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
255
|
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
256
|
+
)
|
257
|
+
|
258
|
+
self.vae_scale_factor = (
|
259
|
+
2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
|
260
|
+
)
|
261
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
262
|
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
263
|
+
self.default_sample_size = (
|
264
|
+
self.transformer.config.sample_size
|
265
|
+
if hasattr(self, "transformer") and self.transformer is not None
|
266
|
+
else 128
|
267
|
+
)
|
268
|
+
|
269
|
+
# Copied from diffusers.pipelines.hunyuandit.pipeline_hunyuandit.HunyuanDiTPipeline.encode_prompt
|
270
|
+
def encode_prompt(
|
271
|
+
self,
|
272
|
+
prompt: str,
|
273
|
+
device: torch.device = None,
|
274
|
+
dtype: torch.dtype = None,
|
275
|
+
num_images_per_prompt: int = 1,
|
276
|
+
do_classifier_free_guidance: bool = True,
|
277
|
+
negative_prompt: Optional[str] = None,
|
278
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
279
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
280
|
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
281
|
+
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
|
282
|
+
max_sequence_length: Optional[int] = None,
|
283
|
+
text_encoder_index: int = 0,
|
284
|
+
):
|
285
|
+
r"""
|
286
|
+
Encodes the prompt into text encoder hidden states.
|
287
|
+
|
288
|
+
Args:
|
289
|
+
prompt (`str` or `List[str]`, *optional*):
|
290
|
+
prompt to be encoded
|
291
|
+
device: (`torch.device`):
|
292
|
+
torch device
|
293
|
+
dtype (`torch.dtype`):
|
294
|
+
torch dtype
|
295
|
+
num_images_per_prompt (`int`):
|
296
|
+
number of images that should be generated per prompt
|
297
|
+
do_classifier_free_guidance (`bool`):
|
298
|
+
whether to use classifier free guidance or not
|
299
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
300
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
301
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
302
|
+
less than `1`).
|
303
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
304
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
305
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
306
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
307
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
308
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
309
|
+
argument.
|
310
|
+
prompt_attention_mask (`torch.Tensor`, *optional*):
|
311
|
+
Attention mask for the prompt. Required when `prompt_embeds` is passed directly.
|
312
|
+
negative_prompt_attention_mask (`torch.Tensor`, *optional*):
|
313
|
+
Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.
|
314
|
+
max_sequence_length (`int`, *optional*): maximum sequence length to use for the prompt.
|
315
|
+
text_encoder_index (`int`, *optional*):
|
316
|
+
Index of the text encoder to use. `0` for clip and `1` for T5.
|
317
|
+
"""
|
318
|
+
if dtype is None:
|
319
|
+
if self.text_encoder_2 is not None:
|
320
|
+
dtype = self.text_encoder_2.dtype
|
321
|
+
elif self.transformer is not None:
|
322
|
+
dtype = self.transformer.dtype
|
323
|
+
else:
|
324
|
+
dtype = None
|
325
|
+
|
326
|
+
if device is None:
|
327
|
+
device = self._execution_device
|
328
|
+
|
329
|
+
tokenizers = [self.tokenizer, self.tokenizer_2]
|
330
|
+
text_encoders = [self.text_encoder, self.text_encoder_2]
|
331
|
+
|
332
|
+
tokenizer = tokenizers[text_encoder_index]
|
333
|
+
text_encoder = text_encoders[text_encoder_index]
|
334
|
+
|
335
|
+
if max_sequence_length is None:
|
336
|
+
if text_encoder_index == 0:
|
337
|
+
max_length = 77
|
338
|
+
if text_encoder_index == 1:
|
339
|
+
max_length = 256
|
340
|
+
else:
|
341
|
+
max_length = max_sequence_length
|
342
|
+
|
343
|
+
if prompt is not None and isinstance(prompt, str):
|
344
|
+
batch_size = 1
|
345
|
+
elif prompt is not None and isinstance(prompt, list):
|
346
|
+
batch_size = len(prompt)
|
347
|
+
else:
|
348
|
+
batch_size = prompt_embeds.shape[0]
|
349
|
+
|
350
|
+
if prompt_embeds is None:
|
351
|
+
text_inputs = tokenizer(
|
352
|
+
prompt,
|
353
|
+
padding="max_length",
|
354
|
+
max_length=max_length,
|
355
|
+
truncation=True,
|
356
|
+
return_attention_mask=True,
|
357
|
+
return_tensors="pt",
|
358
|
+
)
|
359
|
+
text_input_ids = text_inputs.input_ids
|
360
|
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
361
|
+
|
362
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
363
|
+
text_input_ids, untruncated_ids
|
364
|
+
):
|
365
|
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
|
366
|
+
logger.warning(
|
367
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
368
|
+
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
369
|
+
)
|
370
|
+
|
371
|
+
prompt_attention_mask = text_inputs.attention_mask.to(device)
|
372
|
+
prompt_embeds = text_encoder(
|
373
|
+
text_input_ids.to(device),
|
374
|
+
attention_mask=prompt_attention_mask,
|
375
|
+
)
|
376
|
+
prompt_embeds = prompt_embeds[0]
|
377
|
+
prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
|
378
|
+
|
379
|
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
380
|
+
|
381
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
382
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
383
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
384
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
385
|
+
|
386
|
+
# get unconditional embeddings for classifier free guidance
|
387
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
388
|
+
uncond_tokens: List[str]
|
389
|
+
if negative_prompt is None:
|
390
|
+
uncond_tokens = [""] * batch_size
|
391
|
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
392
|
+
raise TypeError(
|
393
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
394
|
+
f" {type(prompt)}."
|
395
|
+
)
|
396
|
+
elif isinstance(negative_prompt, str):
|
397
|
+
uncond_tokens = [negative_prompt]
|
398
|
+
elif batch_size != len(negative_prompt):
|
399
|
+
raise ValueError(
|
400
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
401
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
402
|
+
" the batch size of `prompt`."
|
403
|
+
)
|
404
|
+
else:
|
405
|
+
uncond_tokens = negative_prompt
|
406
|
+
|
407
|
+
max_length = prompt_embeds.shape[1]
|
408
|
+
uncond_input = tokenizer(
|
409
|
+
uncond_tokens,
|
410
|
+
padding="max_length",
|
411
|
+
max_length=max_length,
|
412
|
+
truncation=True,
|
413
|
+
return_tensors="pt",
|
414
|
+
)
|
415
|
+
|
416
|
+
negative_prompt_attention_mask = uncond_input.attention_mask.to(device)
|
417
|
+
negative_prompt_embeds = text_encoder(
|
418
|
+
uncond_input.input_ids.to(device),
|
419
|
+
attention_mask=negative_prompt_attention_mask,
|
420
|
+
)
|
421
|
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
422
|
+
negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
|
423
|
+
|
424
|
+
if do_classifier_free_guidance:
|
425
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
426
|
+
seq_len = negative_prompt_embeds.shape[1]
|
427
|
+
|
428
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
|
429
|
+
|
430
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
431
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
432
|
+
|
433
|
+
return prompt_embeds, negative_prompt_embeds, prompt_attention_mask, negative_prompt_attention_mask
|
434
|
+
|
435
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
436
|
+
def run_safety_checker(self, image, device, dtype):
|
437
|
+
if self.safety_checker is None:
|
438
|
+
has_nsfw_concept = None
|
439
|
+
else:
|
440
|
+
if torch.is_tensor(image):
|
441
|
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
442
|
+
else:
|
443
|
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
444
|
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
445
|
+
image, has_nsfw_concept = self.safety_checker(
|
446
|
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
447
|
+
)
|
448
|
+
return image, has_nsfw_concept
|
449
|
+
|
450
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
451
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
452
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
453
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
454
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
455
|
+
# and should be between [0, 1]
|
456
|
+
|
457
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
458
|
+
extra_step_kwargs = {}
|
459
|
+
if accepts_eta:
|
460
|
+
extra_step_kwargs["eta"] = eta
|
461
|
+
|
462
|
+
# check if the scheduler accepts generator
|
463
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
464
|
+
if accepts_generator:
|
465
|
+
extra_step_kwargs["generator"] = generator
|
466
|
+
return extra_step_kwargs
|
467
|
+
|
468
|
+
# Copied from diffusers.pipelines.hunyuandit.pipeline_hunyuandit.HunyuanDiTPipeline.check_inputs
|
469
|
+
def check_inputs(
|
470
|
+
self,
|
471
|
+
prompt,
|
472
|
+
height,
|
473
|
+
width,
|
474
|
+
negative_prompt=None,
|
475
|
+
prompt_embeds=None,
|
476
|
+
negative_prompt_embeds=None,
|
477
|
+
prompt_attention_mask=None,
|
478
|
+
negative_prompt_attention_mask=None,
|
479
|
+
prompt_embeds_2=None,
|
480
|
+
negative_prompt_embeds_2=None,
|
481
|
+
prompt_attention_mask_2=None,
|
482
|
+
negative_prompt_attention_mask_2=None,
|
483
|
+
callback_on_step_end_tensor_inputs=None,
|
484
|
+
):
|
485
|
+
if height % 8 != 0 or width % 8 != 0:
|
486
|
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
487
|
+
|
488
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
489
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
490
|
+
):
|
491
|
+
raise ValueError(
|
492
|
+
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]}"
|
493
|
+
)
|
494
|
+
|
495
|
+
if prompt is not None and prompt_embeds is not None:
|
496
|
+
raise ValueError(
|
497
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
498
|
+
" only forward one of the two."
|
499
|
+
)
|
500
|
+
elif prompt is None and prompt_embeds is None:
|
501
|
+
raise ValueError(
|
502
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
503
|
+
)
|
504
|
+
elif prompt is None and prompt_embeds_2 is None:
|
505
|
+
raise ValueError(
|
506
|
+
"Provide either `prompt` or `prompt_embeds_2`. Cannot leave both `prompt` and `prompt_embeds_2` undefined."
|
507
|
+
)
|
508
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
509
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
510
|
+
|
511
|
+
if prompt_embeds is not None and prompt_attention_mask is None:
|
512
|
+
raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
|
513
|
+
|
514
|
+
if prompt_embeds_2 is not None and prompt_attention_mask_2 is None:
|
515
|
+
raise ValueError("Must provide `prompt_attention_mask_2` when specifying `prompt_embeds_2`.")
|
516
|
+
|
517
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
518
|
+
raise ValueError(
|
519
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
520
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
521
|
+
)
|
522
|
+
|
523
|
+
if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
|
524
|
+
raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
|
525
|
+
|
526
|
+
if negative_prompt_embeds_2 is not None and negative_prompt_attention_mask_2 is None:
|
527
|
+
raise ValueError(
|
528
|
+
"Must provide `negative_prompt_attention_mask_2` when specifying `negative_prompt_embeds_2`."
|
529
|
+
)
|
530
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
531
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
532
|
+
raise ValueError(
|
533
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
534
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
535
|
+
f" {negative_prompt_embeds.shape}."
|
536
|
+
)
|
537
|
+
if prompt_embeds_2 is not None and negative_prompt_embeds_2 is not None:
|
538
|
+
if prompt_embeds_2.shape != negative_prompt_embeds_2.shape:
|
539
|
+
raise ValueError(
|
540
|
+
"`prompt_embeds_2` and `negative_prompt_embeds_2` must have the same shape when passed directly, but"
|
541
|
+
f" got: `prompt_embeds_2` {prompt_embeds_2.shape} != `negative_prompt_embeds_2`"
|
542
|
+
f" {negative_prompt_embeds_2.shape}."
|
543
|
+
)
|
544
|
+
|
545
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
546
|
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
547
|
+
shape = (
|
548
|
+
batch_size,
|
549
|
+
num_channels_latents,
|
550
|
+
int(height) // self.vae_scale_factor,
|
551
|
+
int(width) // self.vae_scale_factor,
|
552
|
+
)
|
553
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
554
|
+
raise ValueError(
|
555
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
556
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
557
|
+
)
|
558
|
+
|
559
|
+
if latents is None:
|
560
|
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
561
|
+
else:
|
562
|
+
latents = latents.to(device)
|
563
|
+
|
564
|
+
# scale the initial noise by the standard deviation required by the scheduler
|
565
|
+
latents = latents * self.scheduler.init_noise_sigma
|
566
|
+
return latents
|
567
|
+
|
568
|
+
# Copied from diffusers.pipelines.controlnet_sd3.pipeline_stable_diffusion_3_controlnet.StableDiffusion3ControlNetPipeline.prepare_image
|
569
|
+
def prepare_image(
|
570
|
+
self,
|
571
|
+
image,
|
572
|
+
width,
|
573
|
+
height,
|
574
|
+
batch_size,
|
575
|
+
num_images_per_prompt,
|
576
|
+
device,
|
577
|
+
dtype,
|
578
|
+
do_classifier_free_guidance=False,
|
579
|
+
guess_mode=False,
|
580
|
+
):
|
581
|
+
if isinstance(image, torch.Tensor):
|
582
|
+
pass
|
583
|
+
else:
|
584
|
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
585
|
+
|
586
|
+
image_batch_size = image.shape[0]
|
587
|
+
|
588
|
+
if image_batch_size == 1:
|
589
|
+
repeat_by = batch_size
|
590
|
+
else:
|
591
|
+
# image batch size is the same as prompt batch size
|
592
|
+
repeat_by = num_images_per_prompt
|
593
|
+
|
594
|
+
image = image.repeat_interleave(repeat_by, dim=0)
|
595
|
+
|
596
|
+
image = image.to(device=device, dtype=dtype)
|
597
|
+
|
598
|
+
if do_classifier_free_guidance and not guess_mode:
|
599
|
+
image = torch.cat([image] * 2)
|
600
|
+
|
601
|
+
return image
|
602
|
+
|
603
|
+
@property
|
604
|
+
def guidance_scale(self):
|
605
|
+
return self._guidance_scale
|
606
|
+
|
607
|
+
@property
|
608
|
+
def guidance_rescale(self):
|
609
|
+
return self._guidance_rescale
|
610
|
+
|
611
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
612
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
613
|
+
# corresponds to doing no classifier free guidance.
|
614
|
+
@property
|
615
|
+
def do_classifier_free_guidance(self):
|
616
|
+
return self._guidance_scale > 1
|
617
|
+
|
618
|
+
@property
|
619
|
+
def num_timesteps(self):
|
620
|
+
return self._num_timesteps
|
621
|
+
|
622
|
+
@property
|
623
|
+
def interrupt(self):
|
624
|
+
return self._interrupt
|
625
|
+
|
626
|
+
@torch.no_grad()
|
627
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
628
|
+
def __call__(
|
629
|
+
self,
|
630
|
+
prompt: Union[str, List[str]] = None,
|
631
|
+
height: Optional[int] = None,
|
632
|
+
width: Optional[int] = None,
|
633
|
+
num_inference_steps: Optional[int] = 50,
|
634
|
+
guidance_scale: Optional[float] = 5.0,
|
635
|
+
control_image: PipelineImageInput = None,
|
636
|
+
controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
|
637
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
638
|
+
num_images_per_prompt: Optional[int] = 1,
|
639
|
+
eta: Optional[float] = 0.0,
|
640
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
641
|
+
latents: Optional[torch.Tensor] = None,
|
642
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
643
|
+
prompt_embeds_2: Optional[torch.Tensor] = None,
|
644
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
645
|
+
negative_prompt_embeds_2: Optional[torch.Tensor] = None,
|
646
|
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
647
|
+
prompt_attention_mask_2: Optional[torch.Tensor] = None,
|
648
|
+
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
|
649
|
+
negative_prompt_attention_mask_2: Optional[torch.Tensor] = None,
|
650
|
+
output_type: Optional[str] = "pil",
|
651
|
+
return_dict: bool = True,
|
652
|
+
callback_on_step_end: Optional[
|
653
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
654
|
+
] = None,
|
655
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
656
|
+
guidance_rescale: float = 0.0,
|
657
|
+
original_size: Optional[Tuple[int, int]] = (1024, 1024),
|
658
|
+
target_size: Optional[Tuple[int, int]] = None,
|
659
|
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
660
|
+
use_resolution_binning: bool = True,
|
661
|
+
):
|
662
|
+
r"""
|
663
|
+
The call function to the pipeline for generation with HunyuanDiT.
|
664
|
+
|
665
|
+
Args:
|
666
|
+
prompt (`str` or `List[str]`, *optional*):
|
667
|
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
668
|
+
height (`int`):
|
669
|
+
The height in pixels of the generated image.
|
670
|
+
width (`int`):
|
671
|
+
The width in pixels of the generated image.
|
672
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
673
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
674
|
+
expense of slower inference. This parameter is modulated by `strength`.
|
675
|
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
676
|
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
677
|
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
678
|
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
679
|
+
The percentage of total steps at which the ControlNet starts applying.
|
680
|
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
681
|
+
The percentage of total steps at which the ControlNet stops applying.
|
682
|
+
control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
683
|
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
684
|
+
The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
|
685
|
+
specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
|
686
|
+
as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
|
687
|
+
width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
|
688
|
+
images must be passed as a list such that each element of the list can be correctly batched for input
|
689
|
+
to a single ControlNet.
|
690
|
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
691
|
+
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
|
692
|
+
to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
|
693
|
+
the corresponding scale as a list.
|
694
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
695
|
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
696
|
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
697
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
698
|
+
The number of images to generate per prompt.
|
699
|
+
eta (`float`, *optional*, defaults to 0.0):
|
700
|
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
701
|
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
702
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
703
|
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
704
|
+
generation deterministic.
|
705
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
706
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
707
|
+
provided, text embeddings are generated from the `prompt` input argument.
|
708
|
+
prompt_embeds_2 (`torch.Tensor`, *optional*):
|
709
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
710
|
+
provided, text embeddings are generated from the `prompt` input argument.
|
711
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
712
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
713
|
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
714
|
+
negative_prompt_embeds_2 (`torch.Tensor`, *optional*):
|
715
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
716
|
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
717
|
+
prompt_attention_mask (`torch.Tensor`, *optional*):
|
718
|
+
Attention mask for the prompt. Required when `prompt_embeds` is passed directly.
|
719
|
+
prompt_attention_mask_2 (`torch.Tensor`, *optional*):
|
720
|
+
Attention mask for the prompt. Required when `prompt_embeds_2` is passed directly.
|
721
|
+
negative_prompt_attention_mask (`torch.Tensor`, *optional*):
|
722
|
+
Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.
|
723
|
+
negative_prompt_attention_mask_2 (`torch.Tensor`, *optional*):
|
724
|
+
Attention mask for the negative prompt. Required when `negative_prompt_embeds_2` is passed directly.
|
725
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
726
|
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
727
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
728
|
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
729
|
+
plain tuple.
|
730
|
+
callback_on_step_end (`Callable[[int, int, Dict], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
731
|
+
A callback function or a list of callback functions to be called at the end of each denoising step.
|
732
|
+
callback_on_step_end_tensor_inputs (`List[str]`, *optional*):
|
733
|
+
A list of tensor inputs that should be passed to the callback function. If not defined, all tensor
|
734
|
+
inputs will be passed.
|
735
|
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
736
|
+
Rescale the noise_cfg according to `guidance_rescale`. Based on findings of [Common Diffusion Noise
|
737
|
+
Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
738
|
+
original_size (`Tuple[int, int]`, *optional*, defaults to `(1024, 1024)`):
|
739
|
+
The original size of the image. Used to calculate the time ids.
|
740
|
+
target_size (`Tuple[int, int]`, *optional*):
|
741
|
+
The target size of the image. Used to calculate the time ids.
|
742
|
+
crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to `(0, 0)`):
|
743
|
+
The top left coordinates of the crop. Used to calculate the time ids.
|
744
|
+
use_resolution_binning (`bool`, *optional*, defaults to `True`):
|
745
|
+
Whether to use resolution binning or not. If `True`, the input resolution will be mapped to the closest
|
746
|
+
standard resolution. Supported resolutions are 1024x1024, 1280x1280, 1024x768, 1152x864, 1280x960,
|
747
|
+
768x1024, 864x1152, 960x1280, 1280x768, and 768x1280. It is recommended to set this to `True`.
|
748
|
+
|
749
|
+
Examples:
|
750
|
+
|
751
|
+
Returns:
|
752
|
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
753
|
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
754
|
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
755
|
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
756
|
+
"not-safe-for-work" (nsfw) content.
|
757
|
+
"""
|
758
|
+
|
759
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
760
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
761
|
+
|
762
|
+
# 0. default height and width
|
763
|
+
height = height or self.default_sample_size * self.vae_scale_factor
|
764
|
+
width = width or self.default_sample_size * self.vae_scale_factor
|
765
|
+
height = int((height // 16) * 16)
|
766
|
+
width = int((width // 16) * 16)
|
767
|
+
|
768
|
+
if use_resolution_binning and (height, width) not in SUPPORTED_SHAPE:
|
769
|
+
width, height = map_to_standard_shapes(width, height)
|
770
|
+
height = int(height)
|
771
|
+
width = int(width)
|
772
|
+
logger.warning(f"Reshaped to (height, width)=({height}, {width}), Supported shapes are {SUPPORTED_SHAPE}")
|
773
|
+
|
774
|
+
# 1. Check inputs. Raise error if not correct
|
775
|
+
self.check_inputs(
|
776
|
+
prompt,
|
777
|
+
height,
|
778
|
+
width,
|
779
|
+
negative_prompt,
|
780
|
+
prompt_embeds,
|
781
|
+
negative_prompt_embeds,
|
782
|
+
prompt_attention_mask,
|
783
|
+
negative_prompt_attention_mask,
|
784
|
+
prompt_embeds_2,
|
785
|
+
negative_prompt_embeds_2,
|
786
|
+
prompt_attention_mask_2,
|
787
|
+
negative_prompt_attention_mask_2,
|
788
|
+
callback_on_step_end_tensor_inputs,
|
789
|
+
)
|
790
|
+
self._guidance_scale = guidance_scale
|
791
|
+
self._guidance_rescale = guidance_rescale
|
792
|
+
self._interrupt = False
|
793
|
+
|
794
|
+
# 2. Define call parameters
|
795
|
+
if prompt is not None and isinstance(prompt, str):
|
796
|
+
batch_size = 1
|
797
|
+
elif prompt is not None and isinstance(prompt, list):
|
798
|
+
batch_size = len(prompt)
|
799
|
+
else:
|
800
|
+
batch_size = prompt_embeds.shape[0]
|
801
|
+
|
802
|
+
device = self._execution_device
|
803
|
+
|
804
|
+
# 3. Encode input prompt
|
805
|
+
|
806
|
+
(
|
807
|
+
prompt_embeds,
|
808
|
+
negative_prompt_embeds,
|
809
|
+
prompt_attention_mask,
|
810
|
+
negative_prompt_attention_mask,
|
811
|
+
) = self.encode_prompt(
|
812
|
+
prompt=prompt,
|
813
|
+
device=device,
|
814
|
+
dtype=self.transformer.dtype,
|
815
|
+
num_images_per_prompt=num_images_per_prompt,
|
816
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
817
|
+
negative_prompt=negative_prompt,
|
818
|
+
prompt_embeds=prompt_embeds,
|
819
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
820
|
+
prompt_attention_mask=prompt_attention_mask,
|
821
|
+
negative_prompt_attention_mask=negative_prompt_attention_mask,
|
822
|
+
max_sequence_length=77,
|
823
|
+
text_encoder_index=0,
|
824
|
+
)
|
825
|
+
(
|
826
|
+
prompt_embeds_2,
|
827
|
+
negative_prompt_embeds_2,
|
828
|
+
prompt_attention_mask_2,
|
829
|
+
negative_prompt_attention_mask_2,
|
830
|
+
) = self.encode_prompt(
|
831
|
+
prompt=prompt,
|
832
|
+
device=device,
|
833
|
+
dtype=self.transformer.dtype,
|
834
|
+
num_images_per_prompt=num_images_per_prompt,
|
835
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
836
|
+
negative_prompt=negative_prompt,
|
837
|
+
prompt_embeds=prompt_embeds_2,
|
838
|
+
negative_prompt_embeds=negative_prompt_embeds_2,
|
839
|
+
prompt_attention_mask=prompt_attention_mask_2,
|
840
|
+
negative_prompt_attention_mask=negative_prompt_attention_mask_2,
|
841
|
+
max_sequence_length=256,
|
842
|
+
text_encoder_index=1,
|
843
|
+
)
|
844
|
+
|
845
|
+
# 4. Prepare control image
|
846
|
+
if isinstance(self.controlnet, HunyuanDiT2DControlNetModel):
|
847
|
+
control_image = self.prepare_image(
|
848
|
+
image=control_image,
|
849
|
+
width=width,
|
850
|
+
height=height,
|
851
|
+
batch_size=batch_size * num_images_per_prompt,
|
852
|
+
num_images_per_prompt=num_images_per_prompt,
|
853
|
+
device=device,
|
854
|
+
dtype=self.dtype,
|
855
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
856
|
+
guess_mode=False,
|
857
|
+
)
|
858
|
+
height, width = control_image.shape[-2:]
|
859
|
+
|
860
|
+
control_image = self.vae.encode(control_image).latent_dist.sample()
|
861
|
+
control_image = control_image * self.vae.config.scaling_factor
|
862
|
+
|
863
|
+
elif isinstance(self.controlnet, HunyuanDiT2DMultiControlNetModel):
|
864
|
+
control_images = []
|
865
|
+
|
866
|
+
for control_image_ in control_image:
|
867
|
+
control_image_ = self.prepare_image(
|
868
|
+
image=control_image_,
|
869
|
+
width=width,
|
870
|
+
height=height,
|
871
|
+
batch_size=batch_size * num_images_per_prompt,
|
872
|
+
num_images_per_prompt=num_images_per_prompt,
|
873
|
+
device=device,
|
874
|
+
dtype=self.dtype,
|
875
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
876
|
+
guess_mode=False,
|
877
|
+
)
|
878
|
+
|
879
|
+
control_image_ = self.vae.encode(control_image_).latent_dist.sample()
|
880
|
+
control_image_ = control_image_ * self.vae.config.scaling_factor
|
881
|
+
|
882
|
+
control_images.append(control_image_)
|
883
|
+
|
884
|
+
control_image = control_images
|
885
|
+
else:
|
886
|
+
assert False
|
887
|
+
|
888
|
+
# 5. Prepare timesteps
|
889
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
890
|
+
timesteps = self.scheduler.timesteps
|
891
|
+
|
892
|
+
# 6. Prepare latent variables
|
893
|
+
num_channels_latents = self.transformer.config.in_channels
|
894
|
+
latents = self.prepare_latents(
|
895
|
+
batch_size * num_images_per_prompt,
|
896
|
+
num_channels_latents,
|
897
|
+
height,
|
898
|
+
width,
|
899
|
+
prompt_embeds.dtype,
|
900
|
+
device,
|
901
|
+
generator,
|
902
|
+
latents,
|
903
|
+
)
|
904
|
+
|
905
|
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
906
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
907
|
+
|
908
|
+
# 8. create image_rotary_emb, style embedding & time ids
|
909
|
+
grid_height = height // 8 // self.transformer.config.patch_size
|
910
|
+
grid_width = width // 8 // self.transformer.config.patch_size
|
911
|
+
base_size = 512 // 8 // self.transformer.config.patch_size
|
912
|
+
grid_crops_coords = get_resize_crop_region_for_grid((grid_height, grid_width), base_size)
|
913
|
+
image_rotary_emb = get_2d_rotary_pos_embed(
|
914
|
+
self.transformer.inner_dim // self.transformer.num_heads, grid_crops_coords, (grid_height, grid_width)
|
915
|
+
)
|
916
|
+
|
917
|
+
style = torch.tensor([0], device=device)
|
918
|
+
|
919
|
+
target_size = target_size or (height, width)
|
920
|
+
add_time_ids = list(original_size + target_size + crops_coords_top_left)
|
921
|
+
add_time_ids = torch.tensor([add_time_ids], dtype=prompt_embeds.dtype)
|
922
|
+
|
923
|
+
if self.do_classifier_free_guidance:
|
924
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
925
|
+
prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])
|
926
|
+
prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])
|
927
|
+
prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2])
|
928
|
+
add_time_ids = torch.cat([add_time_ids] * 2, dim=0)
|
929
|
+
style = torch.cat([style] * 2, dim=0)
|
930
|
+
|
931
|
+
prompt_embeds = prompt_embeds.to(device=device)
|
932
|
+
prompt_attention_mask = prompt_attention_mask.to(device=device)
|
933
|
+
prompt_embeds_2 = prompt_embeds_2.to(device=device)
|
934
|
+
prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device)
|
935
|
+
add_time_ids = add_time_ids.to(dtype=prompt_embeds.dtype, device=device).repeat(
|
936
|
+
batch_size * num_images_per_prompt, 1
|
937
|
+
)
|
938
|
+
style = style.to(device=device).repeat(batch_size * num_images_per_prompt)
|
939
|
+
|
940
|
+
# 9. Denoising loop
|
941
|
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
942
|
+
self._num_timesteps = len(timesteps)
|
943
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
944
|
+
for i, t in enumerate(timesteps):
|
945
|
+
if self.interrupt:
|
946
|
+
continue
|
947
|
+
|
948
|
+
# expand the latents if we are doing classifier free guidance
|
949
|
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
950
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
951
|
+
|
952
|
+
# expand scalar t to 1-D tensor to match the 1st dim of latent_model_input
|
953
|
+
t_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to(
|
954
|
+
dtype=latent_model_input.dtype
|
955
|
+
)
|
956
|
+
|
957
|
+
# controlnet(s) inference
|
958
|
+
control_block_samples = self.controlnet(
|
959
|
+
latent_model_input,
|
960
|
+
t_expand,
|
961
|
+
encoder_hidden_states=prompt_embeds,
|
962
|
+
text_embedding_mask=prompt_attention_mask,
|
963
|
+
encoder_hidden_states_t5=prompt_embeds_2,
|
964
|
+
text_embedding_mask_t5=prompt_attention_mask_2,
|
965
|
+
image_meta_size=add_time_ids,
|
966
|
+
style=style,
|
967
|
+
image_rotary_emb=image_rotary_emb,
|
968
|
+
return_dict=False,
|
969
|
+
controlnet_cond=control_image,
|
970
|
+
conditioning_scale=controlnet_conditioning_scale,
|
971
|
+
)[0]
|
972
|
+
|
973
|
+
# predict the noise residual
|
974
|
+
noise_pred = self.transformer(
|
975
|
+
latent_model_input,
|
976
|
+
t_expand,
|
977
|
+
encoder_hidden_states=prompt_embeds,
|
978
|
+
text_embedding_mask=prompt_attention_mask,
|
979
|
+
encoder_hidden_states_t5=prompt_embeds_2,
|
980
|
+
text_embedding_mask_t5=prompt_attention_mask_2,
|
981
|
+
image_meta_size=add_time_ids,
|
982
|
+
style=style,
|
983
|
+
image_rotary_emb=image_rotary_emb,
|
984
|
+
return_dict=False,
|
985
|
+
controlnet_block_samples=control_block_samples,
|
986
|
+
)[0]
|
987
|
+
|
988
|
+
noise_pred, _ = noise_pred.chunk(2, dim=1)
|
989
|
+
|
990
|
+
# perform guidance
|
991
|
+
if self.do_classifier_free_guidance:
|
992
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
993
|
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
994
|
+
|
995
|
+
if self.do_classifier_free_guidance and guidance_rescale > 0.0:
|
996
|
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
997
|
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
998
|
+
|
999
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1000
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1001
|
+
|
1002
|
+
if callback_on_step_end is not None:
|
1003
|
+
callback_kwargs = {}
|
1004
|
+
for k in callback_on_step_end_tensor_inputs:
|
1005
|
+
callback_kwargs[k] = locals()[k]
|
1006
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1007
|
+
|
1008
|
+
latents = callback_outputs.pop("latents", latents)
|
1009
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1010
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1011
|
+
prompt_embeds_2 = callback_outputs.pop("prompt_embeds_2", prompt_embeds_2)
|
1012
|
+
negative_prompt_embeds_2 = callback_outputs.pop(
|
1013
|
+
"negative_prompt_embeds_2", negative_prompt_embeds_2
|
1014
|
+
)
|
1015
|
+
|
1016
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1017
|
+
progress_bar.update()
|
1018
|
+
|
1019
|
+
if XLA_AVAILABLE:
|
1020
|
+
xm.mark_step()
|
1021
|
+
|
1022
|
+
if not output_type == "latent":
|
1023
|
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
1024
|
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
1025
|
+
else:
|
1026
|
+
image = latents
|
1027
|
+
has_nsfw_concept = None
|
1028
|
+
|
1029
|
+
if has_nsfw_concept is None:
|
1030
|
+
do_denormalize = [True] * image.shape[0]
|
1031
|
+
else:
|
1032
|
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
1033
|
+
|
1034
|
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
1035
|
+
|
1036
|
+
# Offload all models
|
1037
|
+
self.maybe_free_model_hooks()
|
1038
|
+
|
1039
|
+
if not return_dict:
|
1040
|
+
return (image, has_nsfw_concept)
|
1041
|
+
|
1042
|
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|