diffusers 0.30.3__py3-none-any.whl → 0.31.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 +34 -2
- diffusers/configuration_utils.py +12 -0
- diffusers/dependency_versions_table.py +1 -1
- diffusers/image_processor.py +257 -54
- diffusers/loaders/__init__.py +2 -0
- diffusers/loaders/ip_adapter.py +5 -1
- diffusers/loaders/lora_base.py +14 -7
- diffusers/loaders/lora_conversion_utils.py +332 -0
- diffusers/loaders/lora_pipeline.py +707 -41
- diffusers/loaders/peft.py +1 -0
- diffusers/loaders/single_file_utils.py +81 -4
- diffusers/loaders/textual_inversion.py +2 -0
- diffusers/loaders/unet.py +39 -8
- diffusers/models/__init__.py +4 -0
- diffusers/models/adapter.py +53 -53
- diffusers/models/attention.py +86 -10
- diffusers/models/attention_processor.py +169 -133
- diffusers/models/autoencoders/autoencoder_kl.py +71 -11
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +187 -88
- diffusers/models/controlnet_flux.py +536 -0
- diffusers/models/controlnet_sd3.py +7 -3
- diffusers/models/controlnet_sparsectrl.py +0 -1
- diffusers/models/embeddings.py +170 -61
- diffusers/models/embeddings_flax.py +23 -9
- diffusers/models/model_loading_utils.py +182 -14
- diffusers/models/modeling_utils.py +283 -46
- diffusers/models/normalization.py +79 -0
- diffusers/models/transformers/__init__.py +1 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +1 -0
- diffusers/models/transformers/cogvideox_transformer_3d.py +23 -2
- diffusers/models/transformers/pixart_transformer_2d.py +9 -1
- diffusers/models/transformers/transformer_cogview3plus.py +386 -0
- diffusers/models/transformers/transformer_flux.py +161 -44
- diffusers/models/transformers/transformer_sd3.py +7 -1
- diffusers/models/unets/unet_2d_condition.py +8 -8
- diffusers/models/unets/unet_motion_model.py +41 -63
- diffusers/models/upsampling.py +6 -6
- diffusers/pipelines/__init__.py +35 -6
- diffusers/pipelines/animatediff/__init__.py +2 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +45 -21
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +44 -20
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +18 -4
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +2 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +104 -66
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +1 -1
- diffusers/pipelines/auto_pipeline.py +39 -8
- diffusers/pipelines/cogvideo/__init__.py +2 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +30 -17
- diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +794 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +41 -31
- diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +42 -29
- diffusers/pipelines/cogview3/__init__.py +47 -0
- diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
- diffusers/pipelines/cogview3/pipeline_output.py +21 -0
- diffusers/pipelines/controlnet/pipeline_controlnet.py +9 -1
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +8 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +8 -0
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +36 -13
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +9 -1
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +8 -1
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +17 -3
- diffusers/pipelines/controlnet_sd3/__init__.py +4 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +3 -1
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
- diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +16 -4
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +1 -1
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
- diffusers/pipelines/flux/__init__.py +10 -0
- diffusers/pipelines/flux/pipeline_flux.py +53 -20
- diffusers/pipelines/flux/pipeline_flux_controlnet.py +984 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +988 -0
- diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1182 -0
- diffusers/pipelines/flux/pipeline_flux_img2img.py +850 -0
- diffusers/pipelines/flux/pipeline_flux_inpaint.py +1015 -0
- diffusers/pipelines/free_noise_utils.py +365 -5
- diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +15 -3
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +2 -2
- diffusers/pipelines/kolors/pipeline_kolors.py +1 -1
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +14 -11
- diffusers/pipelines/kolors/tokenizer.py +4 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +1 -1
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +1 -1
- diffusers/pipelines/latte/pipeline_latte.py +2 -2
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +15 -3
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +15 -3
- diffusers/pipelines/lumina/pipeline_lumina.py +2 -2
- diffusers/pipelines/pag/__init__.py +6 -0
- diffusers/pipelines/pag/pag_utils.py +8 -2
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1 -1
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1544 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +2 -2
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1685 -0
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +17 -5
- diffusers/pipelines/pag/pipeline_pag_kolors.py +1 -1
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +1 -1
- diffusers/pipelines/pag/pipeline_pag_sd.py +18 -6
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +12 -3
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +5 -1
- diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1091 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +18 -6
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +31 -16
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +42 -19
- diffusers/pipelines/pia/pipeline_pia.py +2 -0
- diffusers/pipelines/pipeline_loading_utils.py +225 -27
- diffusers/pipelines/pipeline_utils.py +123 -180
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +1 -1
- diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +1 -1
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +35 -3
- diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +28 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +241 -81
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +12 -3
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +20 -4
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +3 -3
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +16 -4
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +16 -4
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -4
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +29 -14
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +29 -14
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +1 -1
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +1 -1
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +16 -4
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +15 -3
- diffusers/quantizers/__init__.py +16 -0
- diffusers/quantizers/auto.py +126 -0
- diffusers/quantizers/base.py +233 -0
- diffusers/quantizers/bitsandbytes/__init__.py +2 -0
- diffusers/quantizers/bitsandbytes/bnb_quantizer.py +558 -0
- diffusers/quantizers/bitsandbytes/utils.py +306 -0
- diffusers/quantizers/quantization_config.py +391 -0
- diffusers/schedulers/scheduling_ddim.py +4 -1
- diffusers/schedulers/scheduling_ddim_cogvideox.py +4 -1
- diffusers/schedulers/scheduling_ddim_parallel.py +4 -1
- diffusers/schedulers/scheduling_ddpm.py +4 -1
- diffusers/schedulers/scheduling_ddpm_parallel.py +4 -1
- diffusers/schedulers/scheduling_deis_multistep.py +78 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +82 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +80 -1
- diffusers/schedulers/scheduling_dpmsolver_sde.py +125 -10
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +82 -1
- diffusers/schedulers/scheduling_edm_euler.py +8 -6
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +4 -1
- diffusers/schedulers/scheduling_euler_discrete.py +92 -7
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +4 -5
- diffusers/schedulers/scheduling_heun_discrete.py +114 -8
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +116 -11
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +110 -8
- diffusers/schedulers/scheduling_lms_discrete.py +76 -1
- diffusers/schedulers/scheduling_sasolver.py +78 -1
- diffusers/schedulers/scheduling_unclip.py +4 -1
- diffusers/schedulers/scheduling_unipc_multistep.py +78 -1
- diffusers/training_utils.py +48 -18
- diffusers/utils/__init__.py +2 -1
- diffusers/utils/dummy_pt_objects.py +60 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +165 -0
- diffusers/utils/hub_utils.py +16 -4
- diffusers/utils/import_utils.py +31 -8
- diffusers/utils/loading_utils.py +28 -4
- diffusers/utils/peft_utils.py +3 -3
- diffusers/utils/testing_utils.py +59 -0
- {diffusers-0.30.3.dist-info → diffusers-0.31.0.dist-info}/METADATA +7 -6
- {diffusers-0.30.3.dist-info → diffusers-0.31.0.dist-info}/RECORD +172 -149
- {diffusers-0.30.3.dist-info → diffusers-0.31.0.dist-info}/LICENSE +0 -0
- {diffusers-0.30.3.dist-info → diffusers-0.31.0.dist-info}/WHEEL +0 -0
- {diffusers-0.30.3.dist-info → diffusers-0.31.0.dist-info}/entry_points.txt +0 -0
- {diffusers-0.30.3.dist-info → diffusers-0.31.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1685 @@
|
|
1
|
+
# Copyright 2024 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
|
+
|
16
|
+
import inspect
|
17
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
18
|
+
|
19
|
+
import numpy as np
|
20
|
+
import PIL.Image
|
21
|
+
import torch
|
22
|
+
import torch.nn.functional as F
|
23
|
+
from transformers import (
|
24
|
+
CLIPImageProcessor,
|
25
|
+
CLIPTextModel,
|
26
|
+
CLIPTextModelWithProjection,
|
27
|
+
CLIPTokenizer,
|
28
|
+
CLIPVisionModelWithProjection,
|
29
|
+
)
|
30
|
+
|
31
|
+
from diffusers.utils.import_utils import is_invisible_watermark_available
|
32
|
+
|
33
|
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
34
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
35
|
+
from ...loaders import (
|
36
|
+
FromSingleFileMixin,
|
37
|
+
IPAdapterMixin,
|
38
|
+
StableDiffusionXLLoraLoaderMixin,
|
39
|
+
TextualInversionLoaderMixin,
|
40
|
+
)
|
41
|
+
from ...models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel
|
42
|
+
from ...models.attention_processor import (
|
43
|
+
AttnProcessor2_0,
|
44
|
+
XFormersAttnProcessor,
|
45
|
+
)
|
46
|
+
from ...models.lora import adjust_lora_scale_text_encoder
|
47
|
+
from ...schedulers import KarrasDiffusionSchedulers
|
48
|
+
from ...utils import (
|
49
|
+
USE_PEFT_BACKEND,
|
50
|
+
logging,
|
51
|
+
replace_example_docstring,
|
52
|
+
scale_lora_layers,
|
53
|
+
unscale_lora_layers,
|
54
|
+
)
|
55
|
+
from ...utils.torch_utils import is_compiled_module, randn_tensor
|
56
|
+
from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
57
|
+
from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
|
58
|
+
from .pag_utils import PAGMixin
|
59
|
+
|
60
|
+
|
61
|
+
if is_invisible_watermark_available():
|
62
|
+
from ..stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
|
63
|
+
|
64
|
+
from ..controlnet.multicontrolnet import MultiControlNetModel
|
65
|
+
|
66
|
+
|
67
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
68
|
+
|
69
|
+
|
70
|
+
EXAMPLE_DOC_STRING = """
|
71
|
+
Examples:
|
72
|
+
```py
|
73
|
+
>>> # pip install accelerate transformers safetensors diffusers
|
74
|
+
|
75
|
+
>>> import torch
|
76
|
+
>>> import numpy as np
|
77
|
+
>>> from PIL import Image
|
78
|
+
|
79
|
+
>>> from transformers import DPTFeatureExtractor, DPTForDepthEstimation
|
80
|
+
>>> from diffusers import ControlNetModel, StableDiffusionXLControlNetPAGImg2ImgPipeline, AutoencoderKL
|
81
|
+
>>> from diffusers.utils import load_image
|
82
|
+
|
83
|
+
|
84
|
+
>>> depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
|
85
|
+
>>> feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-hybrid-midas")
|
86
|
+
>>> controlnet = ControlNetModel.from_pretrained(
|
87
|
+
... "diffusers/controlnet-depth-sdxl-1.0-small",
|
88
|
+
... variant="fp16",
|
89
|
+
... use_safetensors="True",
|
90
|
+
... torch_dtype=torch.float16,
|
91
|
+
... )
|
92
|
+
>>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
|
93
|
+
>>> pipe = StableDiffusionXLControlNetPAGImg2ImgPipeline.from_pretrained(
|
94
|
+
... "stabilityai/stable-diffusion-xl-base-1.0",
|
95
|
+
... controlnet=controlnet,
|
96
|
+
... vae=vae,
|
97
|
+
... variant="fp16",
|
98
|
+
... use_safetensors=True,
|
99
|
+
... torch_dtype=torch.float16,
|
100
|
+
... enable_pag=True,
|
101
|
+
... )
|
102
|
+
>>> pipe.enable_model_cpu_offload()
|
103
|
+
|
104
|
+
|
105
|
+
>>> def get_depth_map(image):
|
106
|
+
... image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
|
107
|
+
... with torch.no_grad(), torch.autocast("cuda"):
|
108
|
+
... depth_map = depth_estimator(image).predicted_depth
|
109
|
+
|
110
|
+
... depth_map = torch.nn.fuctional.interpolate(
|
111
|
+
... depth_map.unsqueeze(1),
|
112
|
+
... size=(1024, 1024),
|
113
|
+
... mode="bicubic",
|
114
|
+
... align_corners=False,
|
115
|
+
... )
|
116
|
+
... depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
|
117
|
+
... depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
|
118
|
+
... depth_map = (depth_map - depth_min) / (depth_max - depth_min)
|
119
|
+
... image = torch.cat([depth_map] * 3, dim=1)
|
120
|
+
... image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
|
121
|
+
... image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
|
122
|
+
... return image
|
123
|
+
|
124
|
+
|
125
|
+
>>> prompt = "A robot, 4k photo"
|
126
|
+
>>> image = load_image(
|
127
|
+
... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
|
128
|
+
... "/kandinsky/cat.png"
|
129
|
+
... ).resize((1024, 1024))
|
130
|
+
>>> controlnet_conditioning_scale = 0.5 # recommended for good generalization
|
131
|
+
>>> depth_image = get_depth_map(image)
|
132
|
+
|
133
|
+
>>> images = pipe(
|
134
|
+
... prompt,
|
135
|
+
... image=image,
|
136
|
+
... control_image=depth_image,
|
137
|
+
... strength=0.99,
|
138
|
+
... num_inference_steps=50,
|
139
|
+
... controlnet_conditioning_scale=controlnet_conditioning_scale,
|
140
|
+
... ).images
|
141
|
+
>>> images[0].save(f"robot_cat.png")
|
142
|
+
```
|
143
|
+
"""
|
144
|
+
|
145
|
+
|
146
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
147
|
+
def retrieve_latents(
|
148
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
149
|
+
):
|
150
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
151
|
+
return encoder_output.latent_dist.sample(generator)
|
152
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
153
|
+
return encoder_output.latent_dist.mode()
|
154
|
+
elif hasattr(encoder_output, "latents"):
|
155
|
+
return encoder_output.latents
|
156
|
+
else:
|
157
|
+
raise AttributeError("Could not access latents of provided encoder_output")
|
158
|
+
|
159
|
+
|
160
|
+
class StableDiffusionXLControlNetPAGImg2ImgPipeline(
|
161
|
+
DiffusionPipeline,
|
162
|
+
StableDiffusionMixin,
|
163
|
+
TextualInversionLoaderMixin,
|
164
|
+
StableDiffusionXLLoraLoaderMixin,
|
165
|
+
FromSingleFileMixin,
|
166
|
+
IPAdapterMixin,
|
167
|
+
PAGMixin,
|
168
|
+
):
|
169
|
+
r"""
|
170
|
+
Pipeline for image-to-image generation using Stable Diffusion XL with ControlNet guidance.
|
171
|
+
|
172
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
173
|
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
174
|
+
|
175
|
+
The pipeline also inherits the following loading methods:
|
176
|
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
177
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
178
|
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
179
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
180
|
+
|
181
|
+
Args:
|
182
|
+
vae ([`AutoencoderKL`]):
|
183
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
184
|
+
text_encoder ([`CLIPTextModel`]):
|
185
|
+
Frozen text-encoder. Stable Diffusion uses the text portion of
|
186
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
187
|
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
188
|
+
text_encoder_2 ([` CLIPTextModelWithProjection`]):
|
189
|
+
Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
|
190
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
191
|
+
specifically the
|
192
|
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
193
|
+
variant.
|
194
|
+
tokenizer (`CLIPTokenizer`):
|
195
|
+
Tokenizer of class
|
196
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
197
|
+
tokenizer_2 (`CLIPTokenizer`):
|
198
|
+
Second Tokenizer of class
|
199
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
200
|
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
201
|
+
controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
|
202
|
+
Provides additional conditioning to the unet during the denoising process. If you set multiple ControlNets
|
203
|
+
as a list, the outputs from each ControlNet are added together to create one combined additional
|
204
|
+
conditioning.
|
205
|
+
scheduler ([`SchedulerMixin`]):
|
206
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
207
|
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
208
|
+
requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
|
209
|
+
Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
|
210
|
+
config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
|
211
|
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
212
|
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
213
|
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
214
|
+
add_watermarker (`bool`, *optional*):
|
215
|
+
Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
|
216
|
+
watermark output images. If not defined, it will default to True if the package is installed, otherwise no
|
217
|
+
watermarker will be used.
|
218
|
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
219
|
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
220
|
+
"""
|
221
|
+
|
222
|
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
|
223
|
+
_optional_components = [
|
224
|
+
"tokenizer",
|
225
|
+
"tokenizer_2",
|
226
|
+
"text_encoder",
|
227
|
+
"text_encoder_2",
|
228
|
+
"feature_extractor",
|
229
|
+
"image_encoder",
|
230
|
+
]
|
231
|
+
_callback_tensor_inputs = [
|
232
|
+
"latents",
|
233
|
+
"prompt_embeds",
|
234
|
+
"negative_prompt_embeds",
|
235
|
+
"add_text_embeds",
|
236
|
+
"add_time_ids",
|
237
|
+
"negative_pooled_prompt_embeds",
|
238
|
+
"add_neg_time_ids",
|
239
|
+
]
|
240
|
+
|
241
|
+
def __init__(
|
242
|
+
self,
|
243
|
+
vae: AutoencoderKL,
|
244
|
+
text_encoder: CLIPTextModel,
|
245
|
+
text_encoder_2: CLIPTextModelWithProjection,
|
246
|
+
tokenizer: CLIPTokenizer,
|
247
|
+
tokenizer_2: CLIPTokenizer,
|
248
|
+
unet: UNet2DConditionModel,
|
249
|
+
controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
|
250
|
+
scheduler: KarrasDiffusionSchedulers,
|
251
|
+
requires_aesthetics_score: bool = False,
|
252
|
+
force_zeros_for_empty_prompt: bool = True,
|
253
|
+
add_watermarker: Optional[bool] = None,
|
254
|
+
feature_extractor: CLIPImageProcessor = None,
|
255
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
256
|
+
pag_applied_layers: Union[str, List[str]] = "mid", # ["mid"], ["down.block_1", "up.block_0.attentions_0"]
|
257
|
+
):
|
258
|
+
super().__init__()
|
259
|
+
|
260
|
+
if isinstance(controlnet, (list, tuple)):
|
261
|
+
controlnet = MultiControlNetModel(controlnet)
|
262
|
+
|
263
|
+
self.register_modules(
|
264
|
+
vae=vae,
|
265
|
+
text_encoder=text_encoder,
|
266
|
+
text_encoder_2=text_encoder_2,
|
267
|
+
tokenizer=tokenizer,
|
268
|
+
tokenizer_2=tokenizer_2,
|
269
|
+
unet=unet,
|
270
|
+
controlnet=controlnet,
|
271
|
+
scheduler=scheduler,
|
272
|
+
feature_extractor=feature_extractor,
|
273
|
+
image_encoder=image_encoder,
|
274
|
+
)
|
275
|
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
276
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
277
|
+
self.control_image_processor = VaeImageProcessor(
|
278
|
+
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
|
279
|
+
)
|
280
|
+
add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
|
281
|
+
|
282
|
+
if add_watermarker:
|
283
|
+
self.watermark = StableDiffusionXLWatermarker()
|
284
|
+
else:
|
285
|
+
self.watermark = None
|
286
|
+
|
287
|
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
288
|
+
self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
|
289
|
+
|
290
|
+
self.set_pag_applied_layers(pag_applied_layers)
|
291
|
+
|
292
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
|
293
|
+
def encode_prompt(
|
294
|
+
self,
|
295
|
+
prompt: str,
|
296
|
+
prompt_2: Optional[str] = None,
|
297
|
+
device: Optional[torch.device] = None,
|
298
|
+
num_images_per_prompt: int = 1,
|
299
|
+
do_classifier_free_guidance: bool = True,
|
300
|
+
negative_prompt: Optional[str] = None,
|
301
|
+
negative_prompt_2: Optional[str] = None,
|
302
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
303
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
304
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
305
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
306
|
+
lora_scale: Optional[float] = None,
|
307
|
+
clip_skip: Optional[int] = None,
|
308
|
+
):
|
309
|
+
r"""
|
310
|
+
Encodes the prompt into text encoder hidden states.
|
311
|
+
|
312
|
+
Args:
|
313
|
+
prompt (`str` or `List[str]`, *optional*):
|
314
|
+
prompt to be encoded
|
315
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
316
|
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
317
|
+
used in both text-encoders
|
318
|
+
device: (`torch.device`):
|
319
|
+
torch device
|
320
|
+
num_images_per_prompt (`int`):
|
321
|
+
number of images that should be generated per prompt
|
322
|
+
do_classifier_free_guidance (`bool`):
|
323
|
+
whether to use classifier free guidance or not
|
324
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
325
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
326
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
327
|
+
less than `1`).
|
328
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
329
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
330
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
331
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
332
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
333
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
334
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
335
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
336
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
337
|
+
argument.
|
338
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
339
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
340
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
341
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
342
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
343
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
344
|
+
input argument.
|
345
|
+
lora_scale (`float`, *optional*):
|
346
|
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
347
|
+
clip_skip (`int`, *optional*):
|
348
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
349
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
350
|
+
"""
|
351
|
+
device = device or self._execution_device
|
352
|
+
|
353
|
+
# set lora scale so that monkey patched LoRA
|
354
|
+
# function of text encoder can correctly access it
|
355
|
+
if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
|
356
|
+
self._lora_scale = lora_scale
|
357
|
+
|
358
|
+
# dynamically adjust the LoRA scale
|
359
|
+
if self.text_encoder is not None:
|
360
|
+
if not USE_PEFT_BACKEND:
|
361
|
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
362
|
+
else:
|
363
|
+
scale_lora_layers(self.text_encoder, lora_scale)
|
364
|
+
|
365
|
+
if self.text_encoder_2 is not None:
|
366
|
+
if not USE_PEFT_BACKEND:
|
367
|
+
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
368
|
+
else:
|
369
|
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
370
|
+
|
371
|
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
372
|
+
|
373
|
+
if prompt is not None:
|
374
|
+
batch_size = len(prompt)
|
375
|
+
else:
|
376
|
+
batch_size = prompt_embeds.shape[0]
|
377
|
+
|
378
|
+
# Define tokenizers and text encoders
|
379
|
+
tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
|
380
|
+
text_encoders = (
|
381
|
+
[self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
|
382
|
+
)
|
383
|
+
|
384
|
+
if prompt_embeds is None:
|
385
|
+
prompt_2 = prompt_2 or prompt
|
386
|
+
prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
|
387
|
+
|
388
|
+
# textual inversion: process multi-vector tokens if necessary
|
389
|
+
prompt_embeds_list = []
|
390
|
+
prompts = [prompt, prompt_2]
|
391
|
+
for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
|
392
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
393
|
+
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
394
|
+
|
395
|
+
text_inputs = tokenizer(
|
396
|
+
prompt,
|
397
|
+
padding="max_length",
|
398
|
+
max_length=tokenizer.model_max_length,
|
399
|
+
truncation=True,
|
400
|
+
return_tensors="pt",
|
401
|
+
)
|
402
|
+
|
403
|
+
text_input_ids = text_inputs.input_ids
|
404
|
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
405
|
+
|
406
|
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
407
|
+
text_input_ids, untruncated_ids
|
408
|
+
):
|
409
|
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
|
410
|
+
logger.warning(
|
411
|
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
412
|
+
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
413
|
+
)
|
414
|
+
|
415
|
+
prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
|
416
|
+
|
417
|
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
418
|
+
pooled_prompt_embeds = prompt_embeds[0]
|
419
|
+
if clip_skip is None:
|
420
|
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
421
|
+
else:
|
422
|
+
# "2" because SDXL always indexes from the penultimate layer.
|
423
|
+
prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
|
424
|
+
|
425
|
+
prompt_embeds_list.append(prompt_embeds)
|
426
|
+
|
427
|
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
428
|
+
|
429
|
+
# get unconditional embeddings for classifier free guidance
|
430
|
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
431
|
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
432
|
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
433
|
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
434
|
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
435
|
+
negative_prompt = negative_prompt or ""
|
436
|
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
437
|
+
|
438
|
+
# normalize str to list
|
439
|
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
440
|
+
negative_prompt_2 = (
|
441
|
+
batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
|
442
|
+
)
|
443
|
+
|
444
|
+
uncond_tokens: List[str]
|
445
|
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
446
|
+
raise TypeError(
|
447
|
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
448
|
+
f" {type(prompt)}."
|
449
|
+
)
|
450
|
+
elif batch_size != len(negative_prompt):
|
451
|
+
raise ValueError(
|
452
|
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
453
|
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
454
|
+
" the batch size of `prompt`."
|
455
|
+
)
|
456
|
+
else:
|
457
|
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
458
|
+
|
459
|
+
negative_prompt_embeds_list = []
|
460
|
+
for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
|
461
|
+
if isinstance(self, TextualInversionLoaderMixin):
|
462
|
+
negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
|
463
|
+
|
464
|
+
max_length = prompt_embeds.shape[1]
|
465
|
+
uncond_input = tokenizer(
|
466
|
+
negative_prompt,
|
467
|
+
padding="max_length",
|
468
|
+
max_length=max_length,
|
469
|
+
truncation=True,
|
470
|
+
return_tensors="pt",
|
471
|
+
)
|
472
|
+
|
473
|
+
negative_prompt_embeds = text_encoder(
|
474
|
+
uncond_input.input_ids.to(device),
|
475
|
+
output_hidden_states=True,
|
476
|
+
)
|
477
|
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
478
|
+
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
479
|
+
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
480
|
+
|
481
|
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
482
|
+
|
483
|
+
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
484
|
+
|
485
|
+
if self.text_encoder_2 is not None:
|
486
|
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
487
|
+
else:
|
488
|
+
prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
489
|
+
|
490
|
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
491
|
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
492
|
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
493
|
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
494
|
+
|
495
|
+
if do_classifier_free_guidance:
|
496
|
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
497
|
+
seq_len = negative_prompt_embeds.shape[1]
|
498
|
+
|
499
|
+
if self.text_encoder_2 is not None:
|
500
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
501
|
+
else:
|
502
|
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
|
503
|
+
|
504
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
505
|
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
506
|
+
|
507
|
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
508
|
+
bs_embed * num_images_per_prompt, -1
|
509
|
+
)
|
510
|
+
if do_classifier_free_guidance:
|
511
|
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
512
|
+
bs_embed * num_images_per_prompt, -1
|
513
|
+
)
|
514
|
+
|
515
|
+
if self.text_encoder is not None:
|
516
|
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
517
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
518
|
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
519
|
+
|
520
|
+
if self.text_encoder_2 is not None:
|
521
|
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
522
|
+
# Retrieve the original scale by scaling back the LoRA layers
|
523
|
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
524
|
+
|
525
|
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
526
|
+
|
527
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
528
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
529
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
530
|
+
|
531
|
+
if not isinstance(image, torch.Tensor):
|
532
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
533
|
+
|
534
|
+
image = image.to(device=device, dtype=dtype)
|
535
|
+
if output_hidden_states:
|
536
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
537
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
538
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
539
|
+
torch.zeros_like(image), output_hidden_states=True
|
540
|
+
).hidden_states[-2]
|
541
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
542
|
+
num_images_per_prompt, dim=0
|
543
|
+
)
|
544
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
545
|
+
else:
|
546
|
+
image_embeds = self.image_encoder(image).image_embeds
|
547
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
548
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
549
|
+
|
550
|
+
return image_embeds, uncond_image_embeds
|
551
|
+
|
552
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
553
|
+
def prepare_ip_adapter_image_embeds(
|
554
|
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
555
|
+
):
|
556
|
+
image_embeds = []
|
557
|
+
if do_classifier_free_guidance:
|
558
|
+
negative_image_embeds = []
|
559
|
+
if ip_adapter_image_embeds is None:
|
560
|
+
if not isinstance(ip_adapter_image, list):
|
561
|
+
ip_adapter_image = [ip_adapter_image]
|
562
|
+
|
563
|
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
564
|
+
raise ValueError(
|
565
|
+
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."
|
566
|
+
)
|
567
|
+
|
568
|
+
for single_ip_adapter_image, image_proj_layer in zip(
|
569
|
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
570
|
+
):
|
571
|
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
572
|
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
573
|
+
single_ip_adapter_image, device, 1, output_hidden_state
|
574
|
+
)
|
575
|
+
|
576
|
+
image_embeds.append(single_image_embeds[None, :])
|
577
|
+
if do_classifier_free_guidance:
|
578
|
+
negative_image_embeds.append(single_negative_image_embeds[None, :])
|
579
|
+
else:
|
580
|
+
for single_image_embeds in ip_adapter_image_embeds:
|
581
|
+
if do_classifier_free_guidance:
|
582
|
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
583
|
+
negative_image_embeds.append(single_negative_image_embeds)
|
584
|
+
image_embeds.append(single_image_embeds)
|
585
|
+
|
586
|
+
ip_adapter_image_embeds = []
|
587
|
+
for i, single_image_embeds in enumerate(image_embeds):
|
588
|
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
589
|
+
if do_classifier_free_guidance:
|
590
|
+
single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
|
591
|
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
|
592
|
+
|
593
|
+
single_image_embeds = single_image_embeds.to(device=device)
|
594
|
+
ip_adapter_image_embeds.append(single_image_embeds)
|
595
|
+
|
596
|
+
return ip_adapter_image_embeds
|
597
|
+
|
598
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
599
|
+
def prepare_extra_step_kwargs(self, generator, eta):
|
600
|
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
601
|
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
602
|
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
603
|
+
# and should be between [0, 1]
|
604
|
+
|
605
|
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
606
|
+
extra_step_kwargs = {}
|
607
|
+
if accepts_eta:
|
608
|
+
extra_step_kwargs["eta"] = eta
|
609
|
+
|
610
|
+
# check if the scheduler accepts generator
|
611
|
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
612
|
+
if accepts_generator:
|
613
|
+
extra_step_kwargs["generator"] = generator
|
614
|
+
return extra_step_kwargs
|
615
|
+
|
616
|
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl_img2img.StableDiffusionXLControlNetImg2ImgPipeline.check_inputs
|
617
|
+
def check_inputs(
|
618
|
+
self,
|
619
|
+
prompt,
|
620
|
+
prompt_2,
|
621
|
+
image,
|
622
|
+
strength,
|
623
|
+
num_inference_steps,
|
624
|
+
callback_steps,
|
625
|
+
negative_prompt=None,
|
626
|
+
negative_prompt_2=None,
|
627
|
+
prompt_embeds=None,
|
628
|
+
negative_prompt_embeds=None,
|
629
|
+
pooled_prompt_embeds=None,
|
630
|
+
negative_pooled_prompt_embeds=None,
|
631
|
+
ip_adapter_image=None,
|
632
|
+
ip_adapter_image_embeds=None,
|
633
|
+
controlnet_conditioning_scale=1.0,
|
634
|
+
control_guidance_start=0.0,
|
635
|
+
control_guidance_end=1.0,
|
636
|
+
callback_on_step_end_tensor_inputs=None,
|
637
|
+
):
|
638
|
+
if strength < 0 or strength > 1:
|
639
|
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
640
|
+
if num_inference_steps is None:
|
641
|
+
raise ValueError("`num_inference_steps` cannot be None.")
|
642
|
+
elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
|
643
|
+
raise ValueError(
|
644
|
+
f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
|
645
|
+
f" {type(num_inference_steps)}."
|
646
|
+
)
|
647
|
+
|
648
|
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
649
|
+
raise ValueError(
|
650
|
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
651
|
+
f" {type(callback_steps)}."
|
652
|
+
)
|
653
|
+
|
654
|
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
655
|
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
656
|
+
):
|
657
|
+
raise ValueError(
|
658
|
+
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]}"
|
659
|
+
)
|
660
|
+
|
661
|
+
if prompt is not None and prompt_embeds is not None:
|
662
|
+
raise ValueError(
|
663
|
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
664
|
+
" only forward one of the two."
|
665
|
+
)
|
666
|
+
elif prompt_2 is not None and prompt_embeds is not None:
|
667
|
+
raise ValueError(
|
668
|
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
669
|
+
" only forward one of the two."
|
670
|
+
)
|
671
|
+
elif prompt is None and prompt_embeds is None:
|
672
|
+
raise ValueError(
|
673
|
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
674
|
+
)
|
675
|
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
676
|
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
677
|
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
678
|
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
679
|
+
|
680
|
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
681
|
+
raise ValueError(
|
682
|
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
683
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
684
|
+
)
|
685
|
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
686
|
+
raise ValueError(
|
687
|
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
688
|
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
689
|
+
)
|
690
|
+
|
691
|
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
692
|
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
693
|
+
raise ValueError(
|
694
|
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
695
|
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
696
|
+
f" {negative_prompt_embeds.shape}."
|
697
|
+
)
|
698
|
+
|
699
|
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
700
|
+
raise ValueError(
|
701
|
+
"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`."
|
702
|
+
)
|
703
|
+
|
704
|
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
705
|
+
raise ValueError(
|
706
|
+
"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`."
|
707
|
+
)
|
708
|
+
|
709
|
+
# `prompt` needs more sophisticated handling when there are multiple
|
710
|
+
# conditionings.
|
711
|
+
if isinstance(self.controlnet, MultiControlNetModel):
|
712
|
+
if isinstance(prompt, list):
|
713
|
+
logger.warning(
|
714
|
+
f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
|
715
|
+
" prompts. The conditionings will be fixed across the prompts."
|
716
|
+
)
|
717
|
+
|
718
|
+
# Check `image`
|
719
|
+
is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
|
720
|
+
self.controlnet, torch._dynamo.eval_frame.OptimizedModule
|
721
|
+
)
|
722
|
+
if (
|
723
|
+
isinstance(self.controlnet, ControlNetModel)
|
724
|
+
or is_compiled
|
725
|
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
726
|
+
):
|
727
|
+
self.check_image(image, prompt, prompt_embeds)
|
728
|
+
elif (
|
729
|
+
isinstance(self.controlnet, MultiControlNetModel)
|
730
|
+
or is_compiled
|
731
|
+
and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
|
732
|
+
):
|
733
|
+
if not isinstance(image, list):
|
734
|
+
raise TypeError("For multiple controlnets: `image` must be type `list`")
|
735
|
+
|
736
|
+
# When `image` is a nested list:
|
737
|
+
# (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
|
738
|
+
elif any(isinstance(i, list) for i in image):
|
739
|
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
740
|
+
elif len(image) != len(self.controlnet.nets):
|
741
|
+
raise ValueError(
|
742
|
+
f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
|
743
|
+
)
|
744
|
+
|
745
|
+
for image_ in image:
|
746
|
+
self.check_image(image_, prompt, prompt_embeds)
|
747
|
+
else:
|
748
|
+
assert False
|
749
|
+
|
750
|
+
# Check `controlnet_conditioning_scale`
|
751
|
+
if (
|
752
|
+
isinstance(self.controlnet, ControlNetModel)
|
753
|
+
or is_compiled
|
754
|
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
755
|
+
):
|
756
|
+
if not isinstance(controlnet_conditioning_scale, float):
|
757
|
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
758
|
+
elif (
|
759
|
+
isinstance(self.controlnet, MultiControlNetModel)
|
760
|
+
or is_compiled
|
761
|
+
and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
|
762
|
+
):
|
763
|
+
if isinstance(controlnet_conditioning_scale, list):
|
764
|
+
if any(isinstance(i, list) for i in controlnet_conditioning_scale):
|
765
|
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
766
|
+
elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
|
767
|
+
self.controlnet.nets
|
768
|
+
):
|
769
|
+
raise ValueError(
|
770
|
+
"For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
|
771
|
+
" the same length as the number of controlnets"
|
772
|
+
)
|
773
|
+
else:
|
774
|
+
assert False
|
775
|
+
|
776
|
+
if not isinstance(control_guidance_start, (tuple, list)):
|
777
|
+
control_guidance_start = [control_guidance_start]
|
778
|
+
|
779
|
+
if not isinstance(control_guidance_end, (tuple, list)):
|
780
|
+
control_guidance_end = [control_guidance_end]
|
781
|
+
|
782
|
+
if len(control_guidance_start) != len(control_guidance_end):
|
783
|
+
raise ValueError(
|
784
|
+
f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
|
785
|
+
)
|
786
|
+
|
787
|
+
if isinstance(self.controlnet, MultiControlNetModel):
|
788
|
+
if len(control_guidance_start) != len(self.controlnet.nets):
|
789
|
+
raise ValueError(
|
790
|
+
f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
|
791
|
+
)
|
792
|
+
|
793
|
+
for start, end in zip(control_guidance_start, control_guidance_end):
|
794
|
+
if start >= end:
|
795
|
+
raise ValueError(
|
796
|
+
f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
|
797
|
+
)
|
798
|
+
if start < 0.0:
|
799
|
+
raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
|
800
|
+
if end > 1.0:
|
801
|
+
raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
|
802
|
+
|
803
|
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
804
|
+
raise ValueError(
|
805
|
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
806
|
+
)
|
807
|
+
|
808
|
+
if ip_adapter_image_embeds is not None:
|
809
|
+
if not isinstance(ip_adapter_image_embeds, list):
|
810
|
+
raise ValueError(
|
811
|
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
812
|
+
)
|
813
|
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
814
|
+
raise ValueError(
|
815
|
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
816
|
+
)
|
817
|
+
|
818
|
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.check_image
|
819
|
+
def check_image(self, image, prompt, prompt_embeds):
|
820
|
+
image_is_pil = isinstance(image, PIL.Image.Image)
|
821
|
+
image_is_tensor = isinstance(image, torch.Tensor)
|
822
|
+
image_is_np = isinstance(image, np.ndarray)
|
823
|
+
image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
|
824
|
+
image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
|
825
|
+
image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
|
826
|
+
|
827
|
+
if (
|
828
|
+
not image_is_pil
|
829
|
+
and not image_is_tensor
|
830
|
+
and not image_is_np
|
831
|
+
and not image_is_pil_list
|
832
|
+
and not image_is_tensor_list
|
833
|
+
and not image_is_np_list
|
834
|
+
):
|
835
|
+
raise TypeError(
|
836
|
+
f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
|
837
|
+
)
|
838
|
+
|
839
|
+
if image_is_pil:
|
840
|
+
image_batch_size = 1
|
841
|
+
else:
|
842
|
+
image_batch_size = len(image)
|
843
|
+
|
844
|
+
if prompt is not None and isinstance(prompt, str):
|
845
|
+
prompt_batch_size = 1
|
846
|
+
elif prompt is not None and isinstance(prompt, list):
|
847
|
+
prompt_batch_size = len(prompt)
|
848
|
+
elif prompt_embeds is not None:
|
849
|
+
prompt_batch_size = prompt_embeds.shape[0]
|
850
|
+
|
851
|
+
if image_batch_size != 1 and image_batch_size != prompt_batch_size:
|
852
|
+
raise ValueError(
|
853
|
+
f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
|
854
|
+
)
|
855
|
+
|
856
|
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.prepare_image
|
857
|
+
def prepare_control_image(
|
858
|
+
self,
|
859
|
+
image,
|
860
|
+
width,
|
861
|
+
height,
|
862
|
+
batch_size,
|
863
|
+
num_images_per_prompt,
|
864
|
+
device,
|
865
|
+
dtype,
|
866
|
+
do_classifier_free_guidance=False,
|
867
|
+
guess_mode=False,
|
868
|
+
):
|
869
|
+
image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
870
|
+
image_batch_size = image.shape[0]
|
871
|
+
|
872
|
+
if image_batch_size == 1:
|
873
|
+
repeat_by = batch_size
|
874
|
+
else:
|
875
|
+
# image batch size is the same as prompt batch size
|
876
|
+
repeat_by = num_images_per_prompt
|
877
|
+
|
878
|
+
image = image.repeat_interleave(repeat_by, dim=0)
|
879
|
+
|
880
|
+
image = image.to(device=device, dtype=dtype)
|
881
|
+
|
882
|
+
if do_classifier_free_guidance and not guess_mode:
|
883
|
+
image = torch.cat([image] * 2)
|
884
|
+
|
885
|
+
return image
|
886
|
+
|
887
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
|
888
|
+
def get_timesteps(self, num_inference_steps, strength, device):
|
889
|
+
# get the original timestep using init_timestep
|
890
|
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
891
|
+
|
892
|
+
t_start = max(num_inference_steps - init_timestep, 0)
|
893
|
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
894
|
+
if hasattr(self.scheduler, "set_begin_index"):
|
895
|
+
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
896
|
+
|
897
|
+
return timesteps, num_inference_steps - t_start
|
898
|
+
|
899
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.prepare_latents
|
900
|
+
def prepare_latents(
|
901
|
+
self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
|
902
|
+
):
|
903
|
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
904
|
+
raise ValueError(
|
905
|
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
906
|
+
)
|
907
|
+
|
908
|
+
latents_mean = latents_std = None
|
909
|
+
if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
|
910
|
+
latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
|
911
|
+
if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
|
912
|
+
latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
|
913
|
+
|
914
|
+
# Offload text encoder if `enable_model_cpu_offload` was enabled
|
915
|
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
916
|
+
self.text_encoder_2.to("cpu")
|
917
|
+
torch.cuda.empty_cache()
|
918
|
+
|
919
|
+
image = image.to(device=device, dtype=dtype)
|
920
|
+
|
921
|
+
batch_size = batch_size * num_images_per_prompt
|
922
|
+
|
923
|
+
if image.shape[1] == 4:
|
924
|
+
init_latents = image
|
925
|
+
|
926
|
+
else:
|
927
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
928
|
+
if self.vae.config.force_upcast:
|
929
|
+
image = image.float()
|
930
|
+
self.vae.to(dtype=torch.float32)
|
931
|
+
|
932
|
+
if isinstance(generator, list) and len(generator) != batch_size:
|
933
|
+
raise ValueError(
|
934
|
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
935
|
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
936
|
+
)
|
937
|
+
|
938
|
+
elif isinstance(generator, list):
|
939
|
+
if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
|
940
|
+
image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
|
941
|
+
elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
|
942
|
+
raise ValueError(
|
943
|
+
f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
|
944
|
+
)
|
945
|
+
|
946
|
+
init_latents = [
|
947
|
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
948
|
+
for i in range(batch_size)
|
949
|
+
]
|
950
|
+
init_latents = torch.cat(init_latents, dim=0)
|
951
|
+
else:
|
952
|
+
init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
953
|
+
|
954
|
+
if self.vae.config.force_upcast:
|
955
|
+
self.vae.to(dtype)
|
956
|
+
|
957
|
+
init_latents = init_latents.to(dtype)
|
958
|
+
if latents_mean is not None and latents_std is not None:
|
959
|
+
latents_mean = latents_mean.to(device=device, dtype=dtype)
|
960
|
+
latents_std = latents_std.to(device=device, dtype=dtype)
|
961
|
+
init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
|
962
|
+
else:
|
963
|
+
init_latents = self.vae.config.scaling_factor * init_latents
|
964
|
+
|
965
|
+
if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
|
966
|
+
# expand init_latents for batch_size
|
967
|
+
additional_image_per_prompt = batch_size // init_latents.shape[0]
|
968
|
+
init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
|
969
|
+
elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
|
970
|
+
raise ValueError(
|
971
|
+
f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
|
972
|
+
)
|
973
|
+
else:
|
974
|
+
init_latents = torch.cat([init_latents], dim=0)
|
975
|
+
|
976
|
+
if add_noise:
|
977
|
+
shape = init_latents.shape
|
978
|
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
979
|
+
# get latents
|
980
|
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
981
|
+
|
982
|
+
latents = init_latents
|
983
|
+
|
984
|
+
return latents
|
985
|
+
|
986
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline._get_add_time_ids
|
987
|
+
def _get_add_time_ids(
|
988
|
+
self,
|
989
|
+
original_size,
|
990
|
+
crops_coords_top_left,
|
991
|
+
target_size,
|
992
|
+
aesthetic_score,
|
993
|
+
negative_aesthetic_score,
|
994
|
+
negative_original_size,
|
995
|
+
negative_crops_coords_top_left,
|
996
|
+
negative_target_size,
|
997
|
+
dtype,
|
998
|
+
text_encoder_projection_dim=None,
|
999
|
+
):
|
1000
|
+
if self.config.requires_aesthetics_score:
|
1001
|
+
add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
|
1002
|
+
add_neg_time_ids = list(
|
1003
|
+
negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
|
1004
|
+
)
|
1005
|
+
else:
|
1006
|
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
1007
|
+
add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
|
1008
|
+
|
1009
|
+
passed_add_embed_dim = (
|
1010
|
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
|
1011
|
+
)
|
1012
|
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
1013
|
+
|
1014
|
+
if (
|
1015
|
+
expected_add_embed_dim > passed_add_embed_dim
|
1016
|
+
and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
|
1017
|
+
):
|
1018
|
+
raise ValueError(
|
1019
|
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
|
1020
|
+
)
|
1021
|
+
elif (
|
1022
|
+
expected_add_embed_dim < passed_add_embed_dim
|
1023
|
+
and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
|
1024
|
+
):
|
1025
|
+
raise ValueError(
|
1026
|
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
|
1027
|
+
)
|
1028
|
+
elif expected_add_embed_dim != passed_add_embed_dim:
|
1029
|
+
raise ValueError(
|
1030
|
+
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`."
|
1031
|
+
)
|
1032
|
+
|
1033
|
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
1034
|
+
add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
|
1035
|
+
|
1036
|
+
return add_time_ids, add_neg_time_ids
|
1037
|
+
|
1038
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
1039
|
+
def upcast_vae(self):
|
1040
|
+
dtype = self.vae.dtype
|
1041
|
+
self.vae.to(dtype=torch.float32)
|
1042
|
+
use_torch_2_0_or_xformers = isinstance(
|
1043
|
+
self.vae.decoder.mid_block.attentions[0].processor,
|
1044
|
+
(
|
1045
|
+
AttnProcessor2_0,
|
1046
|
+
XFormersAttnProcessor,
|
1047
|
+
),
|
1048
|
+
)
|
1049
|
+
# if xformers or torch_2_0 is used attention block does not need
|
1050
|
+
# to be in float32 which can save lots of memory
|
1051
|
+
if use_torch_2_0_or_xformers:
|
1052
|
+
self.vae.post_quant_conv.to(dtype)
|
1053
|
+
self.vae.decoder.conv_in.to(dtype)
|
1054
|
+
self.vae.decoder.mid_block.to(dtype)
|
1055
|
+
|
1056
|
+
@property
|
1057
|
+
def guidance_scale(self):
|
1058
|
+
return self._guidance_scale
|
1059
|
+
|
1060
|
+
@property
|
1061
|
+
def clip_skip(self):
|
1062
|
+
return self._clip_skip
|
1063
|
+
|
1064
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
1065
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
1066
|
+
# corresponds to doing no classifier free guidance.
|
1067
|
+
@property
|
1068
|
+
def do_classifier_free_guidance(self):
|
1069
|
+
return self._guidance_scale > 1
|
1070
|
+
|
1071
|
+
@property
|
1072
|
+
def cross_attention_kwargs(self):
|
1073
|
+
return self._cross_attention_kwargs
|
1074
|
+
|
1075
|
+
@property
|
1076
|
+
def num_timesteps(self):
|
1077
|
+
return self._num_timesteps
|
1078
|
+
|
1079
|
+
@torch.no_grad()
|
1080
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
1081
|
+
def __call__(
|
1082
|
+
self,
|
1083
|
+
prompt: Union[str, List[str]] = None,
|
1084
|
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
1085
|
+
image: PipelineImageInput = None,
|
1086
|
+
control_image: PipelineImageInput = None,
|
1087
|
+
height: Optional[int] = None,
|
1088
|
+
width: Optional[int] = None,
|
1089
|
+
strength: float = 0.8,
|
1090
|
+
num_inference_steps: int = 50,
|
1091
|
+
guidance_scale: float = 5.0,
|
1092
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
1093
|
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
1094
|
+
num_images_per_prompt: Optional[int] = 1,
|
1095
|
+
eta: float = 0.0,
|
1096
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
1097
|
+
latents: Optional[torch.Tensor] = None,
|
1098
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
1099
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
1100
|
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
1101
|
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
1102
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
1103
|
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
1104
|
+
output_type: Optional[str] = "pil",
|
1105
|
+
return_dict: bool = True,
|
1106
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
1107
|
+
controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
|
1108
|
+
guess_mode: bool = False,
|
1109
|
+
control_guidance_start: Union[float, List[float]] = 0.0,
|
1110
|
+
control_guidance_end: Union[float, List[float]] = 1.0,
|
1111
|
+
original_size: Tuple[int, int] = None,
|
1112
|
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
1113
|
+
target_size: Tuple[int, int] = None,
|
1114
|
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
1115
|
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
1116
|
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
1117
|
+
aesthetic_score: float = 6.0,
|
1118
|
+
negative_aesthetic_score: float = 2.5,
|
1119
|
+
clip_skip: Optional[int] = None,
|
1120
|
+
callback_on_step_end: Optional[
|
1121
|
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
1122
|
+
] = None,
|
1123
|
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
1124
|
+
pag_scale: float = 3.0,
|
1125
|
+
pag_adaptive_scale: float = 0.0,
|
1126
|
+
):
|
1127
|
+
r"""
|
1128
|
+
Function invoked when calling the pipeline for generation.
|
1129
|
+
|
1130
|
+
Args:
|
1131
|
+
prompt (`str` or `List[str]`, *optional*):
|
1132
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
1133
|
+
instead.
|
1134
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
1135
|
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
1136
|
+
used in both text-encoders
|
1137
|
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
1138
|
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
1139
|
+
The initial image will be used as the starting point for the image generation process. Can also accept
|
1140
|
+
image latents as `image`, if passing latents directly, it will not be encoded again.
|
1141
|
+
control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
1142
|
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
1143
|
+
The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
|
1144
|
+
the type is specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also
|
1145
|
+
be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
|
1146
|
+
and/or width are passed, `image` is resized according to them. If multiple ControlNets are specified in
|
1147
|
+
init, images must be passed as a list such that each element of the list can be correctly batched for
|
1148
|
+
input to a single controlnet.
|
1149
|
+
height (`int`, *optional*, defaults to the size of control_image):
|
1150
|
+
The height in pixels of the generated image. Anything below 512 pixels won't work well for
|
1151
|
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
1152
|
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
1153
|
+
width (`int`, *optional*, defaults to the size of control_image):
|
1154
|
+
The width in pixels of the generated image. Anything below 512 pixels won't work well for
|
1155
|
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
1156
|
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
1157
|
+
strength (`float`, *optional*, defaults to 0.8):
|
1158
|
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
1159
|
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
1160
|
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
1161
|
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
1162
|
+
essentially ignores `image`.
|
1163
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
1164
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
1165
|
+
expense of slower inference.
|
1166
|
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
1167
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
1168
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
1169
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
1170
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
1171
|
+
usually at the expense of lower image quality.
|
1172
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
1173
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
1174
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
1175
|
+
less than `1`).
|
1176
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
1177
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
1178
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
1179
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
1180
|
+
The number of images to generate per prompt.
|
1181
|
+
eta (`float`, *optional*, defaults to 0.0):
|
1182
|
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
1183
|
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
1184
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
1185
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
1186
|
+
to make generation deterministic.
|
1187
|
+
latents (`torch.Tensor`, *optional*):
|
1188
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
1189
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
1190
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
1191
|
+
prompt_embeds (`torch.Tensor`, *optional*):
|
1192
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
1193
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
1194
|
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
1195
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
1196
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
1197
|
+
argument.
|
1198
|
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
1199
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
1200
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
1201
|
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
1202
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
1203
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
1204
|
+
input argument.
|
1205
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
1206
|
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
1207
|
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
1208
|
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
1209
|
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
1210
|
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
1211
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
1212
|
+
The output format of the generate image. Choose between
|
1213
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
1214
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
1215
|
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
1216
|
+
plain tuple.
|
1217
|
+
cross_attention_kwargs (`dict`, *optional*):
|
1218
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
1219
|
+
`self.processor` in
|
1220
|
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
1221
|
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
1222
|
+
The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
|
1223
|
+
to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
|
1224
|
+
corresponding scale as a list.
|
1225
|
+
guess_mode (`bool`, *optional*, defaults to `False`):
|
1226
|
+
In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
|
1227
|
+
you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
|
1228
|
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
1229
|
+
The percentage of total steps at which the controlnet starts applying.
|
1230
|
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
1231
|
+
The percentage of total steps at which the controlnet stops applying.
|
1232
|
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1233
|
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
1234
|
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
1235
|
+
explained in section 2.2 of
|
1236
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1237
|
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
1238
|
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
1239
|
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
1240
|
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1241
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1242
|
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1243
|
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
1244
|
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
1245
|
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1246
|
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1247
|
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
1248
|
+
micro-conditioning as explained in section 2.2 of
|
1249
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1250
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1251
|
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
1252
|
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
1253
|
+
micro-conditioning as explained in section 2.2 of
|
1254
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1255
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1256
|
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
1257
|
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
1258
|
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1259
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
1260
|
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
1261
|
+
aesthetic_score (`float`, *optional*, defaults to 6.0):
|
1262
|
+
Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
|
1263
|
+
Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1264
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
1265
|
+
negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
|
1266
|
+
Part of SDXL's micro-conditioning as explained in section 2.2 of
|
1267
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
|
1268
|
+
simulate an aesthetic score of the generated image by influencing the negative text condition.
|
1269
|
+
clip_skip (`int`, *optional*):
|
1270
|
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
1271
|
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
1272
|
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
1273
|
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
1274
|
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
1275
|
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
1276
|
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
1277
|
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
1278
|
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
1279
|
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
1280
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
1281
|
+
pag_scale (`float`, *optional*, defaults to 3.0):
|
1282
|
+
The scale factor for the perturbed attention guidance. If it is set to 0.0, the perturbed attention
|
1283
|
+
guidance will not be used.
|
1284
|
+
pag_adaptive_scale (`float`, *optional*, defaults to 0.0):
|
1285
|
+
The adaptive scale factor for the perturbed attention guidance. If it is set to 0.0, `pag_scale` is
|
1286
|
+
used.
|
1287
|
+
|
1288
|
+
|
1289
|
+
Examples:
|
1290
|
+
|
1291
|
+
Returns:
|
1292
|
+
[`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
|
1293
|
+
[`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
|
1294
|
+
`tuple` containing the output images.
|
1295
|
+
"""
|
1296
|
+
|
1297
|
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
1298
|
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
1299
|
+
|
1300
|
+
controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
|
1301
|
+
|
1302
|
+
# align format for control guidance
|
1303
|
+
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
|
1304
|
+
control_guidance_start = len(control_guidance_end) * [control_guidance_start]
|
1305
|
+
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
|
1306
|
+
control_guidance_end = len(control_guidance_start) * [control_guidance_end]
|
1307
|
+
elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
|
1308
|
+
mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
|
1309
|
+
control_guidance_start, control_guidance_end = (
|
1310
|
+
mult * [control_guidance_start],
|
1311
|
+
mult * [control_guidance_end],
|
1312
|
+
)
|
1313
|
+
|
1314
|
+
# 1. Check inputs. Raise error if not correct
|
1315
|
+
self.check_inputs(
|
1316
|
+
prompt,
|
1317
|
+
prompt_2,
|
1318
|
+
control_image,
|
1319
|
+
strength,
|
1320
|
+
num_inference_steps,
|
1321
|
+
None,
|
1322
|
+
negative_prompt,
|
1323
|
+
negative_prompt_2,
|
1324
|
+
prompt_embeds,
|
1325
|
+
negative_prompt_embeds,
|
1326
|
+
pooled_prompt_embeds,
|
1327
|
+
negative_pooled_prompt_embeds,
|
1328
|
+
ip_adapter_image,
|
1329
|
+
ip_adapter_image_embeds,
|
1330
|
+
controlnet_conditioning_scale,
|
1331
|
+
control_guidance_start,
|
1332
|
+
control_guidance_end,
|
1333
|
+
callback_on_step_end_tensor_inputs,
|
1334
|
+
)
|
1335
|
+
|
1336
|
+
self._guidance_scale = guidance_scale
|
1337
|
+
self._clip_skip = clip_skip
|
1338
|
+
self._cross_attention_kwargs = cross_attention_kwargs
|
1339
|
+
self._pag_scale = pag_scale
|
1340
|
+
self._pag_adaptive_scale = pag_adaptive_scale
|
1341
|
+
|
1342
|
+
# 2. Define call parameters
|
1343
|
+
if prompt is not None and isinstance(prompt, str):
|
1344
|
+
batch_size = 1
|
1345
|
+
elif prompt is not None and isinstance(prompt, list):
|
1346
|
+
batch_size = len(prompt)
|
1347
|
+
else:
|
1348
|
+
batch_size = prompt_embeds.shape[0]
|
1349
|
+
|
1350
|
+
device = self._execution_device
|
1351
|
+
|
1352
|
+
if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
|
1353
|
+
controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
|
1354
|
+
|
1355
|
+
# 3.1 Encode input prompt
|
1356
|
+
text_encoder_lora_scale = (
|
1357
|
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
1358
|
+
)
|
1359
|
+
(
|
1360
|
+
prompt_embeds,
|
1361
|
+
negative_prompt_embeds,
|
1362
|
+
pooled_prompt_embeds,
|
1363
|
+
negative_pooled_prompt_embeds,
|
1364
|
+
) = self.encode_prompt(
|
1365
|
+
prompt,
|
1366
|
+
prompt_2,
|
1367
|
+
device,
|
1368
|
+
num_images_per_prompt,
|
1369
|
+
self.do_classifier_free_guidance,
|
1370
|
+
negative_prompt,
|
1371
|
+
negative_prompt_2,
|
1372
|
+
prompt_embeds=prompt_embeds,
|
1373
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
1374
|
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
1375
|
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
1376
|
+
lora_scale=text_encoder_lora_scale,
|
1377
|
+
clip_skip=self.clip_skip,
|
1378
|
+
)
|
1379
|
+
|
1380
|
+
# 3.2 Encode ip_adapter_image
|
1381
|
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
1382
|
+
ip_adapter_image_embeds = self.prepare_ip_adapter_image_embeds(
|
1383
|
+
ip_adapter_image,
|
1384
|
+
ip_adapter_image_embeds,
|
1385
|
+
device,
|
1386
|
+
batch_size * num_images_per_prompt,
|
1387
|
+
self.do_classifier_free_guidance,
|
1388
|
+
)
|
1389
|
+
|
1390
|
+
# 4. Prepare image and controlnet_conditioning_image
|
1391
|
+
image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
1392
|
+
|
1393
|
+
if isinstance(controlnet, ControlNetModel):
|
1394
|
+
control_image = self.prepare_control_image(
|
1395
|
+
image=control_image,
|
1396
|
+
width=width,
|
1397
|
+
height=height,
|
1398
|
+
batch_size=batch_size * num_images_per_prompt,
|
1399
|
+
num_images_per_prompt=num_images_per_prompt,
|
1400
|
+
device=device,
|
1401
|
+
dtype=controlnet.dtype,
|
1402
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1403
|
+
guess_mode=False,
|
1404
|
+
)
|
1405
|
+
height, width = control_image.shape[-2:]
|
1406
|
+
elif isinstance(controlnet, MultiControlNetModel):
|
1407
|
+
control_images = []
|
1408
|
+
|
1409
|
+
for control_image_ in control_image:
|
1410
|
+
control_image_ = self.prepare_control_image(
|
1411
|
+
image=control_image_,
|
1412
|
+
width=width,
|
1413
|
+
height=height,
|
1414
|
+
batch_size=batch_size * num_images_per_prompt,
|
1415
|
+
num_images_per_prompt=num_images_per_prompt,
|
1416
|
+
device=device,
|
1417
|
+
dtype=controlnet.dtype,
|
1418
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1419
|
+
guess_mode=False,
|
1420
|
+
)
|
1421
|
+
|
1422
|
+
control_images.append(control_image_)
|
1423
|
+
|
1424
|
+
control_image = control_images
|
1425
|
+
height, width = control_image[0].shape[-2:]
|
1426
|
+
else:
|
1427
|
+
assert False
|
1428
|
+
|
1429
|
+
# 5. Prepare timesteps
|
1430
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
1431
|
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
1432
|
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
1433
|
+
self._num_timesteps = len(timesteps)
|
1434
|
+
|
1435
|
+
# 6. Prepare latent variables
|
1436
|
+
if latents is None:
|
1437
|
+
latents = self.prepare_latents(
|
1438
|
+
image,
|
1439
|
+
latent_timestep,
|
1440
|
+
batch_size,
|
1441
|
+
num_images_per_prompt,
|
1442
|
+
prompt_embeds.dtype,
|
1443
|
+
device,
|
1444
|
+
generator,
|
1445
|
+
True,
|
1446
|
+
)
|
1447
|
+
|
1448
|
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
1449
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1450
|
+
|
1451
|
+
# 7.1 Create tensor stating which controlnets to keep
|
1452
|
+
controlnet_keep = []
|
1453
|
+
for i in range(len(timesteps)):
|
1454
|
+
keeps = [
|
1455
|
+
1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
|
1456
|
+
for s, e in zip(control_guidance_start, control_guidance_end)
|
1457
|
+
]
|
1458
|
+
controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
|
1459
|
+
|
1460
|
+
# 7.2 Prepare added time ids & embeddings
|
1461
|
+
if isinstance(control_image, list):
|
1462
|
+
original_size = original_size or control_image[0].shape[-2:]
|
1463
|
+
else:
|
1464
|
+
original_size = original_size or control_image.shape[-2:]
|
1465
|
+
target_size = target_size or (height, width)
|
1466
|
+
|
1467
|
+
if negative_original_size is None:
|
1468
|
+
negative_original_size = original_size
|
1469
|
+
if negative_target_size is None:
|
1470
|
+
negative_target_size = target_size
|
1471
|
+
add_text_embeds = pooled_prompt_embeds
|
1472
|
+
|
1473
|
+
if self.text_encoder_2 is None:
|
1474
|
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
1475
|
+
else:
|
1476
|
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
1477
|
+
|
1478
|
+
add_time_ids, add_neg_time_ids = self._get_add_time_ids(
|
1479
|
+
original_size,
|
1480
|
+
crops_coords_top_left,
|
1481
|
+
target_size,
|
1482
|
+
aesthetic_score,
|
1483
|
+
negative_aesthetic_score,
|
1484
|
+
negative_original_size,
|
1485
|
+
negative_crops_coords_top_left,
|
1486
|
+
negative_target_size,
|
1487
|
+
dtype=prompt_embeds.dtype,
|
1488
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
1489
|
+
)
|
1490
|
+
add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
|
1491
|
+
add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
|
1492
|
+
|
1493
|
+
control_images = control_image if isinstance(control_image, list) else [control_image]
|
1494
|
+
for i, single_image in enumerate(control_images):
|
1495
|
+
if self.do_classifier_free_guidance:
|
1496
|
+
single_image = single_image.chunk(2)[0]
|
1497
|
+
|
1498
|
+
if self.do_perturbed_attention_guidance:
|
1499
|
+
single_image = self._prepare_perturbed_attention_guidance(
|
1500
|
+
single_image, single_image, self.do_classifier_free_guidance
|
1501
|
+
)
|
1502
|
+
elif self.do_classifier_free_guidance:
|
1503
|
+
single_image = torch.cat([single_image] * 2)
|
1504
|
+
single_image = single_image.to(device)
|
1505
|
+
control_images[i] = single_image
|
1506
|
+
|
1507
|
+
control_image = control_images if isinstance(control_image, list) else control_images[0]
|
1508
|
+
|
1509
|
+
if ip_adapter_image_embeds is not None:
|
1510
|
+
for i, image_embeds in enumerate(ip_adapter_image_embeds):
|
1511
|
+
negative_image_embeds = None
|
1512
|
+
if self.do_classifier_free_guidance:
|
1513
|
+
negative_image_embeds, image_embeds = image_embeds.chunk(2)
|
1514
|
+
|
1515
|
+
if self.do_perturbed_attention_guidance:
|
1516
|
+
image_embeds = self._prepare_perturbed_attention_guidance(
|
1517
|
+
image_embeds, negative_image_embeds, self.do_classifier_free_guidance
|
1518
|
+
)
|
1519
|
+
elif self.do_classifier_free_guidance:
|
1520
|
+
image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0)
|
1521
|
+
image_embeds = image_embeds.to(device)
|
1522
|
+
ip_adapter_image_embeds[i] = image_embeds
|
1523
|
+
|
1524
|
+
if self.do_perturbed_attention_guidance:
|
1525
|
+
prompt_embeds = self._prepare_perturbed_attention_guidance(
|
1526
|
+
prompt_embeds, negative_prompt_embeds, self.do_classifier_free_guidance
|
1527
|
+
)
|
1528
|
+
add_text_embeds = self._prepare_perturbed_attention_guidance(
|
1529
|
+
add_text_embeds, negative_pooled_prompt_embeds, self.do_classifier_free_guidance
|
1530
|
+
)
|
1531
|
+
add_time_ids = self._prepare_perturbed_attention_guidance(
|
1532
|
+
add_time_ids, add_neg_time_ids, self.do_classifier_free_guidance
|
1533
|
+
)
|
1534
|
+
elif self.do_classifier_free_guidance:
|
1535
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1536
|
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
1537
|
+
add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
|
1538
|
+
|
1539
|
+
prompt_embeds = prompt_embeds.to(device)
|
1540
|
+
add_text_embeds = add_text_embeds.to(device)
|
1541
|
+
add_time_ids = add_time_ids.to(device)
|
1542
|
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
1543
|
+
|
1544
|
+
controlnet_prompt_embeds = prompt_embeds
|
1545
|
+
controlnet_added_cond_kwargs = added_cond_kwargs
|
1546
|
+
|
1547
|
+
# 8. Denoising loop
|
1548
|
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
1549
|
+
|
1550
|
+
if self.do_perturbed_attention_guidance:
|
1551
|
+
original_attn_proc = self.unet.attn_processors
|
1552
|
+
self._set_pag_attn_processor(
|
1553
|
+
pag_applied_layers=self.pag_applied_layers,
|
1554
|
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
1555
|
+
)
|
1556
|
+
|
1557
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1558
|
+
for i, t in enumerate(timesteps):
|
1559
|
+
# expand the latents if we are doing classifier free guidance
|
1560
|
+
latent_model_input = torch.cat([latents] * (prompt_embeds.shape[0] // latents.shape[0]))
|
1561
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
1562
|
+
|
1563
|
+
# controlnet(s) inference
|
1564
|
+
control_model_input = latent_model_input
|
1565
|
+
|
1566
|
+
if isinstance(controlnet_keep[i], list):
|
1567
|
+
cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
|
1568
|
+
else:
|
1569
|
+
controlnet_cond_scale = controlnet_conditioning_scale
|
1570
|
+
if isinstance(controlnet_cond_scale, list):
|
1571
|
+
controlnet_cond_scale = controlnet_cond_scale[0]
|
1572
|
+
cond_scale = controlnet_cond_scale * controlnet_keep[i]
|
1573
|
+
down_block_res_samples, mid_block_res_sample = self.controlnet(
|
1574
|
+
control_model_input,
|
1575
|
+
t,
|
1576
|
+
encoder_hidden_states=controlnet_prompt_embeds,
|
1577
|
+
controlnet_cond=control_image,
|
1578
|
+
conditioning_scale=cond_scale,
|
1579
|
+
guess_mode=False,
|
1580
|
+
added_cond_kwargs=controlnet_added_cond_kwargs,
|
1581
|
+
return_dict=False,
|
1582
|
+
)
|
1583
|
+
|
1584
|
+
if ip_adapter_image_embeds is not None:
|
1585
|
+
added_cond_kwargs["image_embeds"] = ip_adapter_image_embeds
|
1586
|
+
|
1587
|
+
# predict the noise residual
|
1588
|
+
noise_pred = self.unet(
|
1589
|
+
latent_model_input,
|
1590
|
+
t,
|
1591
|
+
encoder_hidden_states=prompt_embeds,
|
1592
|
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
1593
|
+
down_block_additional_residuals=down_block_res_samples,
|
1594
|
+
mid_block_additional_residual=mid_block_res_sample,
|
1595
|
+
added_cond_kwargs=added_cond_kwargs,
|
1596
|
+
return_dict=False,
|
1597
|
+
)[0]
|
1598
|
+
|
1599
|
+
# perform guidance
|
1600
|
+
if self.do_perturbed_attention_guidance:
|
1601
|
+
noise_pred = self._apply_perturbed_attention_guidance(
|
1602
|
+
noise_pred, self.do_classifier_free_guidance, self.guidance_scale, t
|
1603
|
+
)
|
1604
|
+
elif self.do_classifier_free_guidance:
|
1605
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
1606
|
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
1607
|
+
|
1608
|
+
# compute the previous noisy sample x_t -> x_t-1
|
1609
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
1610
|
+
|
1611
|
+
if callback_on_step_end is not None:
|
1612
|
+
callback_kwargs = {}
|
1613
|
+
for k in callback_on_step_end_tensor_inputs:
|
1614
|
+
callback_kwargs[k] = locals()[k]
|
1615
|
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
1616
|
+
|
1617
|
+
latents = callback_outputs.pop("latents", latents)
|
1618
|
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
1619
|
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
1620
|
+
add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
|
1621
|
+
negative_pooled_prompt_embeds = callback_outputs.pop(
|
1622
|
+
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
1623
|
+
)
|
1624
|
+
add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
|
1625
|
+
add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
|
1626
|
+
|
1627
|
+
# call the callback, if provided
|
1628
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
1629
|
+
progress_bar.update()
|
1630
|
+
|
1631
|
+
# If we do sequential model offloading, let's offload unet and controlnet
|
1632
|
+
# manually for max memory savings
|
1633
|
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
1634
|
+
self.unet.to("cpu")
|
1635
|
+
self.controlnet.to("cpu")
|
1636
|
+
torch.cuda.empty_cache()
|
1637
|
+
|
1638
|
+
if not output_type == "latent":
|
1639
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
1640
|
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1641
|
+
|
1642
|
+
if needs_upcasting:
|
1643
|
+
self.upcast_vae()
|
1644
|
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
1645
|
+
|
1646
|
+
# unscale/denormalize the latents
|
1647
|
+
# denormalize with the mean and std if available and not None
|
1648
|
+
has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
|
1649
|
+
has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
|
1650
|
+
if has_latents_mean and has_latents_std:
|
1651
|
+
latents_mean = (
|
1652
|
+
torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
1653
|
+
)
|
1654
|
+
latents_std = (
|
1655
|
+
torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
1656
|
+
)
|
1657
|
+
latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
|
1658
|
+
else:
|
1659
|
+
latents = latents / self.vae.config.scaling_factor
|
1660
|
+
|
1661
|
+
image = self.vae.decode(latents, return_dict=False)[0]
|
1662
|
+
|
1663
|
+
# cast back to fp16 if needed
|
1664
|
+
if needs_upcasting:
|
1665
|
+
self.vae.to(dtype=torch.float16)
|
1666
|
+
else:
|
1667
|
+
image = latents
|
1668
|
+
return StableDiffusionXLPipelineOutput(images=image)
|
1669
|
+
|
1670
|
+
# apply watermark if available
|
1671
|
+
if self.watermark is not None:
|
1672
|
+
image = self.watermark.apply_watermark(image)
|
1673
|
+
|
1674
|
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1675
|
+
|
1676
|
+
# Offload all models
|
1677
|
+
self.maybe_free_model_hooks()
|
1678
|
+
|
1679
|
+
if self.do_perturbed_attention_guidance:
|
1680
|
+
self.unet.set_attn_processor(original_attn_proc)
|
1681
|
+
|
1682
|
+
if not return_dict:
|
1683
|
+
return (image,)
|
1684
|
+
|
1685
|
+
return StableDiffusionXLPipelineOutput(images=image)
|