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
@@ -0,0 +1,378 @@
|
|
1
|
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
2
|
+
#
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4
|
+
# you may not use this file except in compliance with the License.
|
5
|
+
# You may obtain a copy of the License at
|
6
|
+
#
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8
|
+
#
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12
|
+
# See the License for the specific language governing permissions and
|
13
|
+
# limitations under the License.
|
14
|
+
|
15
|
+
|
16
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
17
|
+
|
18
|
+
import torch
|
19
|
+
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
|
20
|
+
|
21
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
22
|
+
from ...models import UVit2DModel, VQModel
|
23
|
+
from ...schedulers import AmusedScheduler
|
24
|
+
from ...utils import replace_example_docstring
|
25
|
+
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
26
|
+
|
27
|
+
|
28
|
+
EXAMPLE_DOC_STRING = """
|
29
|
+
Examples:
|
30
|
+
```py
|
31
|
+
>>> import torch
|
32
|
+
>>> from diffusers import AmusedInpaintPipeline
|
33
|
+
>>> from diffusers.utils import load_image
|
34
|
+
|
35
|
+
>>> pipe = AmusedInpaintPipeline.from_pretrained(
|
36
|
+
... "amused/amused-512", variant="fp16", torch_dtype=torch.float16
|
37
|
+
... )
|
38
|
+
>>> pipe = pipe.to("cuda")
|
39
|
+
|
40
|
+
>>> prompt = "fall mountains"
|
41
|
+
>>> input_image = (
|
42
|
+
... load_image(
|
43
|
+
... "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1.jpg"
|
44
|
+
... )
|
45
|
+
... .resize((512, 512))
|
46
|
+
... .convert("RGB")
|
47
|
+
... )
|
48
|
+
>>> mask = (
|
49
|
+
... load_image(
|
50
|
+
... "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1_mask.png"
|
51
|
+
... )
|
52
|
+
... .resize((512, 512))
|
53
|
+
... .convert("L")
|
54
|
+
... )
|
55
|
+
>>> pipe(prompt, input_image, mask).images[0].save("out.png")
|
56
|
+
```
|
57
|
+
"""
|
58
|
+
|
59
|
+
|
60
|
+
class AmusedInpaintPipeline(DiffusionPipeline):
|
61
|
+
image_processor: VaeImageProcessor
|
62
|
+
vqvae: VQModel
|
63
|
+
tokenizer: CLIPTokenizer
|
64
|
+
text_encoder: CLIPTextModelWithProjection
|
65
|
+
transformer: UVit2DModel
|
66
|
+
scheduler: AmusedScheduler
|
67
|
+
|
68
|
+
model_cpu_offload_seq = "text_encoder->transformer->vqvae"
|
69
|
+
|
70
|
+
# TODO - when calling self.vqvae.quantize, it uses self.vqvae.quantize.embedding.weight before
|
71
|
+
# the forward method of self.vqvae.quantize, so the hook doesn't get called to move the parameter
|
72
|
+
# off the meta device. There should be a way to fix this instead of just not offloading it
|
73
|
+
_exclude_from_cpu_offload = ["vqvae"]
|
74
|
+
|
75
|
+
def __init__(
|
76
|
+
self,
|
77
|
+
vqvae: VQModel,
|
78
|
+
tokenizer: CLIPTokenizer,
|
79
|
+
text_encoder: CLIPTextModelWithProjection,
|
80
|
+
transformer: UVit2DModel,
|
81
|
+
scheduler: AmusedScheduler,
|
82
|
+
):
|
83
|
+
super().__init__()
|
84
|
+
|
85
|
+
self.register_modules(
|
86
|
+
vqvae=vqvae,
|
87
|
+
tokenizer=tokenizer,
|
88
|
+
text_encoder=text_encoder,
|
89
|
+
transformer=transformer,
|
90
|
+
scheduler=scheduler,
|
91
|
+
)
|
92
|
+
self.vae_scale_factor = 2 ** (len(self.vqvae.config.block_out_channels) - 1)
|
93
|
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_normalize=False)
|
94
|
+
self.mask_processor = VaeImageProcessor(
|
95
|
+
vae_scale_factor=self.vae_scale_factor,
|
96
|
+
do_normalize=False,
|
97
|
+
do_binarize=True,
|
98
|
+
do_convert_grayscale=True,
|
99
|
+
do_resize=True,
|
100
|
+
)
|
101
|
+
self.scheduler.register_to_config(masking_schedule="linear")
|
102
|
+
|
103
|
+
@torch.no_grad()
|
104
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
105
|
+
def __call__(
|
106
|
+
self,
|
107
|
+
prompt: Optional[Union[List[str], str]] = None,
|
108
|
+
image: PipelineImageInput = None,
|
109
|
+
mask_image: PipelineImageInput = None,
|
110
|
+
strength: float = 1.0,
|
111
|
+
num_inference_steps: int = 12,
|
112
|
+
guidance_scale: float = 10.0,
|
113
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
114
|
+
num_images_per_prompt: Optional[int] = 1,
|
115
|
+
generator: Optional[torch.Generator] = None,
|
116
|
+
prompt_embeds: Optional[torch.Tensor] = None,
|
117
|
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
118
|
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
119
|
+
negative_encoder_hidden_states: Optional[torch.Tensor] = None,
|
120
|
+
output_type="pil",
|
121
|
+
return_dict: bool = True,
|
122
|
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
123
|
+
callback_steps: int = 1,
|
124
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
125
|
+
micro_conditioning_aesthetic_score: int = 6,
|
126
|
+
micro_conditioning_crop_coord: Tuple[int, int] = (0, 0),
|
127
|
+
temperature: Union[int, Tuple[int, int], List[int]] = (2, 0),
|
128
|
+
):
|
129
|
+
"""
|
130
|
+
The call function to the pipeline for generation.
|
131
|
+
|
132
|
+
Args:
|
133
|
+
prompt (`str` or `List[str]`, *optional*):
|
134
|
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
135
|
+
image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
136
|
+
`Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
|
137
|
+
numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
|
138
|
+
or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
|
139
|
+
list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
|
140
|
+
latents as `image`, but if passing latents directly it is not encoded again.
|
141
|
+
mask_image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
142
|
+
`Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
|
143
|
+
are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
|
144
|
+
single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
|
145
|
+
color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
|
146
|
+
H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
|
147
|
+
1)`, or `(H, W)`.
|
148
|
+
strength (`float`, *optional*, defaults to 1.0):
|
149
|
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
150
|
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
151
|
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
152
|
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
153
|
+
essentially ignores `image`.
|
154
|
+
num_inference_steps (`int`, *optional*, defaults to 16):
|
155
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
156
|
+
expense of slower inference.
|
157
|
+
guidance_scale (`float`, *optional*, defaults to 10.0):
|
158
|
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
159
|
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
160
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
161
|
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
162
|
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
163
|
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
164
|
+
The number of images to generate per prompt.
|
165
|
+
generator (`torch.Generator`, *optional*):
|
166
|
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
167
|
+
generation deterministic.
|
168
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
169
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
170
|
+
provided, text embeddings are generated from the `prompt` input argument. A single vector from the
|
171
|
+
pooled and projected final hidden states.
|
172
|
+
encoder_hidden_states (`torch.FloatTensor`, *optional*):
|
173
|
+
Pre-generated penultimate hidden states from the text encoder providing additional text conditioning.
|
174
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
175
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
176
|
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
177
|
+
negative_encoder_hidden_states (`torch.FloatTensor`, *optional*):
|
178
|
+
Analogous to `encoder_hidden_states` for the positive prompt.
|
179
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
180
|
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
181
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
182
|
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
183
|
+
plain tuple.
|
184
|
+
callback (`Callable`, *optional*):
|
185
|
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
186
|
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
187
|
+
callback_steps (`int`, *optional*, defaults to 1):
|
188
|
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
189
|
+
every step.
|
190
|
+
cross_attention_kwargs (`dict`, *optional*):
|
191
|
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
192
|
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
193
|
+
micro_conditioning_aesthetic_score (`int`, *optional*, defaults to 6):
|
194
|
+
The targeted aesthetic score according to the laion aesthetic classifier. See https://laion.ai/blog/laion-aesthetics/
|
195
|
+
and the micro-conditioning section of https://arxiv.org/abs/2307.01952.
|
196
|
+
micro_conditioning_crop_coord (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
197
|
+
The targeted height, width crop coordinates. See the micro-conditioning section of https://arxiv.org/abs/2307.01952.
|
198
|
+
temperature (`Union[int, Tuple[int, int], List[int]]`, *optional*, defaults to (2, 0)):
|
199
|
+
Configures the temperature scheduler on `self.scheduler` see `AmusedScheduler#set_timesteps`.
|
200
|
+
|
201
|
+
Examples:
|
202
|
+
|
203
|
+
Returns:
|
204
|
+
[`~pipelines.pipeline_utils.ImagePipelineOutput`] or `tuple`:
|
205
|
+
If `return_dict` is `True`, [`~pipelines.pipeline_utils.ImagePipelineOutput`] is returned, otherwise a
|
206
|
+
`tuple` is returned where the first element is a list with the generated images.
|
207
|
+
"""
|
208
|
+
|
209
|
+
if (prompt_embeds is not None and encoder_hidden_states is None) or (
|
210
|
+
prompt_embeds is None and encoder_hidden_states is not None
|
211
|
+
):
|
212
|
+
raise ValueError("pass either both `prompt_embeds` and `encoder_hidden_states` or neither")
|
213
|
+
|
214
|
+
if (negative_prompt_embeds is not None and negative_encoder_hidden_states is None) or (
|
215
|
+
negative_prompt_embeds is None and negative_encoder_hidden_states is not None
|
216
|
+
):
|
217
|
+
raise ValueError(
|
218
|
+
"pass either both `negatve_prompt_embeds` and `negative_encoder_hidden_states` or neither"
|
219
|
+
)
|
220
|
+
|
221
|
+
if (prompt is None and prompt_embeds is None) or (prompt is not None and prompt_embeds is not None):
|
222
|
+
raise ValueError("pass only one of `prompt` or `prompt_embeds`")
|
223
|
+
|
224
|
+
if isinstance(prompt, str):
|
225
|
+
prompt = [prompt]
|
226
|
+
|
227
|
+
if prompt is not None:
|
228
|
+
batch_size = len(prompt)
|
229
|
+
else:
|
230
|
+
batch_size = prompt_embeds.shape[0]
|
231
|
+
|
232
|
+
batch_size = batch_size * num_images_per_prompt
|
233
|
+
|
234
|
+
if prompt_embeds is None:
|
235
|
+
input_ids = self.tokenizer(
|
236
|
+
prompt,
|
237
|
+
return_tensors="pt",
|
238
|
+
padding="max_length",
|
239
|
+
truncation=True,
|
240
|
+
max_length=self.tokenizer.model_max_length,
|
241
|
+
).input_ids.to(self._execution_device)
|
242
|
+
|
243
|
+
outputs = self.text_encoder(input_ids, return_dict=True, output_hidden_states=True)
|
244
|
+
prompt_embeds = outputs.text_embeds
|
245
|
+
encoder_hidden_states = outputs.hidden_states[-2]
|
246
|
+
|
247
|
+
prompt_embeds = prompt_embeds.repeat(num_images_per_prompt, 1)
|
248
|
+
encoder_hidden_states = encoder_hidden_states.repeat(num_images_per_prompt, 1, 1)
|
249
|
+
|
250
|
+
if guidance_scale > 1.0:
|
251
|
+
if negative_prompt_embeds is None:
|
252
|
+
if negative_prompt is None:
|
253
|
+
negative_prompt = [""] * len(prompt)
|
254
|
+
|
255
|
+
if isinstance(negative_prompt, str):
|
256
|
+
negative_prompt = [negative_prompt]
|
257
|
+
|
258
|
+
input_ids = self.tokenizer(
|
259
|
+
negative_prompt,
|
260
|
+
return_tensors="pt",
|
261
|
+
padding="max_length",
|
262
|
+
truncation=True,
|
263
|
+
max_length=self.tokenizer.model_max_length,
|
264
|
+
).input_ids.to(self._execution_device)
|
265
|
+
|
266
|
+
outputs = self.text_encoder(input_ids, return_dict=True, output_hidden_states=True)
|
267
|
+
negative_prompt_embeds = outputs.text_embeds
|
268
|
+
negative_encoder_hidden_states = outputs.hidden_states[-2]
|
269
|
+
|
270
|
+
negative_prompt_embeds = negative_prompt_embeds.repeat(num_images_per_prompt, 1)
|
271
|
+
negative_encoder_hidden_states = negative_encoder_hidden_states.repeat(num_images_per_prompt, 1, 1)
|
272
|
+
|
273
|
+
prompt_embeds = torch.concat([negative_prompt_embeds, prompt_embeds])
|
274
|
+
encoder_hidden_states = torch.concat([negative_encoder_hidden_states, encoder_hidden_states])
|
275
|
+
|
276
|
+
image = self.image_processor.preprocess(image)
|
277
|
+
|
278
|
+
height, width = image.shape[-2:]
|
279
|
+
|
280
|
+
# Note that the micro conditionings _do_ flip the order of width, height for the original size
|
281
|
+
# and the crop coordinates. This is how it was done in the original code base
|
282
|
+
micro_conds = torch.tensor(
|
283
|
+
[
|
284
|
+
width,
|
285
|
+
height,
|
286
|
+
micro_conditioning_crop_coord[0],
|
287
|
+
micro_conditioning_crop_coord[1],
|
288
|
+
micro_conditioning_aesthetic_score,
|
289
|
+
],
|
290
|
+
device=self._execution_device,
|
291
|
+
dtype=encoder_hidden_states.dtype,
|
292
|
+
)
|
293
|
+
|
294
|
+
micro_conds = micro_conds.unsqueeze(0)
|
295
|
+
micro_conds = micro_conds.expand(2 * batch_size if guidance_scale > 1.0 else batch_size, -1)
|
296
|
+
|
297
|
+
self.scheduler.set_timesteps(num_inference_steps, temperature, self._execution_device)
|
298
|
+
num_inference_steps = int(len(self.scheduler.timesteps) * strength)
|
299
|
+
start_timestep_idx = len(self.scheduler.timesteps) - num_inference_steps
|
300
|
+
|
301
|
+
needs_upcasting = self.vqvae.dtype == torch.float16 and self.vqvae.config.force_upcast
|
302
|
+
|
303
|
+
if needs_upcasting:
|
304
|
+
self.vqvae.float()
|
305
|
+
|
306
|
+
latents = self.vqvae.encode(image.to(dtype=self.vqvae.dtype, device=self._execution_device)).latents
|
307
|
+
latents_bsz, channels, latents_height, latents_width = latents.shape
|
308
|
+
latents = self.vqvae.quantize(latents)[2][2].reshape(latents_bsz, latents_height, latents_width)
|
309
|
+
|
310
|
+
mask = self.mask_processor.preprocess(
|
311
|
+
mask_image, height // self.vae_scale_factor, width // self.vae_scale_factor
|
312
|
+
)
|
313
|
+
mask = mask.reshape(mask.shape[0], latents_height, latents_width).bool().to(latents.device)
|
314
|
+
latents[mask] = self.scheduler.config.mask_token_id
|
315
|
+
|
316
|
+
starting_mask_ratio = mask.sum() / latents.numel()
|
317
|
+
|
318
|
+
latents = latents.repeat(num_images_per_prompt, 1, 1)
|
319
|
+
|
320
|
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
321
|
+
for i in range(start_timestep_idx, len(self.scheduler.timesteps)):
|
322
|
+
timestep = self.scheduler.timesteps[i]
|
323
|
+
|
324
|
+
if guidance_scale > 1.0:
|
325
|
+
model_input = torch.cat([latents] * 2)
|
326
|
+
else:
|
327
|
+
model_input = latents
|
328
|
+
|
329
|
+
model_output = self.transformer(
|
330
|
+
model_input,
|
331
|
+
micro_conds=micro_conds,
|
332
|
+
pooled_text_emb=prompt_embeds,
|
333
|
+
encoder_hidden_states=encoder_hidden_states,
|
334
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
335
|
+
)
|
336
|
+
|
337
|
+
if guidance_scale > 1.0:
|
338
|
+
uncond_logits, cond_logits = model_output.chunk(2)
|
339
|
+
model_output = uncond_logits + guidance_scale * (cond_logits - uncond_logits)
|
340
|
+
|
341
|
+
latents = self.scheduler.step(
|
342
|
+
model_output=model_output,
|
343
|
+
timestep=timestep,
|
344
|
+
sample=latents,
|
345
|
+
generator=generator,
|
346
|
+
starting_mask_ratio=starting_mask_ratio,
|
347
|
+
).prev_sample
|
348
|
+
|
349
|
+
if i == len(self.scheduler.timesteps) - 1 or ((i + 1) % self.scheduler.order == 0):
|
350
|
+
progress_bar.update()
|
351
|
+
if callback is not None and i % callback_steps == 0:
|
352
|
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
353
|
+
callback(step_idx, timestep, latents)
|
354
|
+
|
355
|
+
if output_type == "latent":
|
356
|
+
output = latents
|
357
|
+
else:
|
358
|
+
output = self.vqvae.decode(
|
359
|
+
latents,
|
360
|
+
force_not_quantize=True,
|
361
|
+
shape=(
|
362
|
+
batch_size,
|
363
|
+
height // self.vae_scale_factor,
|
364
|
+
width // self.vae_scale_factor,
|
365
|
+
self.vqvae.config.latent_channels,
|
366
|
+
),
|
367
|
+
).sample.clip(0, 1)
|
368
|
+
output = self.image_processor.postprocess(output, output_type)
|
369
|
+
|
370
|
+
if needs_upcasting:
|
371
|
+
self.vqvae.half()
|
372
|
+
|
373
|
+
self.maybe_free_model_hooks()
|
374
|
+
|
375
|
+
if not return_dict:
|
376
|
+
return (output,)
|
377
|
+
|
378
|
+
return ImagePipelineOutput(output)
|
@@ -18,11 +18,11 @@ from typing import Any, Callable, Dict, List, Optional, Union
|
|
18
18
|
|
19
19
|
import numpy as np
|
20
20
|
import torch
|
21
|
-
from transformers import CLIPTextModel, CLIPTokenizer
|
21
|
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
22
22
|
|
23
|
-
from ...image_processor import VaeImageProcessor
|
24
|
-
from ...loaders import LoraLoaderMixin, TextualInversionLoaderMixin
|
25
|
-
from ...models import AutoencoderKL, UNet2DConditionModel, UNetMotionModel
|
23
|
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
24
|
+
from ...loaders import IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
25
|
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel, UNetMotionModel
|
26
26
|
from ...models.lora import adjust_lora_scale_text_encoder
|
27
27
|
from ...models.unet_motion_model import MotionAdapter
|
28
28
|
from ...schedulers import (
|
@@ -33,7 +33,14 @@ from ...schedulers import (
|
|
33
33
|
LMSDiscreteScheduler,
|
34
34
|
PNDMScheduler,
|
35
35
|
)
|
36
|
-
from ...utils import
|
36
|
+
from ...utils import (
|
37
|
+
USE_PEFT_BACKEND,
|
38
|
+
BaseOutput,
|
39
|
+
logging,
|
40
|
+
replace_example_docstring,
|
41
|
+
scale_lora_layers,
|
42
|
+
unscale_lora_layers,
|
43
|
+
)
|
37
44
|
from ...utils.torch_utils import randn_tensor
|
38
45
|
from ..pipeline_utils import DiffusionPipeline
|
39
46
|
|
@@ -47,7 +54,7 @@ EXAMPLE_DOC_STRING = """
|
|
47
54
|
>>> from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
|
48
55
|
>>> from diffusers.utils import export_to_gif
|
49
56
|
|
50
|
-
>>> adapter = MotionAdapter.from_pretrained("
|
57
|
+
>>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
|
51
58
|
>>> pipe = AnimateDiffPipeline.from_pretrained("frankjoshua/toonyou_beta6", motion_adapter=adapter)
|
52
59
|
>>> pipe.scheduler = DDIMScheduler(beta_schedule="linear", steps_offset=1, clip_sample=False)
|
53
60
|
>>> output = pipe(prompt="A corgi walking in the park")
|
@@ -77,13 +84,19 @@ class AnimateDiffPipelineOutput(BaseOutput):
|
|
77
84
|
frames: Union[torch.Tensor, np.ndarray]
|
78
85
|
|
79
86
|
|
80
|
-
class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin):
|
87
|
+
class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin):
|
81
88
|
r"""
|
82
89
|
Pipeline for text-to-video generation.
|
83
90
|
|
84
91
|
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
85
92
|
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
86
93
|
|
94
|
+
The pipeline also inherits the following loading methods:
|
95
|
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
96
|
+
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
97
|
+
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
98
|
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
99
|
+
|
87
100
|
Args:
|
88
101
|
vae ([`AutoencoderKL`]):
|
89
102
|
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
@@ -99,7 +112,9 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
99
112
|
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
100
113
|
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
101
114
|
"""
|
102
|
-
|
115
|
+
|
116
|
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
117
|
+
_optional_components = ["feature_extractor", "image_encoder"]
|
103
118
|
|
104
119
|
def __init__(
|
105
120
|
self,
|
@@ -116,6 +131,8 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
116
131
|
EulerAncestralDiscreteScheduler,
|
117
132
|
DPMSolverMultistepScheduler,
|
118
133
|
],
|
134
|
+
feature_extractor: CLIPImageProcessor = None,
|
135
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
119
136
|
):
|
120
137
|
super().__init__()
|
121
138
|
unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
|
@@ -127,6 +144,8 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
127
144
|
unet=unet,
|
128
145
|
motion_adapter=motion_adapter,
|
129
146
|
scheduler=scheduler,
|
147
|
+
feature_extractor=feature_extractor,
|
148
|
+
image_encoder=image_encoder,
|
130
149
|
)
|
131
150
|
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
132
151
|
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
@@ -313,6 +332,31 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
313
332
|
|
314
333
|
return prompt_embeds, negative_prompt_embeds
|
315
334
|
|
335
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
336
|
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
337
|
+
dtype = next(self.image_encoder.parameters()).dtype
|
338
|
+
|
339
|
+
if not isinstance(image, torch.Tensor):
|
340
|
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
341
|
+
|
342
|
+
image = image.to(device=device, dtype=dtype)
|
343
|
+
if output_hidden_states:
|
344
|
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
345
|
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
346
|
+
uncond_image_enc_hidden_states = self.image_encoder(
|
347
|
+
torch.zeros_like(image), output_hidden_states=True
|
348
|
+
).hidden_states[-2]
|
349
|
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
350
|
+
num_images_per_prompt, dim=0
|
351
|
+
)
|
352
|
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
353
|
+
else:
|
354
|
+
image_embeds = self.image_encoder(image).image_embeds
|
355
|
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
356
|
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
357
|
+
|
358
|
+
return image_embeds, uncond_image_embeds
|
359
|
+
|
316
360
|
# Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
|
317
361
|
def decode_latents(self, latents):
|
318
362
|
latents = 1 / self.vae.config.scaling_factor * latents
|
@@ -496,6 +540,7 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
496
540
|
return latents
|
497
541
|
|
498
542
|
@torch.no_grad()
|
543
|
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
499
544
|
def __call__(
|
500
545
|
self,
|
501
546
|
prompt: Union[str, List[str]] = None,
|
@@ -511,6 +556,7 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
511
556
|
latents: Optional[torch.FloatTensor] = None,
|
512
557
|
prompt_embeds: Optional[torch.FloatTensor] = None,
|
513
558
|
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
559
|
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
514
560
|
output_type: Optional[str] = "pil",
|
515
561
|
return_dict: bool = True,
|
516
562
|
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
@@ -557,6 +603,7 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
557
603
|
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
558
604
|
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
559
605
|
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
606
|
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
560
607
|
output_type (`str`, *optional*, defaults to `"pil"`):
|
561
608
|
The output format of the generated video. Choose between `torch.FloatTensor`, `PIL.Image` or
|
562
609
|
`np.array`.
|
@@ -628,6 +675,14 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
628
675
|
if do_classifier_free_guidance:
|
629
676
|
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
630
677
|
|
678
|
+
if ip_adapter_image is not None:
|
679
|
+
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
680
|
+
image_embeds, negative_image_embeds = self.encode_image(
|
681
|
+
ip_adapter_image, device, num_videos_per_prompt, output_hidden_state
|
682
|
+
)
|
683
|
+
if do_classifier_free_guidance:
|
684
|
+
image_embeds = torch.cat([negative_image_embeds, image_embeds])
|
685
|
+
|
631
686
|
# 4. Prepare timesteps
|
632
687
|
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
633
688
|
timesteps = self.scheduler.timesteps
|
@@ -648,6 +703,8 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
648
703
|
|
649
704
|
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
650
705
|
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
706
|
+
# 7 Add image embeds for IP-Adapter
|
707
|
+
added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
|
651
708
|
|
652
709
|
# Denoising loop
|
653
710
|
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
@@ -663,6 +720,7 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
|
|
663
720
|
t,
|
664
721
|
encoder_hidden_states=prompt_embeds,
|
665
722
|
cross_attention_kwargs=cross_attention_kwargs,
|
723
|
+
added_cond_kwargs=added_cond_kwargs,
|
666
724
|
).sample
|
667
725
|
|
668
726
|
# perform guidance
|