diffusers 0.23.1__py3-none-any.whl → 0.25.0__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- diffusers/__init__.py +26 -2
- diffusers/commands/fp16_safetensors.py +10 -11
- diffusers/configuration_utils.py +13 -8
- diffusers/dependency_versions_check.py +0 -1
- diffusers/dependency_versions_table.py +5 -5
- diffusers/experimental/rl/value_guided_sampling.py +1 -1
- diffusers/image_processor.py +463 -51
- diffusers/loaders/__init__.py +82 -0
- diffusers/loaders/ip_adapter.py +159 -0
- diffusers/loaders/lora.py +1553 -0
- diffusers/loaders/lora_conversion_utils.py +284 -0
- diffusers/loaders/single_file.py +637 -0
- diffusers/loaders/textual_inversion.py +455 -0
- diffusers/loaders/unet.py +828 -0
- diffusers/loaders/utils.py +59 -0
- diffusers/models/__init__.py +26 -9
- diffusers/models/activations.py +9 -6
- diffusers/models/attention.py +301 -29
- diffusers/models/attention_flax.py +9 -1
- diffusers/models/attention_processor.py +378 -6
- diffusers/models/autoencoders/__init__.py +5 -0
- diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +17 -12
- diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +47 -23
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +402 -0
- diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +24 -28
- diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +51 -44
- diffusers/models/{vae.py → autoencoders/vae.py} +71 -17
- diffusers/models/controlnet.py +59 -39
- diffusers/models/controlnet_flax.py +19 -18
- diffusers/models/downsampling.py +338 -0
- diffusers/models/embeddings.py +112 -29
- diffusers/models/embeddings_flax.py +2 -0
- diffusers/models/lora.py +131 -1
- diffusers/models/modeling_flax_utils.py +14 -8
- diffusers/models/modeling_outputs.py +17 -0
- diffusers/models/modeling_utils.py +37 -29
- diffusers/models/normalization.py +110 -4
- diffusers/models/resnet.py +299 -652
- diffusers/models/transformer_2d.py +22 -5
- diffusers/models/transformer_temporal.py +183 -1
- diffusers/models/unet_2d_blocks_flax.py +5 -0
- diffusers/models/unet_2d_condition.py +46 -0
- diffusers/models/unet_2d_condition_flax.py +13 -13
- diffusers/models/unet_3d_blocks.py +957 -173
- diffusers/models/unet_3d_condition.py +16 -8
- diffusers/models/unet_kandinsky3.py +535 -0
- diffusers/models/unet_motion_model.py +48 -33
- diffusers/models/unet_spatio_temporal_condition.py +489 -0
- diffusers/models/upsampling.py +454 -0
- diffusers/models/uvit_2d.py +471 -0
- diffusers/models/vae_flax.py +7 -0
- diffusers/models/vq_model.py +12 -3
- diffusers/optimization.py +16 -9
- diffusers/pipelines/__init__.py +137 -76
- diffusers/pipelines/amused/__init__.py +62 -0
- diffusers/pipelines/amused/pipeline_amused.py +328 -0
- diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +66 -8
- diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
- diffusers/pipelines/auto_pipeline.py +23 -13
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
- diffusers/pipelines/controlnet/pipeline_controlnet.py +238 -35
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +148 -37
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +155 -41
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +123 -43
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +216 -39
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +106 -34
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
- diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
- diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
- diffusers/pipelines/deprecated/__init__.py +153 -0
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +177 -34
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +182 -37
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
- diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
- diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
- diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
- diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
- diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
- diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
- diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
- diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +5 -4
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
- diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +8 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +34 -13
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +7 -6
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +12 -11
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +17 -11
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +11 -10
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +14 -13
- diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
- diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +83 -51
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +7 -6
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +7 -6
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +7 -6
- diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
- diffusers/pipelines/dit/pipeline_dit.py +1 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
- diffusers/pipelines/kandinsky3/__init__.py +49 -0
- diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +111 -11
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +102 -9
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
- diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
- diffusers/pipelines/onnx_utils.py +8 -5
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
- diffusers/pipelines/pipeline_flax_utils.py +11 -8
- diffusers/pipelines/pipeline_utils.py +63 -42
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +247 -38
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
- diffusers/pipelines/stable_diffusion/__init__.py +37 -65
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +75 -78
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +174 -11
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +178 -11
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +224 -13
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +74 -20
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +7 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +6 -2
- diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +3 -3
- diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +3 -2
- diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +4 -3
- diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +7 -1
- diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +51 -7
- diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +57 -8
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
- diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +68 -10
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +194 -17
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +205 -16
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +206 -17
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +23 -17
- diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +652 -0
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +115 -14
- diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +6 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +23 -3
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +334 -10
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +1331 -0
- diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -1
- diffusers/schedulers/__init__.py +4 -4
- diffusers/schedulers/deprecated/__init__.py +50 -0
- diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
- diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
- diffusers/schedulers/scheduling_amused.py +162 -0
- diffusers/schedulers/scheduling_consistency_models.py +2 -0
- diffusers/schedulers/scheduling_ddim.py +1 -3
- diffusers/schedulers/scheduling_ddim_inverse.py +2 -7
- diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
- diffusers/schedulers/scheduling_ddpm.py +47 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +47 -3
- diffusers/schedulers/scheduling_deis_multistep.py +28 -6
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +28 -6
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +28 -6
- diffusers/schedulers/scheduling_dpmsolver_sde.py +3 -3
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +28 -6
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +59 -3
- diffusers/schedulers/scheduling_euler_discrete.py +102 -16
- diffusers/schedulers/scheduling_heun_discrete.py +17 -5
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +17 -5
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +17 -5
- diffusers/schedulers/scheduling_lcm.py +123 -29
- diffusers/schedulers/scheduling_lms_discrete.py +3 -3
- diffusers/schedulers/scheduling_pndm.py +1 -3
- diffusers/schedulers/scheduling_repaint.py +1 -3
- diffusers/schedulers/scheduling_unipc_multistep.py +28 -6
- diffusers/schedulers/scheduling_utils.py +3 -1
- diffusers/schedulers/scheduling_utils_flax.py +3 -1
- diffusers/training_utils.py +1 -1
- diffusers/utils/__init__.py +1 -2
- diffusers/utils/constants.py +10 -12
- diffusers/utils/dummy_pt_objects.py +75 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
- diffusers/utils/dynamic_modules_utils.py +18 -22
- diffusers/utils/export_utils.py +8 -3
- diffusers/utils/hub_utils.py +24 -36
- diffusers/utils/logging.py +11 -11
- diffusers/utils/outputs.py +5 -5
- diffusers/utils/peft_utils.py +88 -44
- diffusers/utils/state_dict_utils.py +8 -0
- diffusers/utils/testing_utils.py +199 -1
- diffusers/utils/torch_utils.py +4 -4
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/METADATA +86 -69
- diffusers-0.25.0.dist-info/RECORD +360 -0
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
- diffusers/loaders.py +0 -3336
- diffusers-0.23.1.dist-info/RECORD +0 -323
- /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
- {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
@@ -19,12 +19,13 @@ import numpy as np
|
|
19
19
|
import PIL.Image
|
20
20
|
import torch
|
21
21
|
from packaging import version
|
22
|
-
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
22
|
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
23
23
|
|
24
24
|
from ...configuration_utils import FrozenDict
|
25
25
|
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
26
|
-
from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
27
|
-
from ...models import AsymmetricAutoencoderKL, AutoencoderKL, UNet2DConditionModel
|
26
|
+
from ...loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
27
|
+
from ...models import AsymmetricAutoencoderKL, AutoencoderKL, ImageProjection, UNet2DConditionModel
|
28
|
+
from ...models.attention_processor import FusedAttnProcessor2_0
|
28
29
|
from ...models.lora import adjust_lora_scale_text_encoder
|
29
30
|
from ...schedulers import KarrasDiffusionSchedulers
|
30
31
|
from ...utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
|
@@ -160,17 +161,66 @@ def prepare_mask_and_masked_image(image, mask, height, width, return_image: bool
|
|
160
161
|
|
161
162
|
|
162
163
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
163
|
-
def retrieve_latents(
|
164
|
-
|
164
|
+
def retrieve_latents(
|
165
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
166
|
+
):
|
167
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
165
168
|
return encoder_output.latent_dist.sample(generator)
|
169
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
170
|
+
return encoder_output.latent_dist.mode()
|
166
171
|
elif hasattr(encoder_output, "latents"):
|
167
172
|
return encoder_output.latents
|
168
173
|
else:
|
169
174
|
raise AttributeError("Could not access latents of provided encoder_output")
|
170
175
|
|
171
176
|
|
177
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
178
|
+
def retrieve_timesteps(
|
179
|
+
scheduler,
|
180
|
+
num_inference_steps: Optional[int] = None,
|
181
|
+
device: Optional[Union[str, torch.device]] = None,
|
182
|
+
timesteps: Optional[List[int]] = None,
|
183
|
+
**kwargs,
|
184
|
+
):
|
185
|
+
"""
|
186
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
187
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
188
|
+
|
189
|
+
Args:
|
190
|
+
scheduler (`SchedulerMixin`):
|
191
|
+
The scheduler to get timesteps from.
|
192
|
+
num_inference_steps (`int`):
|
193
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
194
|
+
`timesteps` must be `None`.
|
195
|
+
device (`str` or `torch.device`, *optional*):
|
196
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
197
|
+
timesteps (`List[int]`, *optional*):
|
198
|
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
199
|
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
200
|
+
must be `None`.
|
201
|
+
|
202
|
+
Returns:
|
203
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
204
|
+
second element is the number of inference steps.
|
205
|
+
"""
|
206
|
+
if timesteps is not None:
|
207
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
208
|
+
if not accepts_timesteps:
|
209
|
+
raise ValueError(
|
210
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
211
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
212
|
+
)
|
213
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
214
|
+
timesteps = scheduler.timesteps
|
215
|
+
num_inference_steps = len(timesteps)
|
216
|
+
else:
|
217
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
218
|
+
timesteps = scheduler.timesteps
|
219
|
+
return timesteps, num_inference_steps
|
220
|
+
|
221
|
+
|
172
222
|
class StableDiffusionInpaintPipeline(
|
173
|
-
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
|
223
|
+
DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin, FromSingleFileMixin
|
174
224
|
):
|
175
225
|
r"""
|
176
226
|
Pipeline for text-guided image inpainting using Stable Diffusion.
|
@@ -182,6 +232,8 @@ class StableDiffusionInpaintPipeline(
|
|
182
232
|
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
183
233
|
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
184
234
|
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
235
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
236
|
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
185
237
|
|
186
238
|
Args:
|
187
239
|
vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]):
|
@@ -202,8 +254,9 @@ class StableDiffusionInpaintPipeline(
|
|
202
254
|
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
203
255
|
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
204
256
|
"""
|
205
|
-
|
206
|
-
|
257
|
+
|
258
|
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
259
|
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
207
260
|
_exclude_from_cpu_offload = ["safety_checker"]
|
208
261
|
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "mask", "masked_image_latents"]
|
209
262
|
|
@@ -216,6 +269,7 @@ class StableDiffusionInpaintPipeline(
|
|
216
269
|
scheduler: KarrasDiffusionSchedulers,
|
217
270
|
safety_checker: StableDiffusionSafetyChecker,
|
218
271
|
feature_extractor: CLIPImageProcessor,
|
272
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
219
273
|
requires_safety_checker: bool = True,
|
220
274
|
):
|
221
275
|
super().__init__()
|
@@ -297,6 +351,7 @@ class StableDiffusionInpaintPipeline(
|
|
297
351
|
scheduler=scheduler,
|
298
352
|
safety_checker=safety_checker,
|
299
353
|
feature_extractor=feature_extractor,
|
354
|
+
image_encoder=image_encoder,
|
300
355
|
)
|
301
356
|
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
302
357
|
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
@@ -520,6 +575,31 @@ class StableDiffusionInpaintPipeline(
|
|
520
575
|
|
521
576
|
return prompt_embeds, negative_prompt_embeds
|
522
577
|
|
578
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
579
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
580
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
581
|
+
|
582
|
+
if not isinstance(image, torch.Tensor):
|
583
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
584
|
+
|
585
|
+
image = image.to(device=device, dtype=dtype)
|
586
|
+
if output_hidden_states:
|
587
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
588
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
589
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
590
|
+
torch.zeros_like(image), output_hidden_states=True
|
591
|
+
).hidden_states[-2]
|
592
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
593
|
+
num_images_per_prompt, dim=0
|
594
|
+
)
|
595
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
596
|
+
else:
|
597
|
+
image_embeds = self.image_encoder(image).image_embeds
|
598
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
599
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
600
|
+
|
601
|
+
return image_embeds, uncond_image_embeds
|
602
|
+
|
523
603
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
524
604
|
def run_safety_checker(self, image, device, dtype):
|
525
605
|
if self.safety_checker is None:
|
@@ -556,6 +636,8 @@ class StableDiffusionInpaintPipeline(
|
|
556
636
|
def check_inputs(
|
557
637
|
self,
|
558
638
|
prompt,
|
639
|
+
image,
|
640
|
+
mask_image,
|
559
641
|
height,
|
560
642
|
width,
|
561
643
|
strength,
|
@@ -564,6 +646,7 @@ class StableDiffusionInpaintPipeline(
|
|
564
646
|
prompt_embeds=None,
|
565
647
|
negative_prompt_embeds=None,
|
566
648
|
callback_on_step_end_tensor_inputs=None,
|
649
|
+
padding_mask_crop=None,
|
567
650
|
):
|
568
651
|
if strength < 0 or strength > 1:
|
569
652
|
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
@@ -609,6 +692,21 @@ class StableDiffusionInpaintPipeline(
|
|
609
692
|
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
610
693
|
f" {negative_prompt_embeds.shape}."
|
611
694
|
)
|
695
|
+
if padding_mask_crop is not None:
|
696
|
+
if self.unet.config.in_channels != 4:
|
697
|
+
raise ValueError(
|
698
|
+
f"The UNet should have 4 input channels for inpainting mask crop, but has"
|
699
|
+
f" {self.unet.config.in_channels} input channels."
|
700
|
+
)
|
701
|
+
if not isinstance(image, PIL.Image.Image):
|
702
|
+
raise ValueError(
|
703
|
+
f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}."
|
704
|
+
)
|
705
|
+
if not isinstance(mask_image, PIL.Image.Image):
|
706
|
+
raise ValueError(
|
707
|
+
f"The mask image should be a PIL image when inpainting mask crop, but is of type"
|
708
|
+
f" {type(mask_image)}."
|
709
|
+
)
|
612
710
|
|
613
711
|
def prepare_latents(
|
614
712
|
self,
|
@@ -765,6 +863,67 @@ class StableDiffusionInpaintPipeline(
|
|
765
863
|
"""Disables the FreeU mechanism if enabled."""
|
766
864
|
self.unet.disable_freeu()
|
767
865
|
|
866
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.fuse_qkv_projections
|
867
|
+
def fuse_qkv_projections(self, unet: bool = True, vae: bool = True):
|
868
|
+
"""
|
869
|
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
|
870
|
+
key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
|
871
|
+
|
872
|
+
<Tip warning={true}>
|
873
|
+
|
874
|
+
This API is 🧪 experimental.
|
875
|
+
|
876
|
+
</Tip>
|
877
|
+
|
878
|
+
Args:
|
879
|
+
unet (`bool`, defaults to `True`): To apply fusion on the UNet.
|
880
|
+
vae (`bool`, defaults to `True`): To apply fusion on the VAE.
|
881
|
+
"""
|
882
|
+
self.fusing_unet = False
|
883
|
+
self.fusing_vae = False
|
884
|
+
|
885
|
+
if unet:
|
886
|
+
self.fusing_unet = True
|
887
|
+
self.unet.fuse_qkv_projections()
|
888
|
+
self.unet.set_attn_processor(FusedAttnProcessor2_0())
|
889
|
+
|
890
|
+
if vae:
|
891
|
+
if not isinstance(self.vae, AutoencoderKL):
|
892
|
+
raise ValueError("`fuse_qkv_projections()` is only supported for the VAE of type `AutoencoderKL`.")
|
893
|
+
|
894
|
+
self.fusing_vae = True
|
895
|
+
self.vae.fuse_qkv_projections()
|
896
|
+
self.vae.set_attn_processor(FusedAttnProcessor2_0())
|
897
|
+
|
898
|
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.unfuse_qkv_projections
|
899
|
+
def unfuse_qkv_projections(self, unet: bool = True, vae: bool = True):
|
900
|
+
"""Disable QKV projection fusion if enabled.
|
901
|
+
|
902
|
+
<Tip warning={true}>
|
903
|
+
|
904
|
+
This API is 🧪 experimental.
|
905
|
+
|
906
|
+
</Tip>
|
907
|
+
|
908
|
+
Args:
|
909
|
+
unet (`bool`, defaults to `True`): To apply fusion on the UNet.
|
910
|
+
vae (`bool`, defaults to `True`): To apply fusion on the VAE.
|
911
|
+
|
912
|
+
"""
|
913
|
+
if unet:
|
914
|
+
if not self.fusing_unet:
|
915
|
+
logger.warning("The UNet was not initially fused for QKV projections. Doing nothing.")
|
916
|
+
else:
|
917
|
+
self.unet.unfuse_qkv_projections()
|
918
|
+
self.fusing_unet = False
|
919
|
+
|
920
|
+
if vae:
|
921
|
+
if not self.fusing_vae:
|
922
|
+
logger.warning("The VAE was not initially fused for QKV projections. Doing nothing.")
|
923
|
+
else:
|
924
|
+
self.vae.unfuse_qkv_projections()
|
925
|
+
self.fusing_vae = False
|
926
|
+
|
768
927
|
# Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
|
769
928
|
def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
|
770
929
|
"""
|
@@ -817,6 +976,10 @@ class StableDiffusionInpaintPipeline(
|
|
817
976
|
def num_timesteps(self):
|
818
977
|
return self._num_timesteps
|
819
978
|
|
979
|
+
@property
|
980
|
+
def interrupt(self):
|
981
|
+
return self._interrupt
|
982
|
+
|
820
983
|
@torch.no_grad()
|
821
984
|
def __call__(
|
822
985
|
self,
|
@@ -826,8 +989,10 @@ class StableDiffusionInpaintPipeline(
|
|
826
989
|
masked_image_latents: torch.FloatTensor = None,
|
827
990
|
height: Optional[int] = None,
|
828
991
|
width: Optional[int] = None,
|
992
|
+
padding_mask_crop: Optional[int] = None,
|
829
993
|
strength: float = 1.0,
|
830
994
|
num_inference_steps: int = 50,
|
995
|
+
timesteps: List[int] = None,
|
831
996
|
guidance_scale: float = 7.5,
|
832
997
|
negative_prompt: Optional[Union[str, List[str]]] = None,
|
833
998
|
num_images_per_prompt: Optional[int] = 1,
|
@@ -836,6 +1001,7 @@ class StableDiffusionInpaintPipeline(
|
|
836
1001
|
latents: Optional[torch.FloatTensor] = None,
|
837
1002
|
prompt_embeds: Optional[torch.FloatTensor] = None,
|
838
1003
|
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
1004
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
839
1005
|
output_type: Optional[str] = "pil",
|
840
1006
|
return_dict: bool = True,
|
841
1007
|
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
@@ -868,6 +1034,12 @@ class StableDiffusionInpaintPipeline(
|
|
868
1034
|
The height in pixels of the generated image.
|
869
1035
|
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
870
1036
|
The width in pixels of the generated image.
|
1037
|
+
padding_mask_crop (`int`, *optional*, defaults to `None`):
|
1038
|
+
The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to image and mask_image. If
|
1039
|
+
`padding_mask_crop` is not `None`, it will first find a rectangular region with the same aspect ration of the image and
|
1040
|
+
contains all masked area, and then expand that area based on `padding_mask_crop`. The image and mask_image will then be cropped based on
|
1041
|
+
the expanded area before resizing to the original image size for inpainting. This is useful when the masked area is small while the image is large
|
1042
|
+
and contain information inreleant for inpainging, such as background.
|
871
1043
|
strength (`float`, *optional*, defaults to 1.0):
|
872
1044
|
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
873
1045
|
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
@@ -877,6 +1049,10 @@ class StableDiffusionInpaintPipeline(
|
|
877
1049
|
num_inference_steps (`int`, *optional*, defaults to 50):
|
878
1050
|
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
879
1051
|
expense of slower inference. This parameter is modulated by `strength`.
|
1052
|
+
timesteps (`List[int]`, *optional*):
|
1053
|
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
1054
|
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
1055
|
+
passed will be used. Must be in descending order.
|
880
1056
|
guidance_scale (`float`, *optional*, defaults to 7.5):
|
881
1057
|
A higher guidance scale value encourages the model to generate images closely linked to the text
|
882
1058
|
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
@@ -901,6 +1077,7 @@ class StableDiffusionInpaintPipeline(
|
|
901
1077
|
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
902
1078
|
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
903
1079
|
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
1080
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
904
1081
|
output_type (`str`, *optional*, defaults to `"pil"`):
|
905
1082
|
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
906
1083
|
return_dict (`bool`, *optional*, defaults to `True`):
|
@@ -920,7 +1097,7 @@ class StableDiffusionInpaintPipeline(
|
|
920
1097
|
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
921
1098
|
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
922
1099
|
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
923
|
-
`._callback_tensor_inputs` attribute of your
|
1100
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
924
1101
|
Examples:
|
925
1102
|
|
926
1103
|
```py
|
@@ -983,6 +1160,8 @@ class StableDiffusionInpaintPipeline(
|
|
983
1160
|
# 1. Check inputs
|
984
1161
|
self.check_inputs(
|
985
1162
|
prompt,
|
1163
|
+
image,
|
1164
|
+
mask_image,
|
986
1165
|
height,
|
987
1166
|
width,
|
988
1167
|
strength,
|
@@ -991,11 +1170,13 @@ class StableDiffusionInpaintPipeline(
|
|
991
1170
|
prompt_embeds,
|
992
1171
|
negative_prompt_embeds,
|
993
1172
|
callback_on_step_end_tensor_inputs,
|
1173
|
+
padding_mask_crop,
|
994
1174
|
)
|
995
1175
|
|
996
1176
|
self._guidance_scale = guidance_scale
|
997
1177
|
self._clip_skip = clip_skip
|
998
1178
|
self._cross_attention_kwargs = cross_attention_kwargs
|
1179
|
+
self._interrupt = False
|
999
1180
|
|
1000
1181
|
# 2. Define call parameters
|
1001
1182
|
if prompt is not None and isinstance(prompt, str):
|
@@ -1028,8 +1209,16 @@ class StableDiffusionInpaintPipeline(
|
|
1028
1209
|
if self.do_classifier_free_guidance:
|
1029
1210
|
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
1030
1211
|
|
1212
|
+
if ip_adapter_image is not None:
|
1213
|
+
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
1214
|
+
image_embeds, negative_image_embeds = self.encode_image(
|
1215
|
+
ip_adapter_image, device, num_images_per_prompt, output_hidden_state
|
1216
|
+
)
|
1217
|
+
if self.do_classifier_free_guidance:
|
1218
|
+
image_embeds = torch.cat([negative_image_embeds, image_embeds])
|
1219
|
+
|
1031
1220
|
# 4. set timesteps
|
1032
|
-
self.scheduler
|
1221
|
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
1033
1222
|
timesteps, num_inference_steps = self.get_timesteps(
|
1034
1223
|
num_inference_steps=num_inference_steps, strength=strength, device=device
|
1035
1224
|
)
|
@@ -1046,7 +1235,17 @@ class StableDiffusionInpaintPipeline(
|
|
1046
1235
|
|
1047
1236
|
# 5. Preprocess mask and image
|
1048
1237
|
|
1049
|
-
|
1238
|
+
if padding_mask_crop is not None:
|
1239
|
+
crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
|
1240
|
+
resize_mode = "fill"
|
1241
|
+
else:
|
1242
|
+
crops_coords = None
|
1243
|
+
resize_mode = "default"
|
1244
|
+
|
1245
|
+
original_image = image
|
1246
|
+
init_image = self.image_processor.preprocess(
|
1247
|
+
image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
|
1248
|
+
)
|
1050
1249
|
init_image = init_image.to(dtype=torch.float32)
|
1051
1250
|
|
1052
1251
|
# 6. Prepare latent variables
|
@@ -1076,7 +1275,9 @@ class StableDiffusionInpaintPipeline(
|
|
1076
1275
|
latents, noise = latents_outputs
|
1077
1276
|
|
1078
1277
|
# 7. Prepare mask latent variables
|
1079
|
-
mask_condition = self.mask_processor.preprocess(
|
1278
|
+
mask_condition = self.mask_processor.preprocess(
|
1279
|
+
mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
|
1280
|
+
)
|
1080
1281
|
|
1081
1282
|
if masked_image_latents is None:
|
1082
1283
|
masked_image = init_image * (mask_condition < 0.5)
|
@@ -1116,7 +1317,10 @@ class StableDiffusionInpaintPipeline(
|
|
1116
1317
|
# 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
1117
1318
|
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1118
1319
|
|
1119
|
-
# 9.
|
1320
|
+
# 9.1 Add image embeds for IP-Adapter
|
1321
|
+
added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
|
1322
|
+
|
1323
|
+
# 9.2 Optionally get Guidance Scale Embedding
|
1120
1324
|
timestep_cond = None
|
1121
1325
|
if self.unet.config.time_cond_proj_dim is not None:
|
1122
1326
|
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
@@ -1129,6 +1333,9 @@ class StableDiffusionInpaintPipeline(
|
|
1129
1333
|
self._num_timesteps = len(timesteps)
|
1130
1334
|
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1131
1335
|
for i, t in enumerate(timesteps):
|
1336
|
+
if self.interrupt:
|
1337
|
+
continue
|
1338
|
+
|
1132
1339
|
# expand the latents if we are doing classifier free guidance
|
1133
1340
|
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
1134
1341
|
|
@@ -1145,6 +1352,7 @@ class StableDiffusionInpaintPipeline(
|
|
1145
1352
|
encoder_hidden_states=prompt_embeds,
|
1146
1353
|
timestep_cond=timestep_cond,
|
1147
1354
|
cross_attention_kwargs=self.cross_attention_kwargs,
|
1355
|
+
added_cond_kwargs=added_cond_kwargs,
|
1148
1356
|
return_dict=False,
|
1149
1357
|
)[0]
|
1150
1358
|
|
@@ -1212,6 +1420,9 @@ class StableDiffusionInpaintPipeline(
|
|
1212
1420
|
|
1213
1421
|
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
1214
1422
|
|
1423
|
+
if padding_mask_crop is not None:
|
1424
|
+
image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
|
1425
|
+
|
1215
1426
|
# Offload all models
|
1216
1427
|
self.maybe_free_model_hooks()
|
1217
1428
|
|
@@ -18,11 +18,11 @@ from typing import Callable, Dict, List, Optional, Union
|
|
18
18
|
import numpy as np
|
19
19
|
import PIL.Image
|
20
20
|
import torch
|
21
|
-
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
21
|
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
22
22
|
|
23
23
|
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
24
|
-
from ...loaders import LoraLoaderMixin, TextualInversionLoaderMixin
|
25
|
-
from ...models import AutoencoderKL, UNet2DConditionModel
|
24
|
+
from ...loaders import IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
25
|
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
26
26
|
from ...schedulers import KarrasDiffusionSchedulers
|
27
27
|
from ...utils import PIL_INTERPOLATION, deprecate, logging
|
28
28
|
from ...utils.torch_utils import randn_tensor
|
@@ -58,7 +58,23 @@ def preprocess(image):
|
|
58
58
|
return image
|
59
59
|
|
60
60
|
|
61
|
-
|
61
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
62
|
+
def retrieve_latents(
|
63
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
64
|
+
):
|
65
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
66
|
+
return encoder_output.latent_dist.sample(generator)
|
67
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
68
|
+
return encoder_output.latent_dist.mode()
|
69
|
+
elif hasattr(encoder_output, "latents"):
|
70
|
+
return encoder_output.latents
|
71
|
+
else:
|
72
|
+
raise AttributeError("Could not access latents of provided encoder_output")
|
73
|
+
|
74
|
+
|
75
|
+
class StableDiffusionInstructPix2PixPipeline(
|
76
|
+
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, IPAdapterMixin
|
77
|
+
):
|
62
78
|
r"""
|
63
79
|
Pipeline for pixel-level image editing by following text instructions (based on Stable Diffusion).
|
64
80
|
|
@@ -69,6 +85,7 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
69
85
|
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
70
86
|
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
71
87
|
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
88
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
72
89
|
|
73
90
|
Args:
|
74
91
|
vae ([`AutoencoderKL`]):
|
@@ -89,8 +106,9 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
89
106
|
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
90
107
|
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
91
108
|
"""
|
109
|
+
|
92
110
|
model_cpu_offload_seq = "text_encoder->unet->vae"
|
93
|
-
_optional_components = ["safety_checker", "feature_extractor"]
|
111
|
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
94
112
|
_exclude_from_cpu_offload = ["safety_checker"]
|
95
113
|
_callback_tensor_inputs = ["latents", "prompt_embeds", "image_latents"]
|
96
114
|
|
@@ -103,6 +121,7 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
103
121
|
scheduler: KarrasDiffusionSchedulers,
|
104
122
|
safety_checker: StableDiffusionSafetyChecker,
|
105
123
|
feature_extractor: CLIPImageProcessor,
|
124
|
+
image_encoder: Optional[CLIPVisionModelWithProjection] = None,
|
106
125
|
requires_safety_checker: bool = True,
|
107
126
|
):
|
108
127
|
super().__init__()
|
@@ -131,6 +150,7 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
131
150
|
scheduler=scheduler,
|
132
151
|
safety_checker=safety_checker,
|
133
152
|
feature_extractor=feature_extractor,
|
153
|
+
image_encoder=image_encoder,
|
134
154
|
)
|
135
155
|
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
136
156
|
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
@@ -151,6 +171,7 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
151
171
|
latents: Optional[torch.FloatTensor] = None,
|
152
172
|
prompt_embeds: Optional[torch.FloatTensor] = None,
|
153
173
|
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
174
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
154
175
|
output_type: Optional[str] = "pil",
|
155
176
|
return_dict: bool = True,
|
156
177
|
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
@@ -198,6 +219,8 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
198
219
|
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
199
220
|
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
200
221
|
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
222
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*):
|
223
|
+
Optional image input to work with IP Adapters.
|
201
224
|
output_type (`str`, *optional*, defaults to `"pil"`):
|
202
225
|
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
203
226
|
return_dict (`bool`, *optional*, defaults to `True`):
|
@@ -211,7 +234,7 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
211
234
|
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
212
235
|
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
213
236
|
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
214
|
-
`._callback_tensor_inputs` attribute of your
|
237
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
215
238
|
|
216
239
|
Examples:
|
217
240
|
|
@@ -278,6 +301,16 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
278
301
|
self._guidance_scale = guidance_scale
|
279
302
|
self._image_guidance_scale = image_guidance_scale
|
280
303
|
|
304
|
+
device = self._execution_device
|
305
|
+
|
306
|
+
if ip_adapter_image is not None:
|
307
|
+
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
308
|
+
image_embeds, negative_image_embeds = self.encode_image(
|
309
|
+
ip_adapter_image, device, num_images_per_prompt, output_hidden_state
|
310
|
+
)
|
311
|
+
if self.do_classifier_free_guidance:
|
312
|
+
image_embeds = torch.cat([image_embeds, negative_image_embeds, negative_image_embeds])
|
313
|
+
|
281
314
|
if image is None:
|
282
315
|
raise ValueError("`image` input cannot be undefined.")
|
283
316
|
|
@@ -319,7 +352,6 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
319
352
|
prompt_embeds.dtype,
|
320
353
|
device,
|
321
354
|
self.do_classifier_free_guidance,
|
322
|
-
generator,
|
323
355
|
)
|
324
356
|
|
325
357
|
height, width = image_latents.shape[-2:]
|
@@ -353,6 +385,9 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
353
385
|
# 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
354
386
|
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
355
387
|
|
388
|
+
# 8.1 Add image embeds for IP-Adapter
|
389
|
+
added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
|
390
|
+
|
356
391
|
# 9. Denoising loop
|
357
392
|
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
358
393
|
self._num_timesteps = len(timesteps)
|
@@ -369,7 +404,11 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
369
404
|
|
370
405
|
# predict the noise residual
|
371
406
|
noise_pred = self.unet(
|
372
|
-
scaled_latent_model_input,
|
407
|
+
scaled_latent_model_input,
|
408
|
+
t,
|
409
|
+
encoder_hidden_states=prompt_embeds,
|
410
|
+
added_cond_kwargs=added_cond_kwargs,
|
411
|
+
return_dict=False,
|
373
412
|
)[0]
|
374
413
|
|
375
414
|
# Hack:
|
@@ -584,11 +623,36 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
584
623
|
# For classifier free guidance, we need to do two forward passes.
|
585
624
|
# Here we concatenate the unconditional and text embeddings into a single batch
|
586
625
|
# to avoid doing two forward passes
|
587
|
-
# pix2pix has two
|
626
|
+
# pix2pix has two negative embeddings, and unlike in other pipelines latents are ordered [prompt_embeds, negative_prompt_embeds, negative_prompt_embeds]
|
588
627
|
prompt_embeds = torch.cat([prompt_embeds, negative_prompt_embeds, negative_prompt_embeds])
|
589
628
|
|
590
629
|
return prompt_embeds
|
591
630
|
|
631
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
632
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
633
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
634
|
+
|
635
|
+
if not isinstance(image, torch.Tensor):
|
636
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
637
|
+
|
638
|
+
image = image.to(device=device, dtype=dtype)
|
639
|
+
if output_hidden_states:
|
640
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
641
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
642
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
643
|
+
torch.zeros_like(image), output_hidden_states=True
|
644
|
+
).hidden_states[-2]
|
645
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
646
|
+
num_images_per_prompt, dim=0
|
647
|
+
)
|
648
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
649
|
+
else:
|
650
|
+
image_embeds = self.image_encoder(image).image_embeds
|
651
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
652
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
653
|
+
|
654
|
+
return image_embeds, uncond_image_embeds
|
655
|
+
|
592
656
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
593
657
|
def run_safety_checker(self, image, device, dtype):
|
594
658
|
if self.safety_checker is None:
|
@@ -715,17 +779,7 @@ class StableDiffusionInstructPix2PixPipeline(DiffusionPipeline, TextualInversion
|
|
715
779
|
if image.shape[1] == 4:
|
716
780
|
image_latents = image
|
717
781
|
else:
|
718
|
-
|
719
|
-
raise ValueError(
|
720
|
-
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
721
|
-
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
722
|
-
)
|
723
|
-
|
724
|
-
if isinstance(generator, list):
|
725
|
-
image_latents = [self.vae.encode(image[i : i + 1]).latent_dist.mode() for i in range(batch_size)]
|
726
|
-
image_latents = torch.cat(image_latents, dim=0)
|
727
|
-
else:
|
728
|
-
image_latents = self.vae.encode(image).latent_dist.mode()
|
782
|
+
image_latents = retrieve_latents(self.vae.encode(image), sample_mode="argmax")
|
729
783
|
|
730
784
|
if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
|
731
785
|
# expand image_latents for batch_size
|
@@ -67,6 +67,9 @@ class StableDiffusionLatentUpscalePipeline(DiffusionPipeline, FromSingleFileMixi
|
|
67
67
|
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
68
68
|
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
69
69
|
|
70
|
+
The pipeline also inherits the following loading methods:
|
71
|
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
72
|
+
|
70
73
|
Args:
|
71
74
|
vae ([`AutoencoderKL`]):
|
72
75
|
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
@@ -79,6 +82,7 @@ class StableDiffusionLatentUpscalePipeline(DiffusionPipeline, FromSingleFileMixi
|
|
79
82
|
scheduler ([`SchedulerMixin`]):
|
80
83
|
A [`EulerDiscreteScheduler`] to be used in combination with `unet` to denoise the encoded image latents.
|
81
84
|
"""
|
85
|
+
|
82
86
|
model_cpu_offload_seq = "text_encoder->unet->vae"
|
83
87
|
|
84
88
|
def __init__(
|