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
@@ -20,11 +20,11 @@ from typing import Any, Callable, Dict, List, Optional, Union
|
|
20
20
|
|
21
21
|
import PIL.Image
|
22
22
|
import torch
|
23
|
-
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
23
|
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
24
24
|
|
25
25
|
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
26
|
-
from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
27
|
-
from ...models import AutoencoderKL, UNet2DConditionModel
|
26
|
+
from ...loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
27
|
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
28
28
|
from ...models.lora import adjust_lora_scale_text_encoder
|
29
29
|
from ...schedulers import LCMScheduler
|
30
30
|
from ...utils import (
|
@@ -44,15 +44,64 @@ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
|
44
44
|
|
45
45
|
|
46
46
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
47
|
-
def retrieve_latents(
|
48
|
-
|
47
|
+
def retrieve_latents(
|
48
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
49
|
+
):
|
50
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
49
51
|
return encoder_output.latent_dist.sample(generator)
|
52
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
53
|
+
return encoder_output.latent_dist.mode()
|
50
54
|
elif hasattr(encoder_output, "latents"):
|
51
55
|
return encoder_output.latents
|
52
56
|
else:
|
53
57
|
raise AttributeError("Could not access latents of provided encoder_output")
|
54
58
|
|
55
59
|
|
60
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
61
|
+
def retrieve_timesteps(
|
62
|
+
scheduler,
|
63
|
+
num_inference_steps: Optional[int] = None,
|
64
|
+
device: Optional[Union[str, torch.device]] = None,
|
65
|
+
timesteps: Optional[List[int]] = None,
|
66
|
+
**kwargs,
|
67
|
+
):
|
68
|
+
"""
|
69
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
70
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
71
|
+
|
72
|
+
Args:
|
73
|
+
scheduler (`SchedulerMixin`):
|
74
|
+
The scheduler to get timesteps from.
|
75
|
+
num_inference_steps (`int`):
|
76
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
77
|
+
`timesteps` must be `None`.
|
78
|
+
device (`str` or `torch.device`, *optional*):
|
79
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
80
|
+
timesteps (`List[int]`, *optional*):
|
81
|
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
82
|
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
83
|
+
must be `None`.
|
84
|
+
|
85
|
+
Returns:
|
86
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
87
|
+
second element is the number of inference steps.
|
88
|
+
"""
|
89
|
+
if timesteps is not None:
|
90
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
91
|
+
if not accepts_timesteps:
|
92
|
+
raise ValueError(
|
93
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
94
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
95
|
+
)
|
96
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
97
|
+
timesteps = scheduler.timesteps
|
98
|
+
num_inference_steps = len(timesteps)
|
99
|
+
else:
|
100
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
101
|
+
timesteps = scheduler.timesteps
|
102
|
+
return timesteps, num_inference_steps
|
103
|
+
|
104
|
+
|
56
105
|
EXAMPLE_DOC_STRING = """
|
57
106
|
Examples:
|
58
107
|
```py
|
@@ -80,7 +129,7 @@ EXAMPLE_DOC_STRING = """
|
|
80
129
|
|
81
130
|
|
82
131
|
class LatentConsistencyModelImg2ImgPipeline(
|
83
|
-
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
|
132
|
+
DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin, FromSingleFileMixin
|
84
133
|
):
|
85
134
|
r"""
|
86
135
|
Pipeline for image-to-image generation using a latent consistency model.
|
@@ -93,6 +142,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
93
142
|
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
94
143
|
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
95
144
|
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
145
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
96
146
|
|
97
147
|
Args:
|
98
148
|
vae ([`AutoencoderKL`]):
|
@@ -115,8 +165,9 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
115
165
|
requires_safety_checker (`bool`, *optional*, defaults to `True`):
|
116
166
|
Whether the pipeline requires a safety checker component.
|
117
167
|
"""
|
168
|
+
|
118
169
|
model_cpu_offload_seq = "text_encoder->unet->vae"
|
119
|
-
_optional_components = ["safety_checker", "feature_extractor"]
|
170
|
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
120
171
|
_exclude_from_cpu_offload = ["safety_checker"]
|
121
172
|
_callback_tensor_inputs = ["latents", "denoised", "prompt_embeds", "w_embedding"]
|
122
173
|
|
@@ -129,6 +180,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
129
180
|
scheduler: LCMScheduler,
|
130
181
|
safety_checker: StableDiffusionSafetyChecker,
|
131
182
|
feature_extractor: CLIPImageProcessor,
|
183
|
+
image_encoder: Optional[CLIPVisionModelWithProjection] = None,
|
132
184
|
requires_safety_checker: bool = True,
|
133
185
|
):
|
134
186
|
super().__init__()
|
@@ -141,6 +193,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
141
193
|
scheduler=scheduler,
|
142
194
|
safety_checker=safety_checker,
|
143
195
|
feature_extractor=feature_extractor,
|
196
|
+
image_encoder=image_encoder,
|
144
197
|
)
|
145
198
|
|
146
199
|
if safety_checker is None and requires_safety_checker:
|
@@ -399,6 +452,31 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
399
452
|
|
400
453
|
return prompt_embeds, negative_prompt_embeds
|
401
454
|
|
455
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
456
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
457
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
458
|
+
|
459
|
+
if not isinstance(image, torch.Tensor):
|
460
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
461
|
+
|
462
|
+
image = image.to(device=device, dtype=dtype)
|
463
|
+
if output_hidden_states:
|
464
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
465
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
466
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
467
|
+
torch.zeros_like(image), output_hidden_states=True
|
468
|
+
).hidden_states[-2]
|
469
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
470
|
+
num_images_per_prompt, dim=0
|
471
|
+
)
|
472
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
473
|
+
else:
|
474
|
+
image_embeds = self.image_encoder(image).image_embeds
|
475
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
476
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
477
|
+
|
478
|
+
return image_embeds, uncond_image_embeds
|
479
|
+
|
402
480
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
403
481
|
def run_safety_checker(self, image, device, dtype):
|
404
482
|
if self.safety_checker is None:
|
@@ -591,11 +669,13 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
591
669
|
num_inference_steps: int = 4,
|
592
670
|
strength: float = 0.8,
|
593
671
|
original_inference_steps: int = None,
|
672
|
+
timesteps: List[int] = None,
|
594
673
|
guidance_scale: float = 8.5,
|
595
674
|
num_images_per_prompt: Optional[int] = 1,
|
596
675
|
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
597
676
|
latents: Optional[torch.FloatTensor] = None,
|
598
677
|
prompt_embeds: Optional[torch.FloatTensor] = None,
|
678
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
599
679
|
output_type: Optional[str] = "pil",
|
600
680
|
return_dict: bool = True,
|
601
681
|
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
@@ -622,6 +702,10 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
622
702
|
we will draw `num_inference_steps` evenly spaced timesteps from as our final timestep schedule,
|
623
703
|
following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the
|
624
704
|
scheduler's `original_inference_steps` attribute.
|
705
|
+
timesteps (`List[int]`, *optional*):
|
706
|
+
Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
|
707
|
+
timesteps on the original LCM training/distillation timestep schedule are used. Must be in descending
|
708
|
+
order.
|
625
709
|
guidance_scale (`float`, *optional*, defaults to 7.5):
|
626
710
|
A higher guidance scale value encourages the model to generate images closely linked to the text
|
627
711
|
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
@@ -640,6 +724,8 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
640
724
|
prompt_embeds (`torch.FloatTensor`, *optional*):
|
641
725
|
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
642
726
|
provided, text embeddings are generated from the `prompt` input argument.
|
727
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*):
|
728
|
+
Optional image input to work with IP Adapters.
|
643
729
|
output_type (`str`, *optional*, defaults to `"pil"`):
|
644
730
|
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
645
731
|
return_dict (`bool`, *optional*, defaults to `True`):
|
@@ -659,7 +745,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
659
745
|
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
660
746
|
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
661
747
|
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
662
|
-
`._callback_tensor_inputs` attribute of your
|
748
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
663
749
|
|
664
750
|
Examples:
|
665
751
|
|
@@ -703,6 +789,12 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
703
789
|
device = self._execution_device
|
704
790
|
# do_classifier_free_guidance = guidance_scale > 1.0
|
705
791
|
|
792
|
+
if ip_adapter_image is not None:
|
793
|
+
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
794
|
+
image_embeds, negative_image_embeds = self.encode_image(
|
795
|
+
ip_adapter_image, device, num_images_per_prompt, output_hidden_state
|
796
|
+
)
|
797
|
+
|
706
798
|
# 3. Encode input prompt
|
707
799
|
lora_scale = (
|
708
800
|
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
@@ -727,10 +819,14 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
727
819
|
image = self.image_processor.preprocess(image)
|
728
820
|
|
729
821
|
# 5. Prepare timesteps
|
730
|
-
|
731
|
-
|
822
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
823
|
+
self.scheduler,
|
824
|
+
num_inference_steps,
|
825
|
+
device,
|
826
|
+
timesteps,
|
827
|
+
original_inference_steps=original_inference_steps,
|
828
|
+
strength=strength,
|
732
829
|
)
|
733
|
-
timesteps = self.scheduler.timesteps
|
734
830
|
|
735
831
|
# 6. Prepare latent variables
|
736
832
|
original_inference_steps = (
|
@@ -756,6 +852,9 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
756
852
|
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
757
853
|
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, None)
|
758
854
|
|
855
|
+
# 7.1 Add image embeds for IP-Adapter
|
856
|
+
added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
|
857
|
+
|
759
858
|
# 8. LCM Multistep Sampling Loop
|
760
859
|
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
761
860
|
self._num_timesteps = len(timesteps)
|
@@ -770,6 +869,7 @@ class LatentConsistencyModelImg2ImgPipeline(
|
|
770
869
|
timestep_cond=w_embedding,
|
771
870
|
encoder_hidden_states=prompt_embeds,
|
772
871
|
cross_attention_kwargs=self.cross_attention_kwargs,
|
872
|
+
added_cond_kwargs=added_cond_kwargs,
|
773
873
|
return_dict=False,
|
774
874
|
)[0]
|
775
875
|
|
@@ -19,11 +19,11 @@ import inspect
|
|
19
19
|
from typing import Any, Callable, Dict, List, Optional, Union
|
20
20
|
|
21
21
|
import torch
|
22
|
-
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
22
|
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
23
23
|
|
24
|
-
from ...image_processor import VaeImageProcessor
|
25
|
-
from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
26
|
-
from ...models import AutoencoderKL, UNet2DConditionModel
|
24
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
25
|
+
from ...loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
26
|
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
27
27
|
from ...models.lora import adjust_lora_scale_text_encoder
|
28
28
|
from ...schedulers import LCMScheduler
|
29
29
|
from ...utils import (
|
@@ -61,8 +61,53 @@ EXAMPLE_DOC_STRING = """
|
|
61
61
|
"""
|
62
62
|
|
63
63
|
|
64
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
65
|
+
def retrieve_timesteps(
|
66
|
+
scheduler,
|
67
|
+
num_inference_steps: Optional[int] = None,
|
68
|
+
device: Optional[Union[str, torch.device]] = None,
|
69
|
+
timesteps: Optional[List[int]] = None,
|
70
|
+
**kwargs,
|
71
|
+
):
|
72
|
+
"""
|
73
|
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
74
|
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
75
|
+
|
76
|
+
Args:
|
77
|
+
scheduler (`SchedulerMixin`):
|
78
|
+
The scheduler to get timesteps from.
|
79
|
+
num_inference_steps (`int`):
|
80
|
+
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
81
|
+
`timesteps` must be `None`.
|
82
|
+
device (`str` or `torch.device`, *optional*):
|
83
|
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
84
|
+
timesteps (`List[int]`, *optional*):
|
85
|
+
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
86
|
+
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
87
|
+
must be `None`.
|
88
|
+
|
89
|
+
Returns:
|
90
|
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
91
|
+
second element is the number of inference steps.
|
92
|
+
"""
|
93
|
+
if timesteps is not None:
|
94
|
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
95
|
+
if not accepts_timesteps:
|
96
|
+
raise ValueError(
|
97
|
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
98
|
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
99
|
+
)
|
100
|
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
101
|
+
timesteps = scheduler.timesteps
|
102
|
+
num_inference_steps = len(timesteps)
|
103
|
+
else:
|
104
|
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
105
|
+
timesteps = scheduler.timesteps
|
106
|
+
return timesteps, num_inference_steps
|
107
|
+
|
108
|
+
|
64
109
|
class LatentConsistencyModelPipeline(
|
65
|
-
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
|
110
|
+
DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin, FromSingleFileMixin
|
66
111
|
):
|
67
112
|
r"""
|
68
113
|
Pipeline for text-to-image generation using a latent consistency model.
|
@@ -75,6 +120,7 @@ class LatentConsistencyModelPipeline(
|
|
75
120
|
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
76
121
|
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
77
122
|
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
123
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
78
124
|
|
79
125
|
Args:
|
80
126
|
vae ([`AutoencoderKL`]):
|
@@ -97,8 +143,9 @@ class LatentConsistencyModelPipeline(
|
|
97
143
|
requires_safety_checker (`bool`, *optional*, defaults to `True`):
|
98
144
|
Whether the pipeline requires a safety checker component.
|
99
145
|
"""
|
146
|
+
|
100
147
|
model_cpu_offload_seq = "text_encoder->unet->vae"
|
101
|
-
_optional_components = ["safety_checker", "feature_extractor"]
|
148
|
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
102
149
|
_exclude_from_cpu_offload = ["safety_checker"]
|
103
150
|
_callback_tensor_inputs = ["latents", "denoised", "prompt_embeds", "w_embedding"]
|
104
151
|
|
@@ -111,6 +158,7 @@ class LatentConsistencyModelPipeline(
|
|
111
158
|
scheduler: LCMScheduler,
|
112
159
|
safety_checker: StableDiffusionSafetyChecker,
|
113
160
|
feature_extractor: CLIPImageProcessor,
|
161
|
+
image_encoder: Optional[CLIPVisionModelWithProjection] = None,
|
114
162
|
requires_safety_checker: bool = True,
|
115
163
|
):
|
116
164
|
super().__init__()
|
@@ -139,6 +187,7 @@ class LatentConsistencyModelPipeline(
|
|
139
187
|
scheduler=scheduler,
|
140
188
|
safety_checker=safety_checker,
|
141
189
|
feature_extractor=feature_extractor,
|
190
|
+
image_encoder=image_encoder,
|
142
191
|
)
|
143
192
|
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
144
193
|
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
@@ -387,6 +436,31 @@ class LatentConsistencyModelPipeline(
|
|
387
436
|
|
388
437
|
return prompt_embeds, negative_prompt_embeds
|
389
438
|
|
439
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
440
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
441
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
442
|
+
|
443
|
+
if not isinstance(image, torch.Tensor):
|
444
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
445
|
+
|
446
|
+
image = image.to(device=device, dtype=dtype)
|
447
|
+
if output_hidden_states:
|
448
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
449
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
450
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
451
|
+
torch.zeros_like(image), output_hidden_states=True
|
452
|
+
).hidden_states[-2]
|
453
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
454
|
+
num_images_per_prompt, dim=0
|
455
|
+
)
|
456
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
457
|
+
else:
|
458
|
+
image_embeds = self.image_encoder(image).image_embeds
|
459
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
460
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
461
|
+
|
462
|
+
return image_embeds, uncond_image_embeds
|
463
|
+
|
390
464
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
391
465
|
def run_safety_checker(self, image, device, dtype):
|
392
466
|
if self.safety_checker is None:
|
@@ -529,11 +603,13 @@ class LatentConsistencyModelPipeline(
|
|
529
603
|
width: Optional[int] = None,
|
530
604
|
num_inference_steps: int = 4,
|
531
605
|
original_inference_steps: int = None,
|
606
|
+
timesteps: List[int] = None,
|
532
607
|
guidance_scale: float = 8.5,
|
533
608
|
num_images_per_prompt: Optional[int] = 1,
|
534
609
|
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
535
610
|
latents: Optional[torch.FloatTensor] = None,
|
536
611
|
prompt_embeds: Optional[torch.FloatTensor] = None,
|
612
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
537
613
|
output_type: Optional[str] = "pil",
|
538
614
|
return_dict: bool = True,
|
539
615
|
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
@@ -560,6 +636,10 @@ class LatentConsistencyModelPipeline(
|
|
560
636
|
we will draw `num_inference_steps` evenly spaced timesteps from as our final timestep schedule,
|
561
637
|
following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the
|
562
638
|
scheduler's `original_inference_steps` attribute.
|
639
|
+
timesteps (`List[int]`, *optional*):
|
640
|
+
Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
|
641
|
+
timesteps on the original LCM training/distillation timestep schedule are used. Must be in descending
|
642
|
+
order.
|
563
643
|
guidance_scale (`float`, *optional*, defaults to 7.5):
|
564
644
|
A higher guidance scale value encourages the model to generate images closely linked to the text
|
565
645
|
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
@@ -578,6 +658,8 @@ class LatentConsistencyModelPipeline(
|
|
578
658
|
prompt_embeds (`torch.FloatTensor`, *optional*):
|
579
659
|
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
580
660
|
provided, text embeddings are generated from the `prompt` input argument.
|
661
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*):
|
662
|
+
Optional image input to work with IP Adapters.
|
581
663
|
output_type (`str`, *optional*, defaults to `"pil"`):
|
582
664
|
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
583
665
|
return_dict (`bool`, *optional*, defaults to `True`):
|
@@ -597,7 +679,7 @@ class LatentConsistencyModelPipeline(
|
|
597
679
|
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
598
680
|
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
599
681
|
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
600
|
-
`._callback_tensor_inputs` attribute of your
|
682
|
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
601
683
|
|
602
684
|
Examples:
|
603
685
|
|
@@ -646,6 +728,12 @@ class LatentConsistencyModelPipeline(
|
|
646
728
|
device = self._execution_device
|
647
729
|
# do_classifier_free_guidance = guidance_scale > 1.0
|
648
730
|
|
731
|
+
if ip_adapter_image is not None:
|
732
|
+
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
733
|
+
image_embeds, negative_image_embeds = self.encode_image(
|
734
|
+
ip_adapter_image, device, num_images_per_prompt, output_hidden_state
|
735
|
+
)
|
736
|
+
|
649
737
|
# 3. Encode input prompt
|
650
738
|
lora_scale = (
|
651
739
|
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
@@ -667,8 +755,9 @@ class LatentConsistencyModelPipeline(
|
|
667
755
|
)
|
668
756
|
|
669
757
|
# 4. Prepare timesteps
|
670
|
-
|
671
|
-
|
758
|
+
timesteps, num_inference_steps = retrieve_timesteps(
|
759
|
+
self.scheduler, num_inference_steps, device, timesteps, original_inference_steps=original_inference_steps
|
760
|
+
)
|
672
761
|
|
673
762
|
# 5. Prepare latent variable
|
674
763
|
num_channels_latents = self.unet.config.in_channels
|
@@ -696,6 +785,9 @@ class LatentConsistencyModelPipeline(
|
|
696
785
|
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
697
786
|
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, None)
|
698
787
|
|
788
|
+
# 7.1 Add image embeds for IP-Adapter
|
789
|
+
added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
|
790
|
+
|
699
791
|
# 8. LCM MultiStep Sampling Loop:
|
700
792
|
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
701
793
|
self._num_timesteps = len(timesteps)
|
@@ -710,6 +802,7 @@ class LatentConsistencyModelPipeline(
|
|
710
802
|
timestep_cond=w_embedding,
|
711
803
|
encoder_hidden_states=prompt_embeds,
|
712
804
|
cross_attention_kwargs=self.cross_attention_kwargs,
|
805
|
+
added_cond_kwargs=added_cond_kwargs,
|
713
806
|
return_dict=False,
|
714
807
|
)[0]
|
715
808
|
|
@@ -49,6 +49,7 @@ class LDMTextToImagePipeline(DiffusionPipeline):
|
|
49
49
|
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
50
50
|
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
51
51
|
"""
|
52
|
+
|
52
53
|
model_cpu_offload_seq = "bert->unet->vqvae"
|
53
54
|
|
54
55
|
def __init__(
|
@@ -51,7 +51,7 @@ EXAMPLE_DOC_STRING = """
|
|
51
51
|
>>> import torch
|
52
52
|
>>> import scipy
|
53
53
|
|
54
|
-
>>> repo_id = "
|
54
|
+
>>> repo_id = "ucsd-reach/musicldm"
|
55
55
|
>>> pipe = MusicLDMPipeline.from_pretrained(repo_id, torch_dtype=torch.float16)
|
56
56
|
>>> pipe = pipe.to("cuda")
|
57
57
|
|
@@ -22,6 +22,7 @@ from typing import Optional, Union
|
|
22
22
|
|
23
23
|
import numpy as np
|
24
24
|
from huggingface_hub import hf_hub_download
|
25
|
+
from huggingface_hub.utils import validate_hf_hub_args
|
25
26
|
|
26
27
|
from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging
|
27
28
|
|
@@ -130,10 +131,11 @@ class OnnxRuntimeModel:
|
|
130
131
|
self._save_pretrained(save_directory, **kwargs)
|
131
132
|
|
132
133
|
@classmethod
|
134
|
+
@validate_hf_hub_args
|
133
135
|
def _from_pretrained(
|
134
136
|
cls,
|
135
137
|
model_id: Union[str, Path],
|
136
|
-
|
138
|
+
token: Optional[Union[bool, str, None]] = None,
|
137
139
|
revision: Optional[Union[str, None]] = None,
|
138
140
|
force_download: bool = False,
|
139
141
|
cache_dir: Optional[str] = None,
|
@@ -148,7 +150,7 @@ class OnnxRuntimeModel:
|
|
148
150
|
Arguments:
|
149
151
|
model_id (`str` or `Path`):
|
150
152
|
Directory from which to load
|
151
|
-
|
153
|
+
token (`str` or `bool`):
|
152
154
|
Is needed to load models from a private or gated repository
|
153
155
|
revision (`str`):
|
154
156
|
Revision is the specific model version to use. It can be a branch name, a tag name, or a commit id
|
@@ -179,7 +181,7 @@ class OnnxRuntimeModel:
|
|
179
181
|
model_cache_path = hf_hub_download(
|
180
182
|
repo_id=model_id,
|
181
183
|
filename=model_file_name,
|
182
|
-
|
184
|
+
token=token,
|
183
185
|
revision=revision,
|
184
186
|
cache_dir=cache_dir,
|
185
187
|
force_download=force_download,
|
@@ -190,11 +192,12 @@ class OnnxRuntimeModel:
|
|
190
192
|
return cls(model=model, **kwargs)
|
191
193
|
|
192
194
|
@classmethod
|
195
|
+
@validate_hf_hub_args
|
193
196
|
def from_pretrained(
|
194
197
|
cls,
|
195
198
|
model_id: Union[str, Path],
|
196
199
|
force_download: bool = True,
|
197
|
-
|
200
|
+
token: Optional[str] = None,
|
198
201
|
cache_dir: Optional[str] = None,
|
199
202
|
**model_kwargs,
|
200
203
|
):
|
@@ -207,6 +210,6 @@ class OnnxRuntimeModel:
|
|
207
210
|
revision=revision,
|
208
211
|
cache_dir=cache_dir,
|
209
212
|
force_download=force_download,
|
210
|
-
|
213
|
+
token=token,
|
211
214
|
**model_kwargs,
|
212
215
|
)
|
@@ -35,9 +35,13 @@ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
|
35
35
|
|
36
36
|
|
37
37
|
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
38
|
-
def retrieve_latents(
|
39
|
-
|
38
|
+
def retrieve_latents(
|
39
|
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
40
|
+
):
|
41
|
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
40
42
|
return encoder_output.latent_dist.sample(generator)
|
43
|
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
44
|
+
return encoder_output.latent_dist.mode()
|
41
45
|
elif hasattr(encoder_output, "latents"):
|
42
46
|
return encoder_output.latents
|
43
47
|
else:
|
@@ -177,6 +181,7 @@ class PaintByExamplePipeline(DiffusionPipeline):
|
|
177
181
|
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
178
182
|
|
179
183
|
"""
|
184
|
+
|
180
185
|
# TODO: feature_extractor is required to encode initial images (if they are in PIL format),
|
181
186
|
# we should give a descriptive message if the pipeline doesn't have one.
|
182
187
|
|
@@ -24,6 +24,7 @@ import numpy as np
|
|
24
24
|
import PIL.Image
|
25
25
|
from flax.core.frozen_dict import FrozenDict
|
26
26
|
from huggingface_hub import create_repo, snapshot_download
|
27
|
+
from huggingface_hub.utils import validate_hf_hub_args
|
27
28
|
from PIL import Image
|
28
29
|
from tqdm.auto import tqdm
|
29
30
|
|
@@ -32,7 +33,6 @@ from ..models.modeling_flax_utils import FLAX_WEIGHTS_NAME, FlaxModelMixin
|
|
32
33
|
from ..schedulers.scheduling_utils_flax import SCHEDULER_CONFIG_NAME, FlaxSchedulerMixin
|
33
34
|
from ..utils import (
|
34
35
|
CONFIG_NAME,
|
35
|
-
DIFFUSERS_CACHE,
|
36
36
|
BaseOutput,
|
37
37
|
PushToHubMixin,
|
38
38
|
http_user_agent,
|
@@ -112,6 +112,7 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
|
|
112
112
|
- **config_name** ([`str`]) -- The configuration filename that stores the class and module names of all the
|
113
113
|
diffusion pipeline's components.
|
114
114
|
"""
|
115
|
+
|
115
116
|
config_name = "model_index.json"
|
116
117
|
|
117
118
|
def register_modules(self, **kwargs):
|
@@ -226,6 +227,7 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
|
|
226
227
|
)
|
227
228
|
|
228
229
|
@classmethod
|
230
|
+
@validate_hf_hub_args
|
229
231
|
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
|
230
232
|
r"""
|
231
233
|
Instantiate a Flax-based diffusion pipeline from pretrained pipeline weights.
|
@@ -263,7 +265,7 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
|
|
263
265
|
local_files_only (`bool`, *optional*, defaults to `False`):
|
264
266
|
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
265
267
|
won't be downloaded from the Hub.
|
266
|
-
|
268
|
+
token (`str` or *bool*, *optional*):
|
267
269
|
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
268
270
|
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
269
271
|
revision (`str`, *optional*, defaults to `"main"`):
|
@@ -313,11 +315,11 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
|
|
313
315
|
>>> dpm_params["scheduler"] = dpmpp_state
|
314
316
|
```
|
315
317
|
"""
|
316
|
-
cache_dir = kwargs.pop("cache_dir",
|
318
|
+
cache_dir = kwargs.pop("cache_dir", None)
|
317
319
|
resume_download = kwargs.pop("resume_download", False)
|
318
320
|
proxies = kwargs.pop("proxies", None)
|
319
321
|
local_files_only = kwargs.pop("local_files_only", False)
|
320
|
-
|
322
|
+
token = kwargs.pop("token", None)
|
321
323
|
revision = kwargs.pop("revision", None)
|
322
324
|
from_pt = kwargs.pop("from_pt", False)
|
323
325
|
use_memory_efficient_attention = kwargs.pop("use_memory_efficient_attention", False)
|
@@ -333,7 +335,7 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
|
|
333
335
|
resume_download=resume_download,
|
334
336
|
proxies=proxies,
|
335
337
|
local_files_only=local_files_only,
|
336
|
-
|
338
|
+
token=token,
|
337
339
|
revision=revision,
|
338
340
|
)
|
339
341
|
# make sure we only download sub-folders and `diffusers` filenames
|
@@ -364,7 +366,7 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
|
|
364
366
|
resume_download=resume_download,
|
365
367
|
proxies=proxies,
|
366
368
|
local_files_only=local_files_only,
|
367
|
-
|
369
|
+
token=token,
|
368
370
|
revision=revision,
|
369
371
|
allow_patterns=allow_patterns,
|
370
372
|
ignore_patterns=ignore_patterns,
|
@@ -537,12 +539,13 @@ class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin):
|
|
537
539
|
model = pipeline_class(**init_kwargs, dtype=dtype)
|
538
540
|
return model, params
|
539
541
|
|
540
|
-
@
|
541
|
-
def _get_signature_keys(obj):
|
542
|
+
@classmethod
|
543
|
+
def _get_signature_keys(cls, obj):
|
542
544
|
parameters = inspect.signature(obj.__init__).parameters
|
543
545
|
required_parameters = {k: v for k, v in parameters.items() if v.default == inspect._empty}
|
544
546
|
optional_parameters = set({k for k, v in parameters.items() if v.default != inspect._empty})
|
545
547
|
expected_modules = set(required_parameters.keys()) - {"self"}
|
548
|
+
|
546
549
|
return expected_modules, optional_parameters
|
547
550
|
|
548
551
|
@property
|